<?php
/**
 * API: جلب قائمة الفحوصات للمشرف
 * GET /api/supervisor/endpoints/get_inspections.php
 */

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

// تضمين ملف قاعدة البيانات
require_once __DIR__ . '/../../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    // جلب الفحوصات مع معلومات إضافية
    $query = "SELECT 
                ir.id,
                ir.request_number,
                ir.inspection_number,
                ir.customer_name,
                ir.customer_phone,
                ir.customer_email,
                ir.vehicle_type,
                ir.vehicle_model,
                ir.vehicle_year,
                ir.plate_number,
                ir.inspection_type,
                ir.appointment_date,
                ir.appointment_time,
                ir.center_id,
                ir.notes,
                ir.status,
                ir.created_at,
                ir.updated_at,
                ir.inspector_id,
                ir.inspection_date,
                ir.inspection_result,
                ir.technical_notes,
                ir.rework_notes,
                (SELECT COUNT(*) FROM inspection_points WHERE inspection_id = ir.id) as points_checked,
                (SELECT SUM(CASE WHEN status = 'pass' THEN 1 ELSE 0 END) FROM inspection_points WHERE inspection_id = ir.id) as points_passed
            FROM inspection_requests_new ir
            ORDER BY ir.created_at DESC
            LIMIT 100";
    
    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $inspections = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تنسيق البيانات
    $data = [];
    foreach ($inspections as $insp) {
        $data[] = [
            'id' => $insp['id'],
            'request_number' => $insp['request_number'],
            'inspection_number' => $insp['inspection_number'] ?? $insp['request_number'],
            'client_name' => $insp['customer_name'],
            'full_name' => $insp['customer_name'],
            'customer_phone' => $insp['customer_phone'],
            'car_brand' => $insp['vehicle_type'],
            'car_model' => $insp['vehicle_model'],
            'car_year' => $insp['vehicle_year'],
            'plate_number' => $insp['plate_number'],
            'inspection_type' => $insp['inspection_type'],
            'service_name' => $insp['inspection_type'],
            'inspector_name' => $this->getInspectorName($db, $insp['inspector_id']),
            'status' => $insp['status'],
            'created_at' => $insp['created_at'],
            'appointment_date' => $insp['appointment_date'],
            'center_id' => $insp['center_id'],
            'inspection_result' => $insp['inspection_result'],
            'points_checked' => $insp['points_checked'],
            'points_passed' => $insp['points_passed'],
            'pass_percentage' => $insp['points_checked'] > 0 ? round(($insp['points_passed'] / $insp['points_checked']) * 100) : 0
        ];
    }
    
    echo json_encode([
        'success' => true,
        'data' => $data,
        'total' => count($data)
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_inspections.php: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'data' => []
    ]);
}

/**
 * الحصول على اسم الفاحص من المعرف
 */
function getInspectorName($db, $inspectorId) {
    if (!$inspectorId) return '-';
    
    try {
        $query = "SELECT full_name FROM users WHERE id = :id AND role = 'inspector'";
        $stmt = $db->prepare($query);
        $stmt->execute([':id' => $inspectorId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? $result['full_name'] : '-';
    } catch (Exception $e) {
        return '-';
    }
}
?>