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

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

require_once '../../config/database.php';

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

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit();
}

$database = new Database();
$db = $database->getConnection();

try {
    $query = "UPDATE inspection_requests SET status = :status, updated_at = NOW() WHERE request_number = :request_number";
    $stmt = $db->prepare($query);
    $result = $stmt->execute([
        ':status' => $input['status'],
        ':request_number' => $input['request_number']
    ]);
    
    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'تم تحديث حالة الطلب بنجاح'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'فشل تحديث حالة الطلب'
        ]);
    }
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}