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

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    $request_id = $input['request_id'] ?? 0;
    $status = $input['status'] ?? '';
    $notes = $input['notes'] ?? '';
    $admin_id = $input['admin_id'] ?? 0;
    
    if (!$request_id || !$status) {
        throw new Exception("البيانات غير مكتملة");
    }
    
    // تحديث حالة الطلب
    $query = "UPDATE inspection_requests SET status = :status, notes = CONCAT(notes, '\n', :notes) WHERE id = :id";
    $stmt = $db->prepare($query);
    $stmt->execute([
        'id' => $request_id,
        'status' => $status,
        'notes' => "[" . date('Y-m-d H:i:s') . "] تم تحديث الحالة إلى $status" . ($notes ? " - $notes" : "")
    ]);
    
    // إضافة إلى الجدول الزمني
    $timelineQuery = "INSERT INTO request_timeline (request_id, status, notes, created_at) 
                      VALUES (:request_id, :status, :notes, NOW())";
    $timelineStmt = $db->prepare($timelineQuery);
    $timelineStmt->execute([
        'request_id' => $request_id,
        'status' => $status,
        'notes' => $notes
    ]);
    
    // إرسال إشعار للعميل
    $clientQuery = "SELECT u.id FROM inspection_requests ir
                    JOIN clients c ON ir.client_id = c.id
                    JOIN users u ON c.user_id = u.id
                    WHERE ir.id = :request_id";
    $clientStmt = $db->prepare($clientQuery);
    $clientStmt->execute(['request_id' => $request_id]);
    $client = $clientStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($client) {
        $notifQuery = "INSERT INTO notifications (user_id, type, title, message, created_at) 
                       VALUES (:user_id, 'status_update', 'تحديث حالة الطلب', :message, NOW())";
        $notifStmt = $db->prepare($notifQuery);
        $notifStmt->execute([
            'user_id' => $client['id'],
            'message' => "تم تحديث حالة الطلب إلى " . $status
        ]);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'تم تحديث الحالة بنجاح'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>