<?php
require_once '../config/config.php';
requireLogin('admin');

$database = new Database();
$db = $database->getConnection();

$message = '';

// Handle company status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $company_id = (int)$_POST['company_id'];
    $action = $_POST['action'];
    
    if (in_array($action, ['approve', 'reject', 'delete'])) {
        try {
            if ($action === 'delete') {
                $stmt = $db->prepare("DELETE FROM companies WHERE id = ?");
                $stmt->execute([$company_id]);
                $message = 'Company deleted successfully.';
            } else {
                $status = $action === 'approve' ? 'approved' : 'rejected';
                $stmt = $db->prepare("UPDATE companies SET status = ? WHERE id = ?");
                $stmt->execute([$status, $company_id]);
                $message = 'Company status updated successfully.';
            }
        } catch (PDOException $e) {
            $message = 'Error updating company: ' . $e->getMessage();
        }
    }
}

// Get all companies with filters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

$where_conditions = [];
$params = [];

if ($status_filter) {
    $where_conditions[] = "c.status = ?";
    $params[] = $status_filter;
}

if ($search) {
    $where_conditions[] = "(c.name LIKE ? OR c.contact_person_email LIKE ? OR c.contact_person_name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

$stmt = $db->prepare("
    SELECT c.*, COUNT(cu.id) as user_count 
    FROM companies c 
    LEFT JOIN company_users cu ON c.id = cu.company_id AND cu.status = 'active'
    $where_clause 
    GROUP BY c.id 
    ORDER BY c.created_at DESC
");
$stmt->execute($params);
$companies = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Companies - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="companies.php">
                                <i class="fas fa-building me-2"></i>Manage Companies
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="candidates.php">
                                <i class="fas fa-users me-2"></i>Manage Candidates
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="categories.php">
                                <i class="fas fa-tags me-2"></i>Job Categories
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="admin-users.php">
                                <i class="fas fa-user-shield me-2"></i>Admin Users
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-building me-2"></i>Manage Companies
                        </h1>
                        <a href="add-company.php" class="btn btn-primary">
                            <i class="fas fa-plus me-1"></i>Add New Company
                        </a>
                    </div>

                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Filters -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-4">
                                    <label for="search" class="form-label">Search</label>
                                    <input type="text" class="form-control" id="search" name="search" 
                                           placeholder="Company name or email..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                <div class="col-md-3">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">All Status</option>
                                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                        <option value="approved" <?php echo $status_filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                    </select>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary me-2">
                                        <i class="fas fa-search me-1"></i>Filter
                                    </button>
                                    <a href="companies.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Companies Table -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">Companies (<?php echo count($companies); ?>)</h5>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($companies)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-building fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No companies found.</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Company</th>
                                                <th>Contact</th>
                                                <th>Status</th>
                                                <th>Registered</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($companies as $company): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="company-logo me-3">
                                                                <?php if ($company['logo']): ?>
                                                                    <img src="<?php echo UPLOAD_URL . 'logos/' . $company['logo']; ?>" 
                                                                         alt="Logo" class="company-logo">
                                                                <?php else: ?>
                                                                    <div class="company-logo bg-light d-flex align-items-center justify-content-center">
                                                                        <i class="fas fa-building text-muted"></i>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-0"><?php echo htmlspecialchars($company['name']); ?></h6>
                                                                <?php if ($company['website']): ?>
                                                                    <small class="text-muted">
                                                                        <a href="<?php echo htmlspecialchars($company['website']); ?>" target="_blank">
                                                                            <?php echo htmlspecialchars($company['website']); ?>
                                                                        </a>
                                                                    </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <div><?php echo htmlspecialchars($company['contact_person_email']); ?></div>
                                                            <small class="text-muted"><?php echo htmlspecialchars($company['contact_person_name']); ?></small>
                                                            <?php if ($company['contact_person_phone']): ?>
                                                                <br><small class="text-muted"><?php echo htmlspecialchars($company['contact_person_phone']); ?></small>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge status-<?php echo $company['status']; ?>">
                                                            <?php echo ucfirst($company['status']); ?>
                                                        </span>
                                                        <br><small class="text-muted"><?php echo $company['user_count']; ?> user<?php echo $company['user_count'] != 1 ? 's' : ''; ?></small>
                                                    </td>
                                                    <td><?php echo formatDate($company['created_at']); ?></td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <button type="button" class="btn btn-outline-primary dropdown-toggle" 
                                                                    data-bs-toggle="dropdown">
                                                                Actions
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a class="dropdown-item" href="view-company.php?id=<?php echo $company['id']; ?>">
                                                                        <i class="fas fa-eye me-2"></i>View Details
                                                                    </a>
                                                                </li>
                                                                <?php if ($company['status'] === 'pending'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="company_id" value="<?php echo $company['id']; ?>">
                                                                            <input type="hidden" name="action" value="approve">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-check me-2"></i>Approve
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="company_id" value="<?php echo $company['id']; ?>">
                                                                            <input type="hidden" name="action" value="reject">
                                                                            <button type="submit" class="dropdown-item text-warning">
                                                                                <i class="fas fa-times me-2"></i>Reject
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <form method="POST" class="d-inline" 
                                                                          onsubmit="return confirm('Are you sure you want to delete this company?')">
                                                                        <input type="hidden" name="company_id" value="<?php echo $company['id']; ?>">
                                                                        <input type="hidden" name="action" value="delete">
                                                                        <button type="submit" class="dropdown-item text-danger">
                                                                            <i class="fas fa-trash me-2"></i>Delete
                                                                        </button>
                                                                    </form>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>