<?php
/**
 * Prince VIP System - View Contract
 * عرض تفاصيل العقد
 */
$pageTitle = 'تفاصيل العقد';
require_once 'includes/header.php';

$db = getDB();
$contractId = (int)($_GET['id'] ?? 0);

if (!$contractId) {
    redirect('contracts.php');
}

// جلب بيانات العقد
$stmt = $db->prepare("SELECT c.*, cl.full_name as client_name, cl.id_number as client_id_number, 
                       cl.phone as client_phone, u.full_name as agent_name,
                       p.name as package_name, p.package_type, p.price as package_price
                       FROM contracts c 
                       JOIN clients cl ON c.client_id = cl.id 
                       JOIN users u ON c.agent_id = u.id 
                       LEFT JOIN packages p ON c.package_id = p.id
                       WHERE c.id = ?");
$stmt->execute([$contractId]);
$contract = $stmt->fetch();

if (!$contract) {
    redirect('contracts.php');
}

// التحقق من الصلاحية (الوكيل يرى عقوده فقط)
if (!isAdmin() && $contract['agent_id'] != $_SESSION['user_id']) {
    redirect('contracts.php');
}

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

// جلب خيارات القوائم المنسدلة للتعديل
$plateTypes = $db->query("SELECT * FROM settings_options WHERE category = 'plate_type' AND is_active = 1 ORDER BY sort_order")->fetchAll();
$classifications = $db->query("SELECT * FROM settings_options WHERE category = 'classification' AND is_active = 1 ORDER BY sort_order")->fetchAll();
$licenseTypes = $db->query("SELECT * FROM settings_options WHERE category = 'license_type' AND is_active = 1 ORDER BY sort_order")->fetchAll();
$carTypes = $db->query("SELECT * FROM settings_options WHERE category = 'car_type' AND is_active = 1 ORDER BY sort_order")->fetchAll();
$usageTypes = $db->query("SELECT * FROM settings_options WHERE category = 'usage_type' AND is_active = 1 ORDER BY sort_order")->fetchAll();
$insuranceTypes = $db->query("SELECT * FROM settings_options WHERE category = 'insurance_type' AND is_active = 1 ORDER BY sort_order")->fetchAll();
$currentYear = (int)date('Y');
?>

<div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
    <div>
        <h4 class="fw-bold mb-1">
            <i class="fas fa-file-contract text-primary me-2"></i>
            عقد رقم: <?= clean($contract['contract_number']) ?>
        </h4>
        <p class="text-muted small mb-0">
            <span class="status-badge <?= $contract['status'] ?>"><?= $statusLabels[$contract['status']] ?></span>
            <span class="me-2">تاريخ الإنشاء: <?= date('Y/m/d', strtotime($contract['created_at'])) ?></span>
        </p>
    </div>
    <div class="d-flex gap-2 flex-wrap">
        <?php if ($contract['status'] === 'active'): ?>
        <a href="policy_pdf.php?id=<?= $contract['id'] ?>" class="btn btn-gold" target="_blank">
            <i class="fas fa-file-pdf me-1"></i> تصدير البوليصة
        </a>
        <?php endif; ?>
        
        <?php if (isAdmin() && $contract['status'] === 'pending'): ?>
        <button class="btn btn-success" onclick="approveContract(<?= $contract['id'] ?>)">
            <i class="fas fa-check me-1"></i> موافقة
        </button>
        <button class="btn btn-danger" onclick="rejectContract(<?= $contract['id'] ?>)">
            <i class="fas fa-times me-1"></i> رفض
        </button>
        <?php endif; ?>
        
        <?php if (in_array($contract['status'], ['draft', 'rejected']) && ($contract['agent_id'] == $_SESSION['user_id'] || isAdmin())): ?>
        <button class="btn btn-outline-gold" onclick="enableEdit()">
            <i class="fas fa-edit me-1"></i> تعديل
        </button>
        <?php endif; ?>
        
        <a href="contracts.php" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-right me-1"></i> العودة
        </a>
    </div>
</div>

<?php if ($contract['status'] === 'rejected' && $contract['admin_notes']): ?>
<div class="alert alert-danger alert-custom mb-4">
    <i class="fas fa-exclamation-circle me-1"></i>
    <strong>سبب الرفض:</strong> <?= clean($contract['admin_notes']) ?>
</div>
<?php endif; ?>

<form id="editContractForm">
    <input type="hidden" name="contract_id" value="<?= $contract['id'] ?>">
    <div class="row">
        <div class="col-lg-8">
            <!-- معلومات العميل -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-user text-success"></i> معلومات العميل</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">الاسم الكامل</label>
                            <p class="mb-0 fw-bold"><?= clean($contract['client_name']) ?></p>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">رقم الهوية</label>
                            <p class="mb-0"><?= clean($contract['client_id_number']) ?></p>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">رقم الجوال</label>
                            <p class="mb-0"><?= clean($contract['client_phone']) ?></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- بيانات المركبة -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-car text-info"></i> تفاصيل المركبة</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">نوع النمرة</label>
                            <p class="mb-0 editable-field"><?= clean($contract['plate_type'] ?? '-') ?></p>
                            <select name="plate_type" class="form-select edit-field" style="display:none;">
                                <?php foreach ($plateTypes as $opt): ?>
                                <option value="<?= clean($opt['option_value']) ?>" <?= $contract['plate_type'] == $opt['option_value'] ? 'selected' : '' ?>><?= clean($opt['option_value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">التصنيف</label>
                            <p class="mb-0 editable-field"><?= clean($contract['classification'] ?? '-') ?></p>
                            <select name="classification" class="form-select edit-field" style="display:none;">
                                <option value="">--</option>
                                <?php foreach ($classifications as $opt): ?>
                                <option value="<?= clean($opt['option_value']) ?>" <?= $contract['classification'] == $opt['option_value'] ? 'selected' : '' ?>><?= clean($opt['option_value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">رقم السيارة</label>
                            <p class="mb-0 editable-field"><?= clean($contract['car_number'] ?? '-') ?></p>
                            <input type="text" name="car_number" class="form-control edit-field" value="<?= clean($contract['car_number'] ?? '') ?>" style="display:none;">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">نوع الترخيص</label>
                            <p class="mb-0 editable-field"><?= clean($contract['license_type'] ?? '-') ?></p>
                            <select name="license_type" class="form-select edit-field" style="display:none;">
                                <option value="">--</option>
                                <?php foreach ($licenseTypes as $opt): ?>
                                <option value="<?= clean($opt['option_value']) ?>" <?= $contract['license_type'] == $opt['option_value'] ? 'selected' : '' ?>><?= clean($opt['option_value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">نوع السيارة</label>
                            <p class="mb-0 editable-field"><?= clean($contract['car_type'] ?? '-') ?></p>
                            <select name="car_type" class="form-select edit-field" style="display:none;">
                                <?php foreach ($carTypes as $opt): ?>
                                <option value="<?= clean($opt['option_value']) ?>" <?= $contract['car_type'] == $opt['option_value'] ? 'selected' : '' ?>><?= clean($opt['option_value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">لون السيارة</label>
                            <p class="mb-0 editable-field"><?= clean($contract['car_color'] ?? '-') ?></p>
                            <input type="text" name="car_color" class="form-control edit-field" value="<?= clean($contract['car_color'] ?? '') ?>" style="display:none;">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">سنة الإنتاج</label>
                            <p class="mb-0 editable-field"><?= $contract['production_year'] ?? '-' ?></p>
                            <select name="production_year" class="form-select edit-field" style="display:none;">
                                <option value="">--</option>
                                <?php for ($y = $currentYear + 5; $y >= 1980; $y--): ?>
                                <option value="<?= $y ?>" <?= $contract['production_year'] == $y ? 'selected' : '' ?>><?= $y ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">صفة الاستخدام</label>
                            <p class="mb-0 editable-field"><?= clean($contract['usage_type'] ?? '-') ?></p>
                            <select name="usage_type" class="form-select edit-field" style="display:none;">
                                <option value="">--</option>
                                <?php foreach ($usageTypes as $opt): ?>
                                <option value="<?= clean($opt['option_value']) ?>" <?= $contract['usage_type'] == $opt['option_value'] ? 'selected' : '' ?>><?= clean($opt['option_value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">نوع التأمين</label>
                            <p class="mb-0 editable-field"><?= clean($contract['insurance_type'] ?? '-') ?></p>
                            <select name="insurance_type" class="form-select edit-field" style="display:none;">
                                <option value="">--</option>
                                <?php foreach ($insuranceTypes as $opt): ?>
                                <option value="<?= clean($opt['option_value']) ?>" <?= $contract['insurance_type'] == $opt['option_value'] ? 'selected' : '' ?>><?= clean($opt['option_value']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="fw-bold small text-muted">رقم الشاصي</label>
                            <p class="mb-0 editable-field"><?= clean($contract['chassis_number'] ?? '-') ?></p>
                            <input type="text" name="chassis_number" class="form-control edit-field" value="<?= clean($contract['chassis_number'] ?? '') ?>" maxlength="17" style="display:none;">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- التواريخ -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-calendar-alt text-warning"></i> تواريخ الاشتراك</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="fw-bold small text-muted">تاريخ البدء</label>
                            <p class="mb-0 editable-field"><?= $contract['start_date'] ?></p>
                            <input type="date" name="start_date" class="form-control edit-field" value="<?= $contract['start_date'] ?>" style="display:none;">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="fw-bold small text-muted">تاريخ الانتهاء</label>
                            <p class="mb-0 editable-field"><?= $contract['end_date'] ?></p>
                            <input type="date" name="end_date" class="form-control edit-field" value="<?= $contract['end_date'] ?>" style="display:none;">
                        </div>
                    </div>
                </div>
            </div>
            
            <?php if ($contract['notes']): ?>
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-sticky-note text-secondary"></i> ملاحظات</h5>
                </div>
                <div class="card-body">
                    <p class="mb-0"><?= nl2br(clean($contract['notes'])) ?></p>
                </div>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- القسم الجانبي -->
        <div class="col-lg-4">
            <!-- معلومات العقد -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-info-circle text-primary"></i> معلومات العقد</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">رقم العقد:</span>
                        <strong><?= clean($contract['contract_number']) ?></strong>
                    </div>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">رقم البطاقة:</span>
                        <strong><?= clean($contract['card_number'] ?? '-') ?></strong>
                    </div>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">الوكيل:</span>
                        <strong><?= clean($contract['agent_name']) ?></strong>
                    </div>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">الحالة:</span>
                        <span class="status-badge <?= $contract['status'] ?>"><?= $statusLabels[$contract['status']] ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">تاريخ الإنشاء:</span>
                        <strong><?= date('Y/m/d H:i', strtotime($contract['created_at'])) ?></strong>
                    </div>
                </div>
            </div>
            
            <!-- الحزمة والسعر -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-box-open text-warning"></i> الحزمة والسعر</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">الحزمة:</span>
                        <strong><?= !empty($contract['package_name']) ? clean($contract['package_name']) : '-' ?></strong>
                    </div>
                    <?php if (!empty($contract['package_type'])): ?>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">نوع الحزمة:</span>
                        <span class="badge bg-<?= $contract['package_type'] == 'commercial' ? 'info' : 'success' ?>">
                            <?= $contract['package_type'] == 'commercial' ? 'تجاري' : 'خصوصي' ?>
                        </span>
                    </div>
                    <?php endif; ?>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">السعر:</span>
                        <strong style="color:#DAA520;font-size:1.1rem;"><?= $contract['price'] ? number_format($contract['price'], 0) . ' ₪' : '-' ?></strong>
                    </div>
                </div>
            </div>
            
            <!-- حالة الدفع -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-money-bill-wave text-success"></i> حالة الدفع</h5>
                </div>
                <div class="card-body">
                    <?php 
                    $paymentLabels = ['unpaid' => 'غير مدفوع', 'paid' => 'مدفوع', 'partial' => 'مدفوع جزئياً'];
                    $paymentColors = ['unpaid' => 'danger', 'paid' => 'success', 'partial' => 'warning'];
                    $payStatus = $contract['payment_status'] ?? 'unpaid';
                    ?>
                    <div class="text-center mb-3">
                        <span class="badge bg-<?= $paymentColors[$payStatus] ?>" style="font-size:0.9rem;padding:8px 20px;">
                            <?= $paymentLabels[$payStatus] ?>
                        </span>
                    </div>
                    <?php if (!empty($contract['paid_at'])): ?>
                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">تاريخ الدفع:</span>
                        <strong><?= date('Y/m/d H:i', strtotime($contract['paid_at'])) ?></strong>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($contract['payment_notes'])): ?>
                    <div class="small mt-2">
                        <span class="text-muted">ملاحظات الدفع:</span>
                        <p class="mb-0 mt-1 p-2 bg-light rounded"><?= nl2br(clean($contract['payment_notes'])) ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isAdmin()): ?>
                    <hr>
                    <div class="small fw-bold mb-2">تحديث حالة الدفع:</div>
                    <select id="paymentStatus" class="form-select form-select-sm mb-2">
                        <option value="unpaid" <?= $payStatus == 'unpaid' ? 'selected' : '' ?>>غير مدفوع</option>
                        <option value="paid" <?= $payStatus == 'paid' ? 'selected' : '' ?>>مدفوع</option>
                        <option value="partial" <?= $payStatus == 'partial' ? 'selected' : '' ?>>مدفوع جزئياً</option>
                    </select>
                    <textarea id="paymentNotes" class="form-control form-control-sm mb-2" rows="2" placeholder="ملاحظات / سند قبض..."><?= clean($contract['payment_notes'] ?? '') ?></textarea>
                    <button class="btn btn-sm btn-gold w-100" onclick="updatePayment(<?= $contract['id'] ?>)">
                        <i class="fas fa-save me-1"></i> حفظ حالة الدفع
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- المرفقات -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-paperclip text-danger"></i> المرفقات</h5>
                </div>
                <div class="card-body">
                    <?php for ($i = 1; $i <= 3; $i++): ?>
                    <?php $att = $contract["attachment$i"]; ?>
                    <div class="d-flex justify-content-between align-items-center mb-2 pb-2 <?= $i < 3 ? 'border-bottom' : '' ?>">
                        <span class="small">مرفق <?= $i ?></span>
                        <?php if ($att): ?>
                        <a href="uploads/<?= $att ?>" target="_blank" class="btn btn-sm btn-outline-gold">
                            <i class="fas fa-eye me-1"></i> معاينة
                        </a>
                        <?php else: ?>
                        <span class="text-muted small">غير مرفق</span>
                        <?php endif; ?>
                    </div>
                    <?php endfor; ?>
                </div>
            </div>
            
            <!-- أزرار التعديل (مخفية بشكل افتراضي) -->
            <div id="editButtons" class="content-card" style="display:none;">
                <div class="card-body">
                    <button type="button" id="saveEdit" class="btn btn-gold w-100 mb-2">
                        <i class="fas fa-save me-1"></i> حفظ التعديلات
                    </button>
                    <button type="button" id="resubmit" class="btn btn-success w-100 mb-2">
                        <i class="fas fa-paper-plane me-1"></i> إعادة الإرسال للمراجعة
                    </button>
                    <button type="button" onclick="cancelEdit()" class="btn btn-outline-secondary w-100">
                        <i class="fas fa-times me-1"></i> إلغاء
                    </button>
                </div>
            </div>
            
            <?php if (isAdmin() && $contract['status'] === 'pending'): ?>
            <!-- ملاحظات المدير -->
            <div class="content-card">
                <div class="card-header">
                    <h5><i class="fas fa-comment-alt text-warning"></i> ملاحظات المدير</h5>
                </div>
                <div class="card-body">
                    <textarea id="adminNotes" class="form-control" rows="3" placeholder="أضف ملاحظات للوكيل..."></textarea>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</form>

<?php
$cid = $contract['id'];
$extraJS = <<<JS
<script>
function enableEdit() {
    $('.editable-field').hide();
    $('.edit-field').show();
    $('#editButtons').show();
}

function cancelEdit() {
    $('.editable-field').show();
    $('.edit-field').hide();
    $('#editButtons').hide();
}

$('#saveEdit').on('click', function() {
    const formData = new FormData($('#editContractForm')[0]);
    formData.append('action', 'update');
    ajaxUpload('ajax/contracts.php', formData, function(response) {
        if (response.success) {
            showAlert(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert(response.message, 'danger');
        }
    });
});

$('#resubmit').on('click', function() {
    const formData = new FormData($('#editContractForm')[0]);
    formData.append('action', 'resubmit');
    ajaxUpload('ajax/contracts.php', formData, function(response) {
        if (response.success) {
            showAlert(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert(response.message, 'danger');
        }
    });
});

function approveContract(id) {
    confirmAction('هل تريد الموافقة على هذا العقد؟', function() {
        ajaxRequest('ajax/contracts.php', {action:'approve', contract_id: id}, function(response) {
            if (response.success) {
                showAlert(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(response.message, 'danger');
            }
        });
    });
}

function rejectContract(id) {
    const notes = $('#adminNotes').val();
    if (!notes) {
        showAlert('يرجى إضافة سبب الرفض في ملاحظات المدير', 'warning');
        return;
    }
    confirmAction('هل تريد رفض هذا العقد؟', function() {
        ajaxRequest('ajax/contracts.php', {action:'reject', contract_id: id, admin_notes: notes}, function(response) {
            if (response.success) {
                showAlert(response.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(response.message, 'danger');
            }
        });
    });
}

function updatePayment(id) {
    const paymentStatus = $('#paymentStatus').val();
    const paymentNotes = $('#paymentNotes').val();
    ajaxRequest('ajax/contracts.php', {
        action: 'update_payment',
        contract_id: id,
        payment_status: paymentStatus,
        payment_notes: paymentNotes
    }, function(response) {
        if (response.success) {
            showAlert(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showAlert(response.message, 'danger');
        }
    });
}
</script>
JS;

require_once 'includes/footer.php';
?>
