<?php
/**
 * Prince VIP System - Contracts List
 * قائمة العقود
 */
$pageTitle = 'العقود';
require_once 'includes/header.php';

$db = getDB();

$statusLabels = [
    'draft' => 'مسودة',
    'pending' => 'قيد المراجعة',
    'active' => 'نشط',
    'rejected' => 'مرفوض',
    'expired' => 'منتهي'
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1"><i class="fas fa-file-contract text-primary me-2"></i>إدارة العقود</h4>
        <p class="text-muted small mb-0">عرض وإدارة جميع العقود</p>
    </div>
    <a href="contract_new.php" class="btn btn-gold">
        <i class="fas fa-plus me-1"></i> عقد جديد
    </a>
</div>

<!-- فلاتر البحث -->
<div class="content-card">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <input type="text" id="searchQuery" class="form-control" placeholder="🔍 بحث برقم العقد أو اسم العميل...">
            </div>
            <div class="col-md-2">
                <select id="filterStatus" class="form-select">
                    <option value="">كل الحالات</option>
                    <?php foreach ($statusLabels as $key => $label): ?>
                    <option value="<?= $key ?>"><?= $label ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select id="filterPeriod" class="form-select">
                    <option value="">كل الفترات</option>
                    <option value="month">آخر شهر</option>
                    <option value="3months">آخر 3 أشهر</option>
                    <option value="year">آخر سنة</option>
                </select>
            </div>
            <?php if (isAdmin()): ?>
            <div class="col-md-2">
                <select id="filterAgent" class="form-select">
                    <option value="">كل الوكلاء</option>
                    <?php
                    $agents = $db->query("SELECT id, full_name FROM users WHERE role = 'agent' ORDER BY full_name")->fetchAll();
                    foreach ($agents as $agent):
                    ?>
                    <option value="<?= $agent['id'] ?>"><?= clean($agent['full_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <div class="col-md-2">
                <button id="btnSearch" class="btn btn-gold w-100">
                    <i class="fas fa-search me-1"></i> بحث
                </button>
            </div>
        </div>
    </div>
</div>

<!-- جدول العقود -->
<div class="content-card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="data-table" id="contractsTable">
                <thead>
                    <tr>
                        <th>رقم العقد</th>
                        <th>العميل</th>
                        <?php if (isAdmin()): ?><th>الوكيل</th><?php endif; ?>
                        <th>رقم السيارة</th>
                        <th>السعر</th>
                        <th>تاريخ البدء</th>
                        <th>الحالة</th>
                        <th>الدفع</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody id="contractsBody">
                    <!-- يتم تحميلها بـ AJAX -->
                </tbody>
            </table>
        </div>
        <div id="paginationContainer" class="d-flex justify-content-center p-3"></div>
    </div>
</div>

<?php
$isAdminJS = isAdmin() ? 'true' : 'false';
$extraJS = <<<JS
<script>
const isAdmin = {$isAdminJS};
let currentPage = 1;

$(document).ready(function() {
    loadContracts();
    
    $('#btnSearch').on('click', function() {
        currentPage = 1;
        loadContracts();
    });
    
    $('#searchQuery').on('keyup', debounce(function() {
        currentPage = 1;
        loadContracts();
    }, 400));
    
    $('#filterStatus, #filterPeriod, #filterAgent').on('change', function() {
        currentPage = 1;
        loadContracts();
    });
});

function loadContracts(page = 1) {
    currentPage = page;
    const data = {
        action: 'list',
        search: $('#searchQuery').val(),
        status: $('#filterStatus').val(),
        period: $('#filterPeriod').val(),
        agent_id: $('#filterAgent').val() || '',
        page: page
    };
    
    $.ajax({
        url: 'ajax/contracts.php',
        method: 'POST',
        data: data,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                renderContracts(response.data, response.total, response.pages);
            }
        }
    });
}

function renderContracts(contracts, total, pages) {
    let html = '';
    const statusLabels = {draft:'مسودة', pending:'قيد المراجعة', active:'نشط', rejected:'مرفوض', expired:'منتهي'};
    
    if (contracts.length === 0) {
        const colspan = isAdmin ? 9 : 8;
        html = '<tr><td colspan="' + colspan + '" class="text-center text-muted py-5"><i class="fas fa-inbox d-block mb-2" style="font-size:2rem;opacity:0.3;"></i>لا توجد عقود</td></tr>';
    } else {
        const payLabels = {unpaid:'غير مدفوع', paid:'مدفوع', partial:'جزئي'};
        const payColors = {unpaid:'danger', paid:'success', partial:'warning'};
        contracts.forEach(function(c) {
            const ps = c.payment_status || 'unpaid';
            html += '<tr>';
            html += '<td class="fw-bold">' + c.contract_number + '</td>';
            html += '<td>' + c.client_name + '</td>';
            if (isAdmin) html += '<td class="text-muted">' + c.agent_name + '</td>';
            html += '<td>' + (c.car_number || '-') + '</td>';
            html += '<td>' + (c.price ? c.price + ' ₪' : '-') + '</td>';
            html += '<td>' + c.start_date + '</td>';
            html += '<td><span class="status-badge ' + c.status + '">' + statusLabels[c.status] + '</span></td>';
            html += '<td><span class="badge bg-' + payColors[ps] + '">' + payLabels[ps] + '</span></td>';
            html += '<td>';
            html += '<a href="contract_view.php?id=' + c.id + '" class="btn btn-sm btn-outline-gold me-1" title="عرض"><i class="fas fa-eye"></i></a>';
            if (c.status === 'active') {
                html += '<a href="policy_pdf.php?id=' + c.id + '" class="btn btn-sm btn-gold" target="_blank" title="بوليصة"><i class="fas fa-file-pdf"></i></a>';
            }
            html += '</td>';
            html += '</tr>';
        });
    }
    
    $('#contractsBody').html(html);
    
    // ترقيم الصفحات
    let pagHtml = '';
    if (pages > 1) {
        pagHtml += '<nav><ul class="pagination pagination-custom mb-0">';
        for (let i = 1; i <= pages; i++) {
            pagHtml += '<li class="page-item ' + (i === currentPage ? 'active' : '') + '">';
            pagHtml += '<a class="page-link" href="#" onclick="loadContracts(' + i + ');return false;">' + i + '</a>';
            pagHtml += '</li>';
        }
        pagHtml += '</ul></nav>';
    }
    $('#paginationContainer').html(pagHtml);
}
</script>
JS;

require_once 'includes/footer.php';
?>
