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

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

// Handle search and filters
$search = $_GET['search'] ?? '';
// Note: status and experience_level columns don't exist in candidates table

// Build query with filters
$where_conditions = ["1=1"];
$params = [];

if ($search) {
    $where_conditions[] = "(CONCAT(first_name, ' ', last_name) LIKE ? OR email LIKE ? OR phone LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

// Removed status and experience filters as columns don't exist

$where_clause = implode(' AND ', $where_conditions);

// Get candidates with pagination
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

$stmt = $db->prepare("
    SELECT c.*, 
           COUNT(ja.id) as total_applications,
           COUNT(CASE WHEN ja.status = 'shortlisted' THEN 1 END) as shortlisted_applications,
           DATE(c.created_at) as registration_date
    FROM candidates c
    LEFT JOIN job_applications ja ON c.id = ja.candidate_id
    WHERE $where_clause
    GROUP BY c.id
    ORDER BY c.created_at DESC
    LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$candidates = $stmt->fetchAll();

// Get total count for pagination
$count_stmt = $db->prepare("SELECT COUNT(DISTINCT c.id) FROM candidates c WHERE $where_clause");
$count_stmt->execute($params);
$total_candidates = $count_stmt->fetchColumn();
$total_pages = ceil($total_candidates / $limit);

// Get candidate statistics
$stats_stmt = $db->query("
    SELECT 
        COUNT(*) as total,
        COUNT(*) as active,
        0 as inactive,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as new_this_month
    FROM candidates
");
$stats = $stats_stmt->fetch();

// Get applications statistics
$app_stats_stmt = $db->query("
    SELECT 
        COUNT(DISTINCT candidate_id) as candidates_with_applications,
        COUNT(*) as total_applications
    FROM job_applications
");
$app_stats = $app_stats_stmt->fetch();

// Actions removed - status column doesn't exist

// Status functionality removed
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Candidates Management - Admin Panel</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>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i>RecruitPro Admin
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">
                            <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="companies.php">
                            <i class="fas fa-building me-1"></i>Companies
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="candidates.php">
                            <i class="fas fa-users me-1"></i>Candidates
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="applications.php">
                            <i class="fas fa-file-alt me-1"></i>Applications
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i>Admin
                        </a>
                        <ul class="dropdown-menu">
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../auth/logout.php">Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1><i class="fas fa-users me-2"></i>Candidates Management</h1>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $stats['total']; ?></h4>
                                        <p class="mb-0">Total Candidates</p>
                                    </div>
                                    <i class="fas fa-users fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $stats['active']; ?></h4>
                                        <p class="mb-0">Active Candidates</p>
                                    </div>
                                    <i class="fas fa-user-check fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $stats['new_this_month']; ?></h4>
                                        <p class="mb-0">New This Month</p>
                                    </div>
                                    <i class="fas fa-user-plus fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $app_stats['candidates_with_applications']; ?></h4>
                                        <p class="mb-0">With Applications</p>
                                    </div>
                                    <i class="fas fa-file-alt fa-2x opacity-75"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Search Candidates</label>
                                <input type="text" class="form-control" name="search" 
                                       value="<?php echo htmlspecialchars($search); ?>" 
                                       placeholder="Name, email, or phone...">
                            </div>
                            <div class="col-md-8">
                                <!-- Additional search options can be added here -->
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="fas fa-search me-1"></i>Filter
                                </button>
                                <a href="candidates.php" class="btn btn-outline-secondary">Clear</a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Candidates List -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Candidates (<?php echo $total_candidates; ?>)</h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($candidates)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                <h5>No candidates found</h5>
                                <p class="text-muted">
                                    <?php if ($status_filter || $search || $experience_filter): ?>
                                        Try adjusting your filters or <a href="candidates.php">view all candidates</a>.
                                    <?php else: ?>
                                        No candidates have registered yet.
                                    <?php endif; ?>
                                </p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead>
                                        <tr>
                                            <th>Candidate</th>
                                            <th>Contact</th>
                                            <th>Location</th>
                                            <th>Applications</th>
                                            <th>Registered</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($candidates as $candidate): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <?php if ($candidate['profile_picture']): ?>
                                                            <img src="../uploads/profiles/<?php echo htmlspecialchars($candidate['profile_picture']); ?>" 
                                                                 alt="Profile" class="rounded-circle me-3" width="40" height="40" style="object-fit: cover;">
                                                        <?php else: ?>
                                                            <div class="bg-primary rounded-circle me-3 d-flex align-items-center justify-content-center" 
                                                                 style="width: 40px; height: 40px;">
                                                                <i class="fas fa-user text-white"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?></strong>
                                                            <br><small class="text-muted">ID: <?php echo $candidate['id']; ?></small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div>
                                                        <i class="fas fa-envelope text-muted me-1"></i>
                                                        <span><?php echo htmlspecialchars($candidate['email']); ?></span>
                                                    </div>
                                                    <?php if ($candidate['phone']): ?>
                                                        <div class="mt-1">
                                                            <i class="fas fa-phone text-muted me-1"></i>
                                                            <span><?php echo htmlspecialchars($candidate['phone']); ?></span>
                                                        </div>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($candidate['address']): ?>
                                                        <i class="fas fa-map-marker-alt text-muted me-1"></i>
                                                        <span><?php echo htmlspecialchars(substr($candidate['address'], 0, 50)); ?><?php echo strlen($candidate['address']) > 50 ? '...' : ''; ?></span>
                                                    <?php else: ?>
                                                        <span class="text-muted">Not provided</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div>
                                                        <strong><?php echo $candidate['total_applications']; ?></strong> applications
                                                    </div>
                                                    <?php if ($candidate['shortlisted_applications'] > 0): ?>
                                                        <small class="text-success">
                                                            <?php echo $candidate['shortlisted_applications']; ?> shortlisted
                                                        </small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <small class="text-muted">
                                                        <?php echo date('M j, Y', strtotime($candidate['registration_date'])); ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="../candidate/profile.php?view=<?php echo $candidate['id']; ?>" 
                                                           class="btn btn-outline-primary" title="View Profile">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="mailto:<?php echo urlencode($candidate['email']); ?>" 
                                                           class="btn btn-outline-info" title="Send Email">
                                                            <i class="fas fa-envelope"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <!-- Pagination -->
                            <?php if ($total_pages > 1): ?>
                                <div class="card-footer">
                                    <nav aria-label="Candidates pagination">
                                        <ul class="pagination justify-content-center mb-0">
                                            <?php if ($page > 1): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page-1; ?>&status=<?php echo urlencode($status_filter); ?>&experience=<?php echo urlencode($experience_filter); ?>&search=<?php echo urlencode($search); ?>">
                                                        Previous
                                                    </a>
                                                </li>
                                            <?php endif; ?>
                                            
                                            <?php for ($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo urlencode($status_filter); ?>&experience=<?php echo urlencode($experience_filter); ?>&search=<?php echo urlencode($search); ?>">
                                                        <?php echo $i; ?>
                                                    </a>
                                                </li>
                                            <?php endfor; ?>
                                            
                                            <?php if ($page < $total_pages): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page+1; ?>&status=<?php echo urlencode($status_filter); ?>&experience=<?php echo urlencode($experience_filter); ?>&search=<?php echo urlencode($search); ?>">
                                                        Next
                                                    </a>
                                                </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .dropdown-item-form {
            margin: 0;
            padding: 0;
        }
        .dropdown-item-form button {
            border: none;
            background: none;
            width: 100%;
            text-align: left;
        }
    </style>
</body>
</html>