<?php
/**
 * جلب مهام الفاحص
 * endpoint: GET /api/inspector/get_my_tasks.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, 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'];

$status = $_GET['status'] ?? 'all';
$page = (int)($_GET['page'] ?? 1);
$limit = (int)($_GET['limit'] ?? 10);
$offset = ($page - 1) * $limit;

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $sql = "
        SELECT 
            ir.*,
            c.brand, c.model, c.year, c.plate_number, c.vin_number,
            cl.name as client_name, cl.phone as client_phone,
            a.comments as approval_comments, a.rework_reason
        FROM inspection_requests ir
        LEFT JOIN client_cars c ON ir.car_id = c.id
        LEFT JOIN clients cl ON ir.client_id = cl.id
        LEFT JOIN approvals a ON ir.id = a.request_id
        WHERE ir.inspector_id = :inspector_id
    ";
    
    $params = [':inspector_id' => $inspectorId];
    
    if ($status !== 'all') {
        $sql .= " AND ir.status = :status";
        $params[':status'] = $status;
    }
    
    $sql .= " ORDER BY ir.created_at DESC LIMIT :limit OFFSET :offset";
    $params[':limit'] = $limit;
    $params[':offset'] = $offset;
    
    $stmt = $db->prepare($sql);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $stmt->execute();
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // جلب العدد الإجمالي
    $countSql = "
        SELECT COUNT(*) as total 
        FROM inspection_requests 
        WHERE inspector_id = :inspector_id
    ";
    $countParams = [':inspector_id' => $inspectorId];
    if ($status !== 'all') {
        $countSql .= " AND status = :status";
        $countParams[':status'] = $status;
    }
    $countStmt = $db->prepare($countSql);
    foreach ($countParams as $key => $value) {
        $countStmt->bindValue($key, $value);
    }
    $countStmt->execute();
    $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    echo json_encode([
        'success' => true,
        'tasks' => $tasks,
        'pagination' => [
            'current_page' => $page,
            'per_page' => $limit,
            'total' => (int)$total,
            'total_pages' => ceil($total / $limit)
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>