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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    updateApplicationStatus($pdo);
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

function updateApplicationStatus($pdo) {
    $data = json_decode(file_get_contents('php://input'), true);

    if (!isset($data['application_id']) || !isset($data['status'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing application_id or status']);
        return;
    }

    $validStatuses = ['New', 'Screening', 'Interview', 'Offer', 'Rejected'];
    if (!in_array($data['status'], $validStatuses)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid status']);
        return;
    }

    try {
        $pdo->beginTransaction();

        // 1. Update Application Status
        $stmt = $pdo->prepare("UPDATE applications SET status = ? WHERE id = ?");
        $stmt->execute([$data['status'], $data['application_id']]);

        // 2. If Interview and Date provided, create Interview entry
        if ($data['status'] === 'Interview' && !empty($data['scheduled_at'])) {
            $stmtInt = $pdo->prepare("INSERT INTO interviews (application_id, scheduled_at, type, status) VALUES (?, ?, 'Video', 'Scheduled')");
            $stmtInt->execute([$data['application_id'], $data['scheduled_at']]);
        }

        $pdo->commit();
        echo json_encode(['message' => 'Status updated successfully']);

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