<?php
use App\Modules\Rentals\Models\RentalContract;
use App\Modules\Rentals\Models\RentalInvoice;
$__template->layout('Layout.main');
?>
<?php $__template->section('title'); ?><?= e($contract->contract_number) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<?php if (in_array($contract->status ?? 'draft', ['approved','active']) && can('rental.manage_contract')): ?>
<a href="/rentals/contracts/<?= (int) $contract->id ?>/invoices/create" class="btn btn-primary" style="margin-left:8px;">
    <i data-lucide="file-plus" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> فاتورة جديدة
</a>
<?php endif; ?>
<a href="/rentals" class="btn btn-outline"><i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> العودة للعقود</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php
$cStatus        = $contract->status ?? 'draft';
$depositStatus  = $contract->deposit_status ?? 'pending';
$activityTypes  = ['practice' => 'تدريب', 'competitive' => 'تنافسي'];
$timeTiers      = ['AM' => 'صباحي', 'PM' => 'مسائي'];
$lateFeeTypes   = ['none' => 'لا يوجد', 'daily' => 'يومي', 'weekly' => 'أسبوعي', 'monthly' => 'شهري'];
?>

<!-- Header -->
<div class="card" style="margin-bottom:20px;padding:20px;">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
        <div>
            <div style="margin-bottom:8px;">
                <code style="font-size:14px;background:#F0F9FF;color:#0284C7;padding:4px 12px;border-radius:4px;font-weight:600;"><?= e($contract->contract_number) ?></code>
            </div>
            <div style="font-size:14px;color:#374151;">
                <strong>الجهة:</strong> <?= $entity ? e($entity->name_ar) : '—' ?>
                &nbsp;|&nbsp;
                <strong>المرفق:</strong> <?= $facility ? e($facility->name_ar) : '—' ?>
            </div>
        </div>
        <span class="badge" style="background:<?= RentalContract::getStatusColor($cStatus) ?>15;color:<?= RentalContract::getStatusColor($cStatus) ?>;font-size:12px;padding:4px 12px;border-radius:10px;font-weight:600;">
            <?= e(RentalContract::getStatusLabel($cStatus)) ?>
        </span>
    </div>
</div>

