<?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;
    
    if (!$request_id) {
        throw new Exception("معرف الطلب مطلوب");
    }
    
    $db->beginTransaction();
    
    // تحديث حالة الدفع
    $paymentQuery = "UPDATE payments SET payment_status = 'paid', payment_date = NOW() WHERE request_id = :request_id";
    $paymentStmt = $db->prepare($paymentQuery);
    $paymentStmt->execute(['request_id' => $request_id]);
    
    // تحديث حالة الطلب
    $requestQuery = "UPDATE inspection_requests SET status = 'pending_assignment' WHERE id = :request_id";
    $requestStmt = $db->prepare($requestQuery);
    $requestStmt->execute(['request_id' => $request_id]);
    
    // إضافة إلى الجدول الزمني
    $timelineQuery = "INSERT INTO request_timeline (request_id, status, notes, created_at) 
                      VALUES (:request_id, 'payment_confirmed', 'تم تأكيد الدفع', NOW())";
    $timelineStmt = $db->prepare($timelineQuery);
    $timelineStmt->execute(['request_id' => $request_id]);
    
    // إرسال إشعار للعميل
    $clientQuery = "SELECT c.user_id FROM inspection_requests ir
                    JOIN clients c ON ir.client_id = c.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, 'payment_received', 'تم تأكيد الدفع', :message, NOW())";
        $notifStmt = $db->prepare($notifQuery);
        $notifStmt->execute([
            'user_id' => $client['user_id'],
            'message' => 'تم تأكيد دفع العربون بنجاح'
        ]);
    }
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم تأكيد الدفع بنجاح'
    ]);
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>