<?php include __DIR__ . '/../../layouts/header.php'; ?>
<?php include __DIR__ . '/../../layouts/sidebar.php'; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="mb-0"><?= __('quotations') ?></h2>
</div>

<div class="table-container">
    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th><?= __('id') ?></th>
                    <th><?= __('customer') ?></th>
                    <th><?= __('vendor') ?></th>
                    <th><?= __('date') ?></th>
                    <th><?= __('total_amount') ?></th>
                    <th><?= __('status') ?></th>
                    <th class="text-end"><?= __('actions') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($quotations)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-5 text-muted"><?= __('no_data_found') ?></td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($quotations as $quotation): ?>
                        <tr>
                            <td class="text-secondary fw-semibold">#<?= htmlspecialchars($quotation['id']) ?></td>
                            <td>
                                <span class="fw-bold text-dark"><i class="fas fa-user-circle text-secondary" style="<?= isRTL() ? 'margin-left: 4px;' : 'margin-right: 4px;' ?>"></i> <?= htmlspecialchars($quotation['customer_name']) ?></span>
                            </td>
                            <td>
                                <span class="badge badge-secondary fw-normal">
                                    <i class="fas fa-building" style="<?= isRTL() ? 'margin-left: 4px;' : 'margin-right: 4px;' ?>"></i> <?= htmlspecialchars($quotation['vendor_name']) ?>
                                </span>
                            </td>
                            <td class="text-secondary"><?= date('M d, Y', strtotime($quotation['created_at'])) ?></td>
                            <td><span class="fw-bold text-dark"><?= htmlspecialchars($quotation['total_amount']) ?></span> <span class="text-secondary" style="font-size: 12px;"><?= htmlspecialchars($quotation['currency']) ?></span></td>
                            <td>
                                <?php if ($quotation['status'] === 'accepted'): ?>
                                    <span class="badge badge-success"><?= __('approved') ?></span>
                                <?php elseif ($quotation['status'] === 'declined' || $quotation['status'] === 'expired'): ?>
                                    <span class="badge badge-danger"><?= __('rejected') ?></span>
                                <?php elseif ($quotation['status'] === 'sent'): ?>
                                    <span class="badge badge-info"><?= __('sent') ?></span>
                                <?php else: ?>
                                    <span class="badge badge-secondary"><?= __('draft') ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-light btn-sm text-primary me-2 view-details-btn"
                                        data-id="<?= htmlspecialchars($quotation['id']) ?>"
                                        data-customer-name="<?= htmlspecialchars($quotation['customer_name']) ?>"
                                        data-vendor-name="<?= htmlspecialchars($quotation['vendor_name']) ?>"
                                        data-maid-name="<?= htmlspecialchars($quotation['maid_name'] ?? '') ?>"
                                        data-base-salary="<?= htmlspecialchars($quotation['base_salary']) ?>"
                                        data-visa-processing="<?= htmlspecialchars($quotation['visa_processing']) ?>"
                                        data-health-insurance="<?= htmlspecialchars($quotation['health_insurance']) ?>"
                                        data-service-fee="<?= htmlspecialchars($quotation['service_fee']) ?>"
                                        data-total-amount="<?= htmlspecialchars($quotation['total_amount']) ?>"
                                        data-currency="<?= htmlspecialchars($quotation['currency']) ?>"
                                        data-notes="<?= htmlspecialchars($quotation['notes'] ?? '') ?>"
                                        data-status="<?= htmlspecialchars($quotation['status']) ?>"
                                        data-created-at="<?= date('M d, Y', strtotime($quotation['created_at'])) ?>"
                                        data-inclusions='<?= json_encode($quotation['inclusions'], JSON_HEX_APOS | JSON_HEX_QUOT) ?>'>
                                    <i class="fas fa-eye"></i>
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="d-flex justify-content-end mt-4">
        <ul class="pagination mb-0 gap-2">
            <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                <a class="page-link rounded-circle border-0 text-secondary bg-light" href="?page=quotations&p=<?= $page - 1 ?>" style="width:40px; height:40px; display:flex; align-items:center; justify-content:center;"><i class="fas <?= isRTL() ? 'fa-chevron-right' : 'fa-chevron-left' ?>"></i></a>
            </li>
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                    <a class="page-link rounded-circle border-0 <?= $i == $page ? 'bg-primary text-white' : 'text-secondary bg-light' ?>" href="?page=quotations&p=<?= $i ?>" style="width:40px; height:40px; display:flex; align-items:center; justify-content:center;"><?= $i ?></a>
                </li>
            <?php endfor; ?>
            <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                <a class="page-link rounded-circle border-0 text-secondary bg-light" href="?page=quotations&p=<?= $page + 1 ?>" style="width:40px; height:40px; display:flex; align-items:center; justify-content:center;"><i class="fas <?= isRTL() ? 'fa-chevron-left' : 'fa-chevron-right' ?>"></i></a>
            </li>
        </ul>
    </div>
    <?php endif; ?>