<!-- Financial Summary -->
<div class="card" style="margin-bottom:20px;padding:0;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#0D7377;"><i data-lucide="calculator" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> الملخص المالي</h3>
    </div>
    <div style="padding:20px;display:grid;grid-template-columns:repeat(3,1fr);gap:15px;">
        <div style="background:#F9FAFB;padding:15px;border-radius:8px;text-align:center;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">إجمالي الوحدات × السعر</div>
            <div style="font-size:18px;font-weight:700;color:#374151;"><?= money((float) ($contract->subtotal ?? 0)) ?></div>
        </div>
        <?php if ((float) ($contract->discount_amount ?? 0) > 0): ?>
        <div style="background:#FEF2F2;padding:15px;border-radius:8px;text-align:center;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">خصم (<?= (float) ($contract->discount_percentage ?? 0) ?>%)</div>
            <div style="font-size:18px;font-weight:700;color:#DC2626;">-<?= money((float) ($contract->discount_amount ?? 0)) ?></div>
        </div>
        <?php endif; ?>
        <div style="background:#F9FAFB;padding:15px;border-radius:8px;text-align:center;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">صافي الإيجار</div>
            <div style="font-size:18px;font-weight:700;color:#374151;"><?= money((float) ($contract->total_amount ?? 0)) ?></div>
        </div>
        <div style="background:#F5F3FF;padding:15px;border-radius:8px;text-align:center;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">مرافق (<?= (float) ($contract->utilities_percentage ?? 0) ?>%)</div>
            <div style="font-size:18px;font-weight:700;color:#7C3AED;"><?= money((float) ($contract->utilities_amount ?? 0)) ?></div>
        </div>
        <div style="background:#FFFBEB;padding:15px;border-radius:8px;text-align:center;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">القيمة المضافة (<?= (float) ($contract->vat_percentage ?? 1) ?>%)</div>
            <div style="font-size:18px;font-weight:700;color:#D97706;"><?= money((float) ($contract->vat_amount ?? 0)) ?></div>
        </div>
        <div style="background:#0D7377;padding:15px;border-radius:8px;text-align:center;">
            <div style="font-size:12px;color:rgba(255,255,255,0.8);margin-bottom:4px;">الإجمالي الكلي</div>
            <div style="font-size:22px;font-weight:700;color:#fff;"><?= money((float) ($contract->grand_total ?? 0)) ?></div>
        </div>
    </div>

    <!-- Monthly preview row -->
    <?php
    use App\Modules\Rentals\Services\RentalInvoiceService;
    $mBase  = RentalInvoiceService::calcBase($contract);
    $mUtils = RentalInvoiceService::calcUtilities($contract, $mBase);
    $mVat   = RentalInvoiceService::calcVat($contract, $mBase + $mUtils);
    $mTotal = round($mBase + $mUtils + $mVat, 2);
    ?>
    <div style="padding:0 20px 15px;">
        <div style="background:#F0FDF4;border:1px solid #BBF7D0;border-radius:8px;padding:12px 20px;display:flex;align-items:center;gap:20px;flex-wrap:wrap;">
            <span style="font-size:13px;font-weight:600;color:#059669;">الفاتورة الشهرية:</span>
            <span style="font-size:13px;color:#374151;">إيجار <strong><?= money($mBase) ?></strong></span>
            <?php if ($mUtils > 0): ?>
            <span style="font-size:13px;color:#374151;">+ مرافق <strong><?= money($mUtils) ?></strong></span>
            <?php endif; ?>
            <span style="font-size:13px;color:#374151;">+ VAT <strong><?= money($mVat) ?></strong></span>
            <span style="font-size:14px;font-weight:700;color:#059669;">= <?= money($mTotal) ?></span>
        </div>
    </div>

    <!-- Deposit row -->
    <div style="padding:0 20px 20px;">
        <div style="background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;padding:12px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
            <span style="font-size:13px;color:#374151;">التأمين (<?= (float) ($contract->deposit_percentage ?? 0) ?>%): <strong><?= money((float) ($contract->deposit_amount ?? 0)) ?></strong></span>
            <span class="badge" style="background:<?= RentalContract::getDepositStatusColor($depositStatus) ?>15;color:<?= RentalContract::getDepositStatusColor($depositStatus) ?>;font-size:12px;padding:4px 12px;border-radius:10px;font-weight:600;">
                <?= e(RentalContract::getDepositStatusLabel($depositStatus)) ?>
            </span>
        </div>
    </div>
</div>

