<?php
/**
 * بدء الفحص
 * endpoint: POST /api/inspector/start_inspection.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';
require_once 'includes/auth.php';

$user = validateToken();
$inspectorId = $user['inspector_id'];
$data = json_decode(file_get_contents('php://input'), true);

$taskId = $data['task_id'] ?? 0;

if (!$taskId) {
    http_response_code(400);
    echo json_encode(['error' => 'معرف المهمة مطلوب']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // التحقق من صلاحية الفاحص للمهمة
    $stmt = $db->prepare("
        SELECT * FROM inspection_requests 
        WHERE id = :id AND inspector_id = :inspector_id AND status = 'approved'
    ");
    $stmt->execute([
        ':id' => $taskId,
        ':inspector_id' => $inspectorId
    ]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$task) {
        http_response_code(403);
        echo json_encode(['error' => 'لا يمكنك بدء هذا الفحص']);
        exit();
    }
    
    // تحديث حالة المهمة
    $stmt = $db->prepare("
        UPDATE inspection_requests 
        SET status = 'in_progress', started_at = NOW() 
        WHERE id = :id
    ");
    $stmt->execute([':id' => $taskId]);
    
    echo json_encode([
        'success' => true,
        'message' => 'تم بدء الفحص بنجاح',
        'task' => [
            'id' => $task['id'],
            'request_number' => $task['request_number'],
            'inspection_type' => $task['inspection_type'],
            'started_at' => date('Y-m-d H:i:s')
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>