<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>طلب شراء <?= e($pr['pr_number']) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<?php if ($pr['status'] === 'draft'): ?>
<a href="/procurement/requisitions/<?= (int) $pr['id'] ?>/edit" class="btn btn-outline">
    <i data-lucide="edit" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> تعديل
</a>
<form method="POST" action="/procurement/requisitions/<?= (int) $pr['id'] ?>/submit" style="display:inline;">
    <?= csrf_field() ?>
    <button type="submit" class="btn" style="background:#D97706;color:#fff;border:none;" onclick="return confirm('هل أنت متأكد من تقديم طلب الشراء؟');">
        <i data-lucide="send" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> تقديم
    </button>
</form>
<?php endif; ?>
<?php if ($pr['status'] === 'submitted'): ?>
<?php if (can('procurement.pr.approve')): ?>
<form method="POST" action="/procurement/requisitions/<?= (int) $pr['id'] ?>/approve" style="display:inline;">
    <?= csrf_field() ?>
    <button type="submit" class="btn" style="background:#0D7377;color:#fff;border:none;" onclick="return confirm('هل أنت متأكد من اعتماد طلب الشراء؟');">
        <i data-lucide="check-circle" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> اعتماد
    </button>
</form>
<button type="button" class="btn" style="background:#FEE2E2;color:#DC2626;border:none;" onclick="document.getElementById('rejectModal').style.display='flex';">
    <i data-lucide="x-circle" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> رفض
</button>
<?php endif; ?>
<?php endif; ?>
<?php if ($pr['status'] === 'approved'): ?>
<?php if (can('procurement.pr.approve')): ?>
<button type="button" class="btn" style="background:#059669;color:#fff;border:none;" onclick="document.getElementById('convertModal').style.display='flex';">
    <i data-lucide="repeat" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> تحويل لأمر شراء
</button>
<?php endif; ?>
<?php endif; ?>
<?php if (in_array($pr['status'], ['draft', 'submitted'])): ?>
<form method="POST" action="/procurement/requisitions/<?= (int) $pr['id'] ?>/cancel" style="display:inline;">
    <?= csrf_field() ?>
    <button type="submit" class="btn" style="background:#FEE2E2;color:#DC2626;border:none;" onclick="return confirm('هل أنت متأكد من إلغاء طلب الشراء؟');">
        <i data-lucide="ban" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> إلغاء
    </button>
</form>
<?php endif; ?>
<a href="/procurement/requisitions" class="btn btn-outline"><i data-lucide="arrow-right" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> العودة للقائمة</a>
<?php $__template->endSection(); ?>

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

<?php
$statusLabels = [
    'draft' => 'مسودة', 'submitted' => 'مُقدّم', 'approved' => 'معتمد',
    'rejected' => 'مرفوض', 'converted' => 'تم التحويل', 'cancelled' => 'ملغي',
];
$statusColorMap = [
    'draft' => ['bg' => '#F3F4F6', 'color' => '#6B7280'],
    'submitted' => ['bg' => '#FFF7ED', 'color' => '#D97706'],
    'approved' => ['bg' => '#F0FDFA', 'color' => '#0D7377'],
    'rejected' => ['bg' => '#FEE2E2', 'color' => '#DC2626'],
    'converted' => ['bg' => '#ECFDF5', 'color' => '#059669'],
    'cancelled' => ['bg' => '#F3F4F6', 'color' => '#9CA3AF'],
];
$urgencyLabels = ['low' => 'منخفض', 'normal' => 'عادي', 'high' => 'عاجل', 'critical' => 'حرج'];
$urgencyColors = ['low' => '#6B7280', 'normal' => '#2563EB', 'high' => '#D97706', 'critical' => '#DC2626'];
$urgencyBgs = ['low' => '#F3F4F6', 'normal' => '#EFF6FF', 'high' => '#FFF7ED', 'critical' => '#FEE2E2'];

$st = $pr['status'] ?? 'draft';
$stColors = $statusColorMap[$st] ?? $statusColorMap['draft'];
$stLabel = $statusLabels[$st] ?? $st;
$urg = $pr['urgency'] ?? 'normal';
?>