</div>

<!-- Quotation Details Modal -->
<div class="modal fade" id="quotationDetailsModal" tabindex="-1" aria-labelledby="quotationDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 20px; overflow: hidden;">
            <!-- Cover Photo Banner -->
            <div style="height: 140px; background: linear-gradient(135deg, #10b981, #06b6d4); position: relative;">
                <div class="position-absolute" style="top: 20px; <?= isRTL() ? 'left: 20px;' : 'right: 20px;' ?>">
                    <span id="modalQuotationStatus" class="badge px-3 py-2 rounded-pill fw-bold"></span>
                </div>
                <div class="position-absolute" style="bottom: 15px; <?= isRTL() ? 'right: 20px;' : 'left: 20px;' ?>">
                    <h4 class="text-white fw-bold mb-0">Quotation #<span id="modalQuotationId"></span></h4>
                    <p class="text-white-50 small mb-0">Created on: <span id="modalQuotationCreated"></span></p>
                </div>
            </div>

            <div class="modal-body p-4">
                <div class="row g-4">
                    <!-- Left Column - Parties involved & Pricing -->
                    <div class="col-md-6">
                        <div class="mb-4">
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><i class="fas fa-users text-success"></i> Parties Involved</h6>
                            <div class="card bg-light border-0 rounded-3 p-3">
                                <div class="mb-2">
                                    <span class="text-secondary small d-block">Customer</span>
                                    <strong class="text-dark" id="modalCustomerName"></strong>
                                </div>
                                <div class="mb-2">
                                    <span class="text-secondary small d-block">Agency Vendor</span>
                                    <strong class="text-dark" id="modalVendorName"></strong>
                                </div>
                                <div class="mb-0">
                                    <span class="text-secondary small d-block">Selected Helper</span>
                                    <span class="fw-bold" id="modalMaidName"></span>
                                </div>
                            </div>
                        </div>

                        <div>
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><i class="fas fa-calculator text-success"></i> Pricing Details (per month)</h6>
                            <div class="card bg-light border-0 rounded-3 p-3">
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-secondary small">Base Salary:</span>
                                    <strong class="text-dark"><span id="modalBaseSalary"></span> <span id="modalCurrency1" class="small text-muted"></span></strong>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-secondary small">Visa Processing:</span>
                                    <strong class="text-dark"><span id="modalVisaProcessing"></span> <span id="modalCurrency2" class="small text-muted"></span></strong>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-secondary small">Medical/Health Insurance:</span>
                                    <strong class="text-dark"><span id="modalHealthInsurance"></span> <span id="modalCurrency3" class="small text-muted"></span></strong>
                                </div>
                                <div class="d-flex justify-content-between mb-2 border-bottom pb-2">
                                    <span class="text-secondary small">Service Fee:</span>
                                    <strong class="text-dark"><span id="modalServiceFee"></span> <span id="modalCurrency4" class="small text-muted"></span></strong>
                                </div>
                                <div class="d-flex justify-content-between pt-2">
                                    <span class="text-dark fw-bold">Total Monthly Amount:</span>
                                    <strong class="text-success fs-5"><span id="modalTotalAmount"></span> <span id="modalCurrency5" class="fs-6 fw-normal text-muted"></span></strong>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column - Inclusions & Notes -->
                    <div class="col-md-6">
                        <div class="mb-4">
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><i class="fas fa-check-double text-success"></i> Custom Inclusions</h6>
                            <div class="card bg-light border-0 rounded-3 p-3">
                                <div id="modalInclusionsContainer" class="d-flex flex-column gap-2">
                                </div>
                            </div>
                        </div>

                        <div>
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><i class="fas fa-comment-dots text-success"></i> Quotation Notes</h6>
                            <div class="card border-0 rounded-3 p-3 text-dark italic-quote" style="background-color: #e0f2fe; border-left: 4px solid #0284c7 !important;">
                                <p id="modalQuotationNotes" class="mb-0 small" style="white-space: pre-wrap; font-style: italic;"></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal-footer border-0 p-4 pt-0 d-flex justify-content-end">
                <button type="button" class="btn btn-light rounded-pill px-4" data-bs-dismiss="modal"><?= __('close') ?></button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const modalElement = document.getElementById('quotationDetailsModal');
    const bsModal = new bootstrap.Modal(modalElement);

    document.querySelectorAll('.view-details-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const id = this.getAttribute('data-id');
            const customerName = this.getAttribute('data-customer-name');
            const vendorName = this.getAttribute('data-vendor-name');
            const maidName = this.getAttribute('data-maid-name');
            const baseSalary = this.getAttribute('data-base-salary');
            const visaProcessing = this.getAttribute('data-visa-processing');
            const healthInsurance = this.getAttribute('data-health-insurance');
            const serviceFee = this.getAttribute('data-service-fee');
            const totalAmount = this.getAttribute('data-total-amount');
            const currency = this.getAttribute('data-currency');
            const notes = this.getAttribute('data-notes');
            const status = this.getAttribute('data-status');
            const created = this.getAttribute('data-created-at');

            let inclusions = [];
            try {
                inclusions = JSON.parse(this.getAttribute('data-inclusions')) || [];
            } catch (e) { console.error(e); }

            // Populate Text
            document.getElementById('modalQuotationId').innerText = id;
            document.getElementById('modalQuotationCreated').innerText = created;
            document.getElementById('modalCustomerName').innerText = customerName;
            document.getElementById('modalVendorName').innerText = vendorName;
            document.getElementById('modalMaidName').innerText = maidName ? maidName : 'No specific helper (General request)';
            
            document.getElementById('modalBaseSalary').innerText = parseFloat(baseSalary).toFixed(2);
            document.getElementById('modalVisaProcessing').innerText = parseFloat(visaProcessing).toFixed(2);
            document.getElementById('modalHealthInsurance').innerText = parseFloat(healthInsurance).toFixed(2);
            document.getElementById('modalServiceFee').innerText = parseFloat(serviceFee).toFixed(2);
            document.getElementById('modalTotalAmount').innerText = parseFloat(totalAmount).toFixed(2);

            for (let i = 1; i <= 5; i++) {
                document.getElementById('modalCurrency' + i).innerText = currency;
            }

            // Notes
            const notesEl = document.getElementById('modalQuotationNotes');
            if (notes && notes.trim() !== '') {
                notesEl.innerText = `"${notes}"`;
                notesEl.parentElement.style.display = 'block';
            } else {
                notesEl.innerText = "No specific notes provided by vendor.";
                notesEl.parentElement.style.display = 'block';
            }

            // Status Badge
            const statusBadge = document.getElementById('modalQuotationStatus');
            statusBadge.innerText = status.toUpperCase();
            statusBadge.className = 'badge px-3 py-2 rounded-pill fw-bold';
            if (status === 'accepted') {
                statusBadge.classList.add('bg-success', 'text-white');
            } else if (status === 'sent') {
                statusBadge.classList.add('bg-info', 'text-white');
            } else if (status === 'declined' || status === 'expired') {
                statusBadge.classList.add('bg-danger', 'text-white');
            } else {
                statusBadge.classList.add('bg-secondary', 'text-white');
            }

            // Inclusions Container
            const incContainer = document.getElementById('modalInclusionsContainer');
            incContainer.innerHTML = '';
            if (inclusions.length > 0) {
                inclusions.forEach(inc => {
                    const row = document.createElement('div');
                    row.className = 'd-flex align-items-center justify-content-between p-2 rounded';
                    row.style.backgroundColor = inc.is_included ? '#e8f5e9' : '#fafafa';
                    row.style.border = '1px solid ' + (inc.is_included ? '#c8e6c9' : '#e0e0e0');
                    
                    const left = document.createElement('span');
                    left.className = 'fw-semibold small text-dark';
                    left.innerText = inc.title;

                    const right = document.createElement('span');
                    if (inc.is_included) {
                        right.className = 'badge bg-success text-white small';
                        right.innerHTML = '<i class="fas fa-check"></i> Included';
                    } else {
                        right.className = 'badge bg-secondary text-white small';
                        right.innerHTML = '<i class="fas fa-times"></i> Not Included';
                    }

                    row.appendChild(left);
                    row.appendChild(right);
                    incContainer.appendChild(row);
                });
            } else {
                incContainer.innerHTML = '<span class="text-muted small">No custom inclusions configured.</span>';
            }

            bsModal.show();
        });
    });
});
</script>

<?php include __DIR__ . '/../../layouts/footer.php'; ?>