<!-- Info Grid -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px;">
    <div class="card" style="padding:20px;">
        <h4 style="color:#0D7377;margin:0 0 15px;">تفاصيل العقد</h4>
        <table style="width:100%;font-size:14px;">
            <tr><td style="padding:6px 0;color:#6B7280;width:45%;">تاريخ البدء</td><td><?= e($contract->start_date ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الانتهاء</td><td><?= e($contract->end_date ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">نوع النشاط</td><td><?= e($activityTypes[$contract->activity_type ?? ''] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">الفترة الزمنية</td><td><?= e($timeTiers[$contract->time_tier ?? ''] ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">التقرير الفني</td><td><?= ($contract->technical_report_submitted ?? 0) ? '<span style="color:#059669;font-weight:600;">نعم</span>' : '<span style="color:#DC2626;">لا</span>' ?></td></tr>
        </table>
    </div>
    <div class="card" style="padding:20px;">
        <h4 style="color:#0D7377;margin:0 0 15px;">الغرامات والاعتماد</h4>
        <table style="width:100%;font-size:14px;">
            <tr>
                <td style="padding:6px 0;color:#6B7280;width:45%;">نوع الغرامة</td>
                <td><?= e($lateFeeTypes[$contract->late_fee_type ?? 'none'] ?? 'لا يوجد') ?></td>
            </tr>
            <?php if (($contract->late_fee_type ?? 'none') !== 'none'): ?>
            <tr>
                <td style="padding:6px 0;color:#6B7280;">نسبة الغرامة</td>
                <td><?= (float) ($contract->late_fee_rate ?? 0) ?>%</td>
            </tr>
            <?php endif; ?>
            <tr><td style="padding:6px 0;color:#6B7280;">اعتمد بواسطة</td><td><?= e($contract->approved_by ?? '—') ?></td></tr>
            <tr><td style="padding:6px 0;color:#6B7280;">تاريخ الاعتماد</td><td><?= e($contract->approved_at ?? '—') ?></td></tr>
        </table>
        <?php if (!empty($contract->notes)): ?>
        <div style="margin-top:12px;padding-top:12px;border-top:1px solid #E5E7EB;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">ملاحظات</div>
            <p style="font-size:14px;margin:0;color:#374151;"><?= nl2br(e($contract->notes)) ?></p>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Action Buttons -->
<?php if ($cStatus === 'pending_approval' && can('rental.approve')): ?>
<div class="card" style="margin-bottom:20px;padding:20px;display:flex;align-items:center;gap:15px;background:#FFFBEB;border:1px solid #FDE68A;">
    <i data-lucide="alert-circle" style="width:20px;height:20px;color:#D97706;"></i>
    <span style="font-size:14px;color:#92400E;flex:1;">هذا العقد بانتظار الاعتماد</span>
    <form method="POST" action="/rentals/contracts/<?= (int) $contract->id ?>/approve" style="margin:0;">
        <?= \App\Core\CSRF::field() ?>
        <button type="submit" class="btn btn-primary" style="background:#059669;"><i data-lucide="check" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> اعتماد العقد</button>
    </form>
</div>
<?php endif; ?>

<?php if (in_array($cStatus, ['approved', 'active']) && $depositStatus === 'pending' && can('rental.manage_deposit')): ?>
<div class="card" style="margin-bottom:20px;padding:20px;display:flex;align-items:center;gap:15px;background:#F0FDF4;border:1px solid #BBF7D0;">
    <i data-lucide="banknote" style="width:20px;height:20px;color:#059669;"></i>
    <span style="font-size:14px;color:#166534;flex:1;">التأمين قيد التحصيل</span>
    <form method="POST" action="/rentals/contracts/<?= (int) $contract->id ?>/deposit/collect" style="margin:0;display:flex;gap:8px;align-items:center;">
        <?= \App\Core\CSRF::field() ?>
        <input type="number" name="payment_id" class="form-input" placeholder="رقم الدفعة" required style="width:150px;">
        <button type="submit" class="btn btn-primary">تحصيل التأمين</button>
    </form>
</div>
<?php endif; ?>

<?php if ($depositStatus === 'collected' && can('rental.manage_deposit')): ?>
<div class="card" style="margin-bottom:20px;padding:20px;display:flex;align-items:center;gap:15px;background:#EFF6FF;border:1px solid #BFDBFE;">
    <i data-lucide="undo-2" style="width:20px;height:20px;color:#0284C7;"></i>
    <span style="font-size:14px;color:#1E40AF;flex:1;">تم تحصيل التأمين — يمكنك استرداد المبلغ</span>
    <form method="POST" action="/rentals/contracts/<?= (int) $contract->id ?>/deposit/refund" style="margin:0;">
        <?= \App\Core\CSRF::field() ?>
        <button type="submit" class="btn btn-outline" style="color:#0284C7;border-color:#0284C7;">استرداد التأمين</button>
    </form>
</div>
<?php endif; ?>

<!-- Invoices Table -->
<div class="card" style="margin-bottom:20px;padding:0;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;">
        <h3 style="margin:0;color:#1A1A2E;"><i data-lucide="receipt" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> الفواتير</h3>
        <?php if (in_array($cStatus, ['approved','active']) && can('rental.manage_contract')): ?>
        <a href="/rentals/contracts/<?= (int) $contract->id ?>/invoices/create" class="btn btn-primary" style="font-size:13px;padding:6px 12px;">+ فاتورة جديدة</a>
        <?php endif; ?>
    </div>
    <?php if (!empty($invoices)): ?>
    <div style="overflow-x:auto;">
        <table style="width:100%;border-collapse:collapse;font-size:14px;">
            <thead>
                <tr style="background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                    <th style="padding:12px 16px;text-align:right;">رقم الفاتورة</th>
                    <th style="padding:12px 16px;text-align:right;">الفترة</th>
                    <th style="padding:12px 16px;text-align:right;">الاستحقاق</th>
                    <th style="padding:12px 16px;text-align:left;">إيجار</th>
                    <th style="padding:12px 16px;text-align:left;">مرافق</th>
                    <th style="padding:12px 16px;text-align:left;">VAT</th>
                    <th style="padding:12px 16px;text-align:left;">غرامة</th>
                    <th style="padding:12px 16px;text-align:left;">الإجمالي</th>
                    <th style="padding:12px 16px;text-align:center;">الحالة</th>
                    <th style="padding:12px 16px;text-align:center;">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($invoices as $inv):
                    $inv = (object) $inv;
                    $iStatus = $inv->status ?? 'unpaid';
                    $iColor  = RentalInvoice::getStatusColor($iStatus);
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 16px;"><a href="/rentals/invoices/<?= (int) $inv->id ?>" style="color:#0D7377;font-weight:600;"><?= e($inv->invoice_number ?? '') ?></a></td>
                    <td style="padding:10px 16px;font-size:12px;"><?= e($inv->period_start ?? '') ?> — <?= e($inv->period_end ?? '') ?></td>
                    <td style="padding:10px 16px;"><?= e($inv->due_date ?? '') ?></td>
                    <td style="padding:10px 16px;"><?= money((float) ($inv->base_amount ?? 0)) ?></td>
                    <td style="padding:10px 16px;"><?= money((float) ($inv->utilities_amount ?? 0)) ?></td>
                    <td style="padding:10px 16px;"><?= money((float) ($inv->vat_amount ?? 0)) ?></td>
                    <td style="padding:10px 16px;color:#DC2626;"><?= money((float) ($inv->late_fee_amount ?? 0)) ?></td>
                    <td style="padding:10px 16px;font-weight:700;"><?= money((float) ($inv->total_amount ?? 0)) ?></td>
                    <td style="padding:10px 16px;text-align:center;">
                        <span class="badge" style="background:<?= $iColor ?>15;color:<?= $iColor ?>;font-size:12px;padding:3px 10px;border-radius:10px;font-weight:600;">
                            <?= e(RentalInvoice::getStatusLabel($iStatus)) ?>
                        </span>
                    </td>
                    <td style="padding:10px 16px;text-align:center;">
                        <a href="/rentals/invoices/<?= (int) $inv->id ?>" style="color:#0D7377;font-size:12px;">عرض</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="padding:40px 20px;text-align:center;">
        <i data-lucide="file-x" style="width:40px;height:40px;color:#D1D5DB;display:block;margin:0 auto 10px;"></i>
        <p style="color:#9CA3AF;font-size:14px;margin:0;">لا توجد فواتير بعد</p>
    </div>
    <?php endif; ?>
</div>

<!-- Bookings Table -->
<div class="card" style="padding:0;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#1A1A2E;"><i data-lucide="calendar" style="width:18px;height:18px;vertical-align:middle;margin-left:6px;"></i> الحجوزات</h3>
    </div>
    <?php if (!empty($bookings)): ?>
    <div style="overflow-x:auto;">
        <table style="width:100%;border-collapse:collapse;font-size:14px;">
            <thead>
                <tr style="background:#F9FAFB;border-bottom:2px solid #E5E7EB;">
                    <th style="padding:12px 16px;text-align:right;">التاريخ</th>
                    <th style="padding:12px 16px;text-align:right;">من</th>
                    <th style="padding:12px 16px;text-align:right;">إلى</th>
                    <th style="padding:12px 16px;text-align:center;">الحالة</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($bookings as $b):
                    $bStatus = $b['status'] ?? 'scheduled';
                    $bColors = ['scheduled'=>'#D97706','completed'=>'#059669','cancelled'=>'#DC2626','no_show'=>'#6B7280'];
                    $bLabels = ['scheduled'=>'مجدول','completed'=>'مكتمل','cancelled'=>'ملغى','no_show'=>'لم يحضر'];
                    $bColor  = $bColors[$bStatus] ?? '#6B7280';
                    $bLabel  = $bLabels[$bStatus] ?? $bStatus;
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 16px;"><?= e($b['booking_date'] ?? '') ?></td>
                    <td style="padding:10px 16px;"><?= e(substr($b['start_time'] ?? '', 0, 5)) ?></td>
                    <td style="padding:10px 16px;"><?= e(substr($b['end_time'] ?? '', 0, 5)) ?></td>
                    <td style="padding:10px 16px;text-align:center;">
                        <span class="badge" style="background:<?= $bColor ?>15;color:<?= $bColor ?>;font-size:12px;padding:3px 10px;border-radius:10px;font-weight:600;">
                            <?= e($bLabel) ?>
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="padding:40px 20px;text-align:center;">
        <i data-lucide="calendar-x" style="width:40px;height:40px;color:#D1D5DB;display:block;margin:0 auto 10px;"></i>
        <p style="color:#9CA3AF;font-size:14px;margin:0;">لا توجد حجوزات لهذا العقد</p>
    </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>
<?php $__template->endSection(); ?>
