<?php
/**
 * Prince VIP System - Payments Management
 * إدارة المحاسبة والمدفوعات
 */
$pageTitle = 'المحاسبة';
require_once 'includes/header.php';

if (!isAdmin()) {
    redirect('dashboard.php');
}

$db = getDB();

// إحصائيات المدفوعات
$stats = $db->query("SELECT 
    COUNT(*) as total_contracts,
    SUM(CASE WHEN payment_status = 'paid' THEN 1 ELSE 0 END) as paid_count,
    SUM(CASE WHEN payment_status = 'unpaid' THEN 1 ELSE 0 END) as unpaid_count,
    SUM(CASE WHEN payment_status = 'partial' THEN 1 ELSE 0 END) as partial_count,
    COALESCE(SUM(CASE WHEN payment_status = 'paid' THEN price ELSE 0 END), 0) as total_paid,
    COALESCE(SUM(CASE WHEN payment_status = 'unpaid' THEN price ELSE 0 END), 0) as total_unpaid,
    COALESCE(SUM(price), 0) as total_all
    FROM contracts WHERE status != 'draft'")->fetch();

// جلب الوكلاء
$agents = $db->query("SELECT id, full_name FROM users WHERE role = 'agent' ORDER BY full_name")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1"><i class="fas fa-money-bill-wave text-success me-2"></i>المحاسبة والمدفوعات</h4>
        <p class="text-muted small mb-0">إدارة مدفوعات الوكلاء وسندات القبض</p>
    </div>
</div>

<!-- إحصائيات -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="content-card text-center p-3">
            <i class="fas fa-file-invoice-dollar text-primary mb-2" style="font-size:1.8rem;"></i>
            <h3 class="fw-bold mb-0"><?= number_format($stats['total_all']) ?> ₪</h3>
            <small class="text-muted">إجمالي المبالغ</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="content-card text-center p-3" style="border-right:3px solid #198754;">
            <i class="fas fa-check-circle text-success mb-2" style="font-size:1.8rem;"></i>
            <h3 class="fw-bold mb-0 text-success"><?= number_format($stats['total_paid']) ?> ₪</h3>
            <small class="text-muted">مدفوع (<?= $stats['paid_count'] ?> عقد)</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="content-card text-center p-3" style="border-right:3px solid #dc3545;">
            <i class="fas fa-times-circle text-danger mb-2" style="font-size:1.8rem;"></i>
            <h3 class="fw-bold mb-0 text-danger"><?= number_format($stats['total_unpaid']) ?> ₪</h3>
            <small class="text-muted">غير مدفوع (<?= $stats['unpaid_count'] ?> عقد)</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="content-card text-center p-3" style="border-right:3px solid #ffc107;">
            <i class="fas fa-exclamation-circle text-warning mb-2" style="font-size:1.8rem;"></i>
            <h3 class="fw-bold mb-0 text-warning"><?= $stats['partial_count'] ?></h3>
            <small class="text-muted">مدفوع جزئياً</small>
        </div>
    </div>
</div>

<!-- فلاتر -->
<div class="content-card">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-3">
                <select id="filterPayStatus" class="form-select">
                    <option value="">كل الحالات</option>
                    <option value="unpaid">غير مدفوع</option>
                    <option value="paid">مدفوع</option>
                    <option value="partial">مدفوع جزئياً</option>
                </select>
            </div>
            <div class="col-md-3">
                <select id="filterPayAgent" class="form-select">
                    <option value="">كل الوكلاء</option>
                    <?php foreach ($agents as $ag): ?>
                    <option value="<?= $ag['id'] ?>"><?= clean($ag['full_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <input type="text" id="filterPaySearch" class="form-control" placeholder="🔍 رقم العقد أو اسم العميل...">
            </div>
            <div class="col-md-3">
                <button id="btnPaySearch" 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">
                <thead>
                    <tr>
                        <th>رقم العقد</th>
                        <th>العميل</th>
                        <th>الوكيل</th>
                        <th>الحزمة</th>
                        <th>السعر</th>
                        <th>حالة الدفع</th>
                        <th>تاريخ الدفع</th>
                        <th>ملاحظات</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody id="paymentsBody">
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal سند القبض -->
<div class="modal fade" id="receiptModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-receipt me-2"></i>تحديث حالة الدفع / سند قبض</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="receiptContractId">
                <div class="mb-3">
                    <label class="form-label fw-bold">حالة الدفع</label>
                    <select id="receiptPayStatus" class="form-select">
                        <option value="unpaid">غير مدفوع</option>
                        <option value="paid">مدفوع</option>
                        <option value="partial">مدفوع جزئياً</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">ملاحظات / سند قبض</label>
                    <textarea id="receiptNotes" class="form-control" rows="3" placeholder="رقم سند القبض أو ملاحظات الدفع..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                <button type="button" class="btn btn-gold" onclick="savePayment()">
                    <i class="fas fa-save me-1"></i> حفظ
                </button>
            </div>
        </div>
    </div>
</div>

<?php
$extraJS = <<<'JS'
<script>
$(document).ready(function() {
    loadPayments();
    
    $('#btnPaySearch').on('click', loadPayments);
    $('#filterPayStatus, #filterPayAgent').on('change', loadPayments);
    $('#filterPaySearch').on('keyup', debounce(loadPayments, 400));
});

function loadPayments() {
    $.ajax({
        url: 'ajax/contracts.php',
        method: 'POST',
        data: {
            action: 'list',
            search: $('#filterPaySearch').val(),
            status: '',
            period: '',
            agent_id: $('#filterPayAgent').val() || '',
            page: 1
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                renderPayments(response.data);
            }
        }
    });
}

function renderPayments(contracts) {
    const payFilter = $('#filterPayStatus').val();
    const payLabels = {unpaid:'غير مدفوع', paid:'مدفوع', partial:'مدفوع جزئياً'};
    const payColors = {unpaid:'danger', paid:'success', partial:'warning'};
    let html = '';
    
    let filtered = contracts;
    if (payFilter) {
        filtered = contracts.filter(c => (c.payment_status || 'unpaid') === payFilter);
    }
    
    if (filtered.length === 0) {
        html = '<tr><td colspan="9" 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 {
        filtered.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>';
            html += '<td class="text-muted">' + c.agent_name + '</td>';
            html += '<td>' + (c.package_name || '-') + '</td>';
            html += '<td class="fw-bold">' + (c.price ? c.price + ' ₪' : '-') + '</td>';
            html += '<td><span class="badge bg-' + payColors[ps] + '">' + payLabels[ps] + '</span></td>';
            html += '<td class="small">' + (c.paid_at || '-') + '</td>';
            html += '<td class="small">' + (c.payment_notes || '-') + '</td>';
            html += '<td>';
            html += '<button class="btn btn-sm btn-outline-gold" onclick="openReceipt(' + c.id + ',\'' + ps + '\',\'' + (c.payment_notes || '').replace(/'/g, "\\'") + '\')" title="سند قبض"><i class="fas fa-receipt"></i></button>';
            html += '</td>';
            html += '</tr>';
        });
    }
    
    $('#paymentsBody').html(html);
}

function openReceipt(id, status, notes) {
    $('#receiptContractId').val(id);
    $('#receiptPayStatus').val(status);
    $('#receiptNotes').val(notes);
    new bootstrap.Modal(document.getElementById('receiptModal')).show();
}

function savePayment() {
    ajaxRequest('ajax/contracts.php', {
        action: 'update_payment',
        contract_id: $('#receiptContractId').val(),
        payment_status: $('#receiptPayStatus').val(),
        payment_notes: $('#receiptNotes').val()
    }, function(response) {
        if (response.success) {
            showAlert(response.message, 'success');
            bootstrap.Modal.getInstance(document.getElementById('receiptModal')).hide();
            loadPayments();
        } else {
            showAlert(response.message, 'danger');
        }
    });
}
</script>
JS;

require_once 'includes/footer.php';
?>
