<?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);
    $inspection_id = $input['inspection_id'] ?? 0;
    $reason = $input['reason'] ?? '';
    $supervisor_id = $input['supervisor_id'] ?? 1; // من الجلسة في النظام الفعلي
    
    if (!$inspection_id || !$reason) {
        throw new Exception("معرف الفحص وسبب الرفض مطلوبان");
    }
    
    $db->beginTransaction();
    
    // تحديث حالة الطلب
    $updateQuery = "UPDATE inspection_requests 
                    SET status = 'rejected',
                        approved_by = :supervisor_id,
                        approved_at = NOW(),
                        notes = CONCAT(notes, '\n', :notes)
                    WHERE id = :inspection_id AND status = 'reviewed'";
    $updateStmt = $db->prepare($updateQuery);
    $updateStmt->execute([
        'inspection_id' => $inspection_id,
        'supervisor_id' => $supervisor_id,
        'notes' => "[" . date('Y-m-d H:i:s') . "] تم رفض نتائج الفحص. السبب: $reason"
    ]);
    
    if ($updateStmt->rowCount() === 0) {
        throw new Exception("لا يمكن رفض هذا الفحص");
    }
    
    // إعادة تعيين حالة الفاحص
    $resetQuery = "UPDATE inspectors i
                   JOIN inspection_requests ir ON i.id = ir.inspector_id
                   SET i.status = 'available'
                   WHERE ir.id = :inspection_id";
    $resetStmt = $db->prepare($resetQuery);
    $resetStmt->execute(['inspection_id' => $inspection_id]);
    
    // إضافة إلى الجدول الزمني
    $timelineQuery = "INSERT INTO request_timeline (request_id, status, notes, created_by, created_at) 
                      VALUES (:inspection_id, 'rejected', :notes, :supervisor_id, NOW())";
    $timelineStmt = $db->prepare($timelineQuery);
    $timelineStmt->execute([
        'inspection_id' => $inspection_id,
        'supervisor_id' => $supervisor_id,
        'notes' => "تم رفض نتائج الفحص. السبب: $reason"
    ]);
    
    // إشعار للفاحص
    $notifQuery = "INSERT INTO notifications (user_id, type, title, message, data, created_at)
                   SELECT i.user_id, 'danger', 'رفض نتائج الفحص', :message, :data, NOW()
                   FROM inspection_requests ir
                   JOIN inspectors i ON ir.inspector_id = i.id
                   WHERE ir.id = :inspection_id";
    $notifStmt = $db->prepare($notifQuery);
    $notifStmt->execute([
        'inspection_id' => $inspection_id,
        'message' => "تم رفض نتائج الفحص الخاص بك. السبب: $reason",
        'data' => json_encode(['inspection_id' => $inspection_id])
    ]);
    
    // تسجيل النشاط
    $logQuery = "INSERT INTO activity_logs (user_id, action, details, created_at) 
                 VALUES (:supervisor_id, 'reject_inspection', :details, NOW())";
    $logStmt = $db->prepare($logQuery);
    $logStmt->execute([
        'supervisor_id' => $supervisor_id,
        'details' => "تم رفض نتائج الفحص رقم $inspection_id. السبب: $reason"
    ]);
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم رفض نتائج الفحص بنجاح'
    ]);
    
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>