<!-- PR Info Card -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
        <i data-lucide="clipboard-list" style="width:18px;height:18px;color:#0D7377;"></i>
        <h3 style="margin:0;color:#0D7377;font-size:15px;">بيانات طلب الشراء</h3>
    </div>
    <div style="padding:20px;">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:0;">
            <table style="width:100%;font-size:14px;">
                <tr>
                    <td style="padding:10px 0;color:#6B7280;width:40%;">رقم الطلب</td>
                    <td style="padding:10px 0;font-weight:600;">
                        <code style="font-size:12px;background:#F3F4F6;padding:2px 8px;border-radius:4px;"><?= e($pr['pr_number']) ?></code>
                    </td>
                </tr>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">مقدم الطلب</td>
                    <td style="padding:10px 0;font-weight:600;"><?= e($pr['requester_name'] ?? '—') ?></td>
                </tr>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">القسم</td>
                    <td style="padding:10px 0;"><?= e($pr['department'] ?? '—') ?></td>
                </tr>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">تاريخ الاحتياج</td>
                    <td style="padding:10px 0;"><?= e($pr['required_date'] ?? '—') ?></td>
                </tr>
            </table>
            <table style="width:100%;font-size:14px;">
                <tr>
                    <td style="padding:10px 0;color:#6B7280;width:40%;">الحالة</td>
                    <td style="padding:10px 0;">
                        <span style="display:inline-block;padding:3px 10px;border-radius:10px;font-size:12px;font-weight:600;background:<?= $stColors['bg'] ?>;color:<?= $stColors['color'] ?>;">
                            <?= e($stLabel) ?>
                        </span>
                    </td>
                </tr>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">الأولوية</td>
                    <td style="padding:10px 0;">
                        <span style="display:inline-block;padding:3px 10px;border-radius:10px;font-size:12px;font-weight:600;background:<?= $urgencyBgs[$urg] ?? '#F3F4F6' ?>;color:<?= $urgencyColors[$urg] ?? '#6B7280' ?>;">
                            <?= e($urgencyLabels[$urg] ?? $urg) ?>
                        </span>
                    </td>
                </tr>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">تاريخ الإنشاء</td>
                    <td style="padding:10px 0;"><?= e($pr['created_at'] ?? '—') ?></td>
                </tr>
                <?php if (!empty($pr['approved_at'])): ?>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">تاريخ الاعتماد</td>
                    <td style="padding:10px 0;"><?= e($pr['approved_at']) ?> — <?= e($pr['approver_name'] ?? '') ?></td>
                </tr>
                <?php endif; ?>
                <?php if (!empty($pr['rejected_at'])): ?>
                <tr>
                    <td style="padding:10px 0;color:#6B7280;">تاريخ الرفض</td>
                    <td style="padding:10px 0;"><?= e($pr['rejected_at']) ?> — <?= e($pr['rejector_name'] ?? '') ?></td>
                </tr>
                <?php endif; ?>
            </table>
        </div>

        <?php if (!empty($pr['justification'])): ?>
        <div style="margin-top:20px;padding-top:15px;border-top:1px solid #F3F4F6;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">المبرر</div>
            <div style="font-size:14px;color:#4B5563;line-height:1.7;"><?= e($pr['justification']) ?></div>
        </div>
        <?php endif; ?>

        <?php if (!empty($pr['rejection_reason'])): ?>
        <div style="margin-top:15px;padding:12px;background:#FEE2E2;border-radius:8px;">
            <div style="font-size:12px;color:#DC2626;font-weight:600;margin-bottom:4px;">سبب الرفض</div>
            <div style="font-size:14px;color:#7F1D1D;"><?= e($pr['rejection_reason']) ?></div>
        </div>
        <?php endif; ?>

        <?php if (!empty($pr['notes'])): ?>
        <div style="margin-top:15px;padding-top:15px;border-top:1px solid #F3F4F6;">
            <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">ملاحظات</div>
            <div style="font-size:14px;color:#4B5563;line-height:1.7;"><?= e($pr['notes']) ?></div>
        </div>
        <?php endif; ?>

        <?php if (!empty($pr['converted_po_id'])): ?>
        <div style="margin-top:15px;padding:12px;background:#ECFDF5;border-radius:8px;">
            <div style="font-size:12px;color:#059669;font-weight:600;margin-bottom:4px;">أمر الشراء المرتبط</div>
            <a href="/inventory/purchase-orders/<?= (int) $pr['converted_po_id'] ?>" style="color:#059669;font-weight:600;">عرض أمر الشراء #<?= (int) $pr['converted_po_id'] ?></a>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Estimated Total -->
<div class="card" style="margin-bottom:20px;padding:20px;text-align:center;background:linear-gradient(135deg, #0D737710, #0D737720);">
    <div style="font-size:14px;color:#6B7280;margin-bottom:6px;">الإجمالي التقديري</div>
    <div style="font-size:36px;font-weight:800;color:#0D7377;direction:ltr;"><?= money($pr['estimated_total'] ?? 0) ?></div>
</div>

