<?php
require_once '../includes/db_connect.php';

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    if (isset($_GET['id'])) {
        getCandidateDetail($pdo, $_GET['id']);
    } else {
        getCandidatesList($pdo);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

function getCandidatesList($pdo) {
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;

    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $status = isset($_GET['status']) ? trim($_GET['status']) : '';
    $department = isset($_GET['department']) ? trim($_GET['department']) : '';
    $sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'newest';

    // Base query
    $sql = "SELECT c.*, a.status as application_status, a.match_score, j.title as job_title, j.department, j.id as job_id
            FROM candidates c 
            LEFT JOIN applications a ON c.id = a.candidate_id 
            LEFT JOIN jobs j ON a.job_id = j.id
            WHERE 1=1";
    
    $params = [];

    // Filters
    if ($search) {
        $sql .= " AND (c.full_name LIKE ? OR c.email LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    if ($status && $status !== 'All Status') {
        $sql .= " AND a.status = ?";
        $params[] = $status;
    }

    if ($department && $department !== 'All Departments') {
        $sql .= " AND j.department = ?";
        $params[] = $department;
    }

    // Sorting
    switch ($sort) {
        case 'score_high':
            $sql .= " ORDER BY a.match_score DESC";
            break;
        case 'score_low':
            $sql .= " ORDER BY a.match_score ASC";
            break;
        case 'oldest':
            $sql .= " ORDER BY c.created_at ASC";
            break;
        default: // newest
            $sql .= " ORDER BY c.created_at DESC";
            break;
    }

    // Count Total
    $countSql = str_replace("c.*, a.status as application_status, a.match_score, j.title as job_title, j.id as job_id", "COUNT(*)", $sql);
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $totalCandidates = $countStmt->fetchColumn();
    $totalPages = ceil($totalCandidates / $limit);

    // Pagination
    $sql .= " LIMIT $limit OFFSET $offset";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $candidates = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'data' => $candidates,
        'pagination' => [
            'total' => $totalCandidates,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => $totalPages
        ]
    ]);
}

function getCandidateDetail($pdo, $id) {
    // 1. Candidate Info
    $stmt = $pdo->prepare("SELECT * FROM candidates WHERE id = ?");
    $stmt->execute([$id]);
    $candidate = $stmt->fetch();

    if (!$candidate) {
        http_response_code(404);
        echo json_encode(['error' => 'Candidate not found']);
        return;
    }

    // 2. Applications History
    $stmtHist = $pdo->prepare("
        SELECT a.*, j.title as job_title, j.department, j.requirements,
               (SELECT scheduled_at FROM interviews WHERE application_id = a.id ORDER BY id DESC LIMIT 1) as scheduled_at
        FROM applications a 
        JOIN jobs j ON a.job_id = j.id 
        WHERE a.candidate_id = ?
        ORDER BY a.applied_date DESC
    ");
    $stmtHist->execute([$id]);
    $applications = $stmtHist->fetchAll();

    echo json_encode([
        'profile' => $candidate,
        'applications' => $applications
    ]);
}
?>
