<?php
// api/reject-application.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$host = 'localhost';
$dbname = 'digitals_autotester_db';
$username = 'digitals';
$password = 'bassam.bassam';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || empty($data['requestId'])) {
    echo json_encode(['success' => false, 'message' => 'بيانات غير صالحة']);
    exit;
}

try {
    // التحقق من وجود جدول job_applications
    $checkTable = $pdo->query("SHOW TABLES LIKE 'job_applications'");
    if ($checkTable->rowCount() == 0) {
        echo json_encode(['success' => false, 'message' => 'جدول طلبات التوظيف غير موجود']);
        exit;
    }
    
    $stmt = $pdo->prepare("UPDATE job_applications SET status = 'rejected', processed_at = NOW() WHERE id = ?");
    $stmt->execute([$data['requestId']]);
    
    echo json_encode([
        'success' => true,
        'message' => 'تم رفض طلب التوظيف'
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>