<!-- Items Table -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
        <i data-lucide="package" style="width:18px;height:18px;color:#D97706;"></i>
        <h3 style="margin:0;color:#D97706;font-size:15px;">الأصناف المطلوبة</h3>
    </div>
    <?php if (!empty($items)): ?>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>الصنف</th>
                    <th>الوصف</th>
                    <th>الكمية</th>
                    <th>الوحدة</th>
                    <th>التكلفة التقديرية</th>
                    <th>الإجمالي</th>
                    <th>المورد المفضل</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($items as $item): ?>
                <tr>
                    <td style="font-weight:600;">
                        <?php if (!empty($item['item_name'])): ?>
                            <?= e($item['item_name']) ?>
                            <?php if (!empty($item['sku'])): ?>
                            <br><code style="font-size:11px;background:#F3F4F6;padding:2px 6px;border-radius:4px;"><?= e($item['sku']) ?></code>
                            <?php endif; ?>
                        <?php else: ?>
                            <span style="color:#6B7280;font-style:italic;">صنف حر</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-size:13px;"><?= e($item['description_ar'] ?? '—') ?></td>
                    <td style="font-weight:600;direction:ltr;text-align:left;"><?= number_format((float) ($item['quantity'] ?? 0), 3) ?></td>
                    <td style="font-size:13px;"><?= e($item['unit_of_measure'] ?? '—') ?></td>
                    <td style="direction:ltr;text-align:left;"><?= !empty($item['estimated_unit_cost']) ? money($item['estimated_unit_cost']) : '—' ?></td>
                    <td style="font-weight:700;direction:ltr;text-align:left;"><?= !empty($item['estimated_line_total']) ? money($item['estimated_line_total']) : '—' ?></td>
                    <td style="font-size:13px;"><?= e($item['preferred_supplier_name'] ?? '—') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="padding:40px 20px;text-align:center;color:#6B7280;">
        <i data-lucide="package-open" style="width:36px;height:36px;color:#D1D5DB;margin-bottom:8px;"></i>
        <p style="margin:0;">لا توجد أصناف في هذا الطلب</p>
    </div>
    <?php endif; ?>
</div>

<!-- Reject Modal -->
<?php if ($pr['status'] === 'submitted'): ?>
<div id="rejectModal" style="display:none;position:fixed;inset:0;z-index:999;background:rgba(0,0,0,0.5);align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:12px;padding:25px;width:90%;max-width:480px;">
        <h3 style="margin:0 0 15px;color:#DC2626;">رفض طلب الشراء</h3>
        <form method="POST" action="/procurement/requisitions/<?= (int) $pr['id'] ?>/reject">
            <?= csrf_field() ?>
            <div style="margin-bottom:15px;">
                <label class="form-label">سبب الرفض <span style="color:#DC2626;">*</span></label>
                <textarea name="rejection_reason" class="form-input" rows="3" required placeholder="أدخل سبب الرفض..."></textarea>
            </div>
            <div style="display:flex;gap:10px;justify-content:flex-end;">
                <button type="button" class="btn btn-outline" onclick="document.getElementById('rejectModal').style.display='none';">إلغاء</button>
                <button type="submit" class="btn" style="background:#DC2626;color:#fff;border:none;">تأكيد الرفض</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<!-- Convert to PO Modal -->
<?php if ($pr['status'] === 'approved'): ?>
<div id="convertModal" style="display:none;position:fixed;inset:0;z-index:999;background:rgba(0,0,0,0.5);align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:12px;padding:25px;width:90%;max-width:480px;">
        <h3 style="margin:0 0 15px;color:#059669;">تحويل لأمر شراء</h3>
        <form method="POST" action="/procurement/requisitions/<?= (int) $pr['id'] ?>/convert">
            <?= csrf_field() ?>
            <div style="margin-bottom:15px;">
                <label class="form-label">المورد <span style="color:#DC2626;">*</span></label>
                <select name="supplier_id" class="form-select" required id="convertSupplier"></select>
            </div>
            <div style="margin-bottom:15px;">
                <label class="form-label">المستودع <span style="color:#DC2626;">*</span></label>
                <select name="warehouse_id" class="form-select" required id="convertWarehouse"></select>
            </div>
            <div style="margin-bottom:15px;">
                <label class="form-label">تاريخ التسليم المتوقع</label>
                <input type="date" name="expected_delivery_date" class="form-input" value="<?= e($pr['required_date'] ?? '') ?>">
            </div>
            <div style="display:flex;gap:10px;justify-content:flex-end;">
                <button type="button" class="btn btn-outline" onclick="document.getElementById('convertModal').style.display='none';">إلغاء</button>
                <button type="submit" class="btn" style="background:#059669;color:#fff;border:none;">تحويل</button>
            </div>
        </form>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load suppliers and warehouses via inline data
    fetch('/api/inventory/suppliers').then(r => r.json()).then(data => {
        let sel = document.getElementById('convertSupplier');
        sel.innerHTML = '<option value="">-- اختر المورد --</option>';
        (data.data || data).forEach(s => {
            sel.innerHTML += '<option value="'+s.id+'">'+s.name_ar+'</option>';
        });
    }).catch(() => {});
    fetch('/api/inventory/warehouses').then(r => r.json()).then(data => {
        let sel = document.getElementById('convertWarehouse');
        sel.innerHTML = '<option value="">-- اختر المستودع --</option>';
        (data.data || data).forEach(w => {
            sel.innerHTML += '<option value="'+w.id+'">'+w.name_ar+'</option>';
        });
    }).catch(() => {});
});
</script>
<?php endif; ?>

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