<?php
// تضمين ملف الاتصال بالقاعدة
include 'db.php';

// التحقق من وجود طلب بحث
if (isset($_GET['search'])) {
    $search = trim($_GET['search']);
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    if ($page < 1) $page = 1;
    $perPage = 5;
    $offset = ($page - 1) * $perPage;

    // بناء استعلام البحث
    $whereConditions = [];
    $params = [];

    if (!empty($search)) {
        $searchTerm = "%$search%";
        $whereConditions[] = "(worker_name LIKE ? OR
                              worker_job LIKE ? OR
                              worker_id LIKE ? OR
                              worker_nationality LIKE ? OR
                              provider_name LIKE ? OR
                              receiver_name LIKE ?)";
        $params = [$searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm];
    }

    $whereSQL = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

    try {
        // جلب إجمالي عدد السجلات
        $countSql = "SELECT COUNT(*) as total FROM contracts $whereSQL";
        $countStmt = $conn->prepare($countSql);
        $countStmt->execute($params);
        $totalRecords = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        $totalPages = ceil($totalRecords / $perPage);

        if ($page > $totalPages && $totalPages > 0) {
            $page = $totalPages;
            $offset = ($page - 1) * $perPage;
        }

        // استعلام لجلب البيانات مع الترقيم
        $sql = "SELECT
                    worker_name, worker_job, worker_id, worker_nationality,
                    provider_name, receiver_name, contract_summary,
                    permit_start, permit_end, work_location,
                    qr_code_path, barcode_path, id
                FROM contracts
                $whereSQL
                ORDER BY id DESC
                LIMIT $perPage OFFSET $offset";

        $stmt = $conn->prepare($sql);
        $stmt->execute($params);
        $contracts = $stmt->fetchAll();

        // تضمين كلاس التشفير
        include '../inc/SecureIdHandler.php';

        // تجهيز البيانات للإرسال كـ JSON
        $response = [
            'success' => true,
            'contracts' => [],
            'pagination' => [
                'current_page' => $page,
                'total_pages' => $totalPages,
                'total_records' => $totalRecords,
                'per_page' => $perPage
            ],
            'search_term' => $search
        ];

        foreach ($contracts as $contract) {
            $encrypted_id = SecureIdHandler::encryptId($contract['id']);

            // تحديد حالة العقد
            $status_class = '';
            $status_text = 'غير محددة';
            $current_date = date('Y-m-d');
            $permit_end = $contract['permit_end'];

            if (!empty($permit_end)) {
                if ($permit_end >= $current_date) {
                    $status_class = 'active';
                    $status_text = 'ساري';
                } else {
                    $status_class = 'expired';
                    $status_text = 'منتهي';
                }
            }

            $response['contracts'][] = [
                'id' => $contract['id'],
                'encrypted_id' => $encrypted_id,
                'worker_name' => $contract['worker_name'],
                'worker_job' => $contract['worker_job'],
                'worker_id' => $contract['worker_id'],
                'worker_nationality' => $contract['worker_nationality'],
                'provider_name' => $contract['provider_name'],
                'permit_start' => $contract['permit_start'],
                'permit_end' => $contract['permit_end'],
                'status_class' => $status_class,
                'status_text' => $status_text
            ];
        }

        header('Content-Type: application/json');
        echo json_encode($response);

    } catch (\PDOException $e) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'خطأ في جلب البيانات: ' . $e->getMessage()
        ]);
    }
} else {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'لم يتم تحديد مصطلح بحث'
    ]);
}
?>
