<?php
header('Content-Type: application/json');
require_once '../includes/db_connect.php';

$query = isset($_GET['q']) ? trim($_GET['q']) : '';

if (empty($query)) {
    echo json_encode(['status' => 'success', 'candidates' => [], 'jobs' => []]);
    exit;
}

try {
    // Search Candidates
    $stmtCandidates = $pdo->prepare("
        SELECT id, full_name as name, email, phone 
        FROM candidates 
        WHERE full_name LIKE :q OR email LIKE :q
        LIMIT 10
    ");
    $stmtCandidates->execute([':q' => "%$query%"]);
    $candidates = $stmtCandidates->fetchAll(PDO::FETCH_ASSOC);

    // Search Jobs
    $stmtJobs = $pdo->prepare("
        SELECT id, title, department, location, type, status 
        FROM jobs 
        WHERE title LIKE :q OR department LIKE :q OR location LIKE :q
        LIMIT 10
    ");
    $stmtJobs->execute([':q' => "%$query%"]);
    $jobs = $stmtJobs->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success', 
        'data' => [
            'candidates' => $candidates, 
            'jobs' => $jobs
        ]
    ]);

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