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

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

try {
    // 1. Total Applications
    $stmt = $pdo->query("SELECT COUNT(*) FROM applications");
    $totalApplications = $stmt->fetchColumn();

    // 2. Interviews Scheduled (Status = 'Scheduled')
    $stmt = $pdo->query("SELECT COUNT(*) FROM interviews WHERE status = 'Scheduled'");
    $interviewsScheduled = $stmt->fetchColumn();

    // 3. Active Jobs (Status = 'Active')
    $stmt = $pdo->query("SELECT COUNT(*) FROM jobs WHERE status = 'Active'");
    $activeJobs = $stmt->fetchColumn();

 

    // 5. Recent Applications
    $stmt = $pdo->query("
        SELECT 
            a.id as candidate_id,
            a.status,
            a.match_score,
            a.applied_date,
            c.full_name as candidate_name,
            c.email as candidate_email,
            j.title as job_title
        FROM applications a
        JOIN candidates c ON a.candidate_id = c.id
        JOIN jobs j ON a.job_id = j.id
        ORDER BY a.applied_date DESC
        LIMIT 5
    ");
    $recentApplications = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 6. Today's Interviews
    $stmt = $pdo->query("
        SELECT 
            i.id,
            i.scheduled_at,
            c.full_name as candidate_name,
            c.id as candidate_id,
            j.title as job_title
        FROM interviews i
        JOIN applications a ON i.application_id = a.id
        JOIN candidates c ON a.candidate_id = c.id
        JOIN jobs j ON a.job_id = j.id
        WHERE DATE(i.scheduled_at) = CURDATE() AND i.status = 'Scheduled'
        ORDER BY i.scheduled_at ASC
    ");
    $todaysInterviews = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'stats' => [
            'total_applications' => $totalApplications,
            'interviews_scheduled' => $interviewsScheduled,
            'active_jobs' => $activeJobs
        ],
        'recent_applications' => $recentApplications,
        'todays_interviews' => $todaysInterviews
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
