<?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"><?= __('quotation_requests') ?></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>Target</th>
                    <th><?= __('date') ?></th>
                    <th><?= __('status') ?></th>
                    <th class="text-end"><?= __('actions') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($requests)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-5 text-muted"><?= __('no_data_found') ?></td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($requests as $req): ?>
                        <tr>
                            <td class="text-secondary fw-semibold">#<?= htmlspecialchars($req['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($req['customer_name']) ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge badge-light text-dark border fw-normal">
                                    <i class="fas fa-building text-secondary" style="<?= isRTL() ? 'margin-left: 4px;' : 'margin-right: 4px;' ?>"></i> <?= htmlspecialchars($req['agency_name']) ?>
                                </span>
                            </td>
                            <td>
                                <?php if($req['request_type'] === 'specific_maid'): ?>
                                    <span class="text-primary fw-bold"><i class="fas fa-user-nurse"></i> <?= htmlspecialchars($req['maid_name']) ?></span>
                                <?php else: ?>
                                    <span class="text-secondary"><i class="fas fa-search"></i> General Search</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-secondary"><?= date('M d, Y', strtotime($req['created_at'])) ?></td>
                            <td>
                                <?php if ($req['status'] === 'accepted'): ?>
                                    <span class="badge badge-success"><?= __('accepted') ?></span>
                                <?php elseif ($req['status'] === 'quoted'): ?>
                                    <span class="badge badge-info"><?= __('quoted') ?></span>
                                <?php elseif ($req['status'] === 'declined' || $req['status'] === 'expired' || $req['status'] === 'cancelled'): ?>
                                    <span class="badge badge-danger"><?= htmlspecialchars(ucfirst($req['status'])) ?></span>
                                <?php else: ?>
                                    <span class="badge badge-warning"><?= htmlspecialchars(ucfirst($req['status'])) ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-light btn-sm text-primary view-details-btn"
                                        data-id="<?= htmlspecialchars($req['id']) ?>"
                                        data-customer-name="<?= htmlspecialchars($req['customer_name']) ?>"
                                        data-agency-name="<?= htmlspecialchars($req['agency_name']) ?>"
                                        data-request-type="<?= htmlspecialchars($req['request_type']) ?>"
                                        data-maid-name="<?= htmlspecialchars($req['maid_name'] ?? '') ?>"
                                        data-service-model-name="<?= htmlspecialchars($req['service_model_name'] ?? 'Not specified') ?>"
                                        data-accommodation-type-name="<?= htmlspecialchars($req['accommodation_type_name'] ?? 'Not specified') ?>"
                                        data-preferred-nationality-name="<?= htmlspecialchars($req['preferred_nationality_name'] ?? 'No Preference') ?>"
                                        data-start-date="<?= htmlspecialchars($req['start_date'] ?? 'As soon as possible') ?>"
                                        data-duration-months="<?= htmlspecialchars($req['duration_months'] ?? 'Not specified') ?>"
                                        data-number-of-helpers="<?= htmlspecialchars($req['number_of_helpers'] ?? '1') ?>"
                                        data-additional-notes="<?= htmlspecialchars($req['additional_notes'] ?? '') ?>"
                                        data-status="<?= htmlspecialchars($req['status']) ?>"
                                        data-created-at="<?= date('M d, Y', strtotime($req['created_at'])) ?>"
                                        data-specialties='<?= json_encode($req['specialties'], JSON_HEX_APOS | JSON_HEX_QUOT) ?>'
                                        data-skills='<?= json_encode($req['skills'], 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=quotation_requests&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=quotation_requests&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=quotation_requests&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 Request Details Modal -->
<div class="modal fade" id="requestDetailsModal" tabindex="-1" aria-labelledby="requestDetailsModalLabel" 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, #4f46e5, #06b6d4); position: relative;">
                <div class="position-absolute" style="top: 20px; <?= isRTL() ? 'left: 20px;' : 'right: 20px;' ?>">
                    <span id="modalRequestStatus" 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 Request #<span id="modalRequestId"></span></h4>
                    <p class="text-white-50 small mb-0">Submitted on: <span id="modalRequestCreated"></span></p>
                </div>
            </div>

            <div class="modal-body p-4">
                <div class="row g-4">
                    <!-- Left Column - Parties involved -->
                    <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-primary"></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="modalAgencyName"></strong>
                                </div>
                                <div class="mb-0">
                                    <span class="text-secondary small d-block">Target Resource</span>
                                    <span class="fw-bold" id="modalTargetResource"></span>
                                </div>
                            </div>
                        </div>

                        <div>
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><i class="fas fa-clipboard-list text-primary"></i> Requirements & Scope</h6>
                            <div class="card bg-light border-0 rounded-3 p-3">
                                <div class="row g-2">
                                    <div class="col-6 mb-2">
                                        <span class="text-secondary small d-block">Number of Helpers</span>
                                        <strong class="text-dark" id="modalHelpersCount"></strong>
                                    </div>
                                    <div class="col-6 mb-2">
                                        <span class="text-secondary small d-block">Preferred Nationality</span>
                                        <strong class="text-dark" id="modalNationality"></strong>
                                    </div>
                                    <div class="col-6 mb-2">
                                        <span class="text-secondary small d-block">Accommodation</span>
                                        <strong class="text-dark" id="modalServiceModel"></strong>
                                    </div>
                                    <div class="col-6">
                                        <span class="text-secondary small d-block">Start Date</span>
                                        <strong class="text-dark" id="modalStartDate"></strong>
                                    </div>
                                    <div class="col-6">
                                        <span class="text-secondary small d-block">Duration</span>
                                        <strong class="text-dark" id="modalDuration"></strong>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column - Specialties, Skills, and 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-tags text-primary"></i> Preferences & Skills</h6>
                            <div class="card bg-light border-0 rounded-3 p-3">
                                <div class="mb-3">
                                    <span class="text-secondary small d-block mb-1">Specialized Skills (Specialties)</span>
                                    <div id="modalSpecialtiesContainer" class="d-flex flex-wrap gap-1"></div>
                                </div>
                                <div class="mb-0">
                                    <span class="text-secondary small d-block mb-1">Additional Skills</span>
                                    <div id="modalSkillsContainer" class="d-flex flex-wrap gap-1"></div>
                                </div>
                            </div>
                        </div>

                        <div>
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><i class="fas fa-comment-alt text-primary"></i> Customer Notes</h6>
                            <div class="card border-0 rounded-3 p-3 text-dark italic-quote" style="background-color: #fef08a; border-left: 4px solid #eab308 !important;">
                                <p id="modalAdditionalNotes" 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('requestDetailsModal');
    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 agencyName = this.getAttribute('data-agency-name');
            const requestType = this.getAttribute('data-request-type');
            const maidName = this.getAttribute('data-maid-name');
            const serviceModel = this.getAttribute('data-service-model-name');
            const accommodation = this.getAttribute('data-accommodation-type-name');
            const nationality = this.getAttribute('data-preferred-nationality-name');
            const startDate = this.getAttribute('data-start-date');
            const duration = this.getAttribute('data-duration-months');
            const helpers = this.getAttribute('data-number-of-helpers');
            const notes = this.getAttribute('data-additional-notes');
            const status = this.getAttribute('data-status');
            const created = this.getAttribute('data-created-at');

            // Parse arrays
            let specialties = [];
            let skills = [];
            try {
                specialties = JSON.parse(this.getAttribute('data-specialties')) || [];
            } catch (e) { console.error(e); }
            try {
                skills = JSON.parse(this.getAttribute('data-skills')) || [];
            } catch (e) { console.error(e); }

            // Populate text elements
            document.getElementById('modalRequestId').innerText = id;
            document.getElementById('modalRequestCreated').innerText = created;
            document.getElementById('modalCustomerName').innerText = customerName;
            document.getElementById('modalAgencyName').innerText = agencyName;
            document.getElementById('modalHelpersCount').innerText = helpers;
            document.getElementById('modalNationality').innerText = nationality;
            document.getElementById('modalServiceModel').innerText = serviceModel;
            document.getElementById('modalStartDate').innerText = startDate;
            document.getElementById('modalDuration').innerText = duration + ' months';

            // Target scope description
            const targetEl = document.getElementById('modalTargetResource');
            if (requestType === 'specific_maid') {
                targetEl.innerHTML = `<span class="text-primary"><i class="fas fa-user-nurse"></i> Specific Maid: ${maidName}</span>`;
            } else {
                targetEl.innerHTML = `<span class="text-secondary"><i class="fas fa-search"></i> General Agency Request</span>`;
            }

            // Customer Notes
            const notesEl = document.getElementById('modalAdditionalNotes');
            if (notes && notes.trim() !== '') {
                notesEl.innerText = `"${notes}"`;
                notesEl.parentElement.style.display = 'block';
            } else {
                notesEl.innerText = "No special notes provided.";
                notesEl.parentElement.style.display = 'block'; // Or hide: 'none'
            }

            // Status badge class mapper
            const statusBadge = document.getElementById('modalRequestStatus');
            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 === 'quoted') {
                statusBadge.classList.add('bg-info', 'text-white');
            } else if (status === 'pending') {
                statusBadge.classList.add('bg-warning', 'text-dark');
            } else if (status === 'declined' || status === 'expired' || status === 'cancelled') {
                statusBadge.classList.add('bg-danger', 'text-white');
            } else {
                statusBadge.classList.add('bg-secondary', 'text-white');
            }

            // Specialties list
            const specialtiesContainer = document.getElementById('modalSpecialtiesContainer');
            specialtiesContainer.innerHTML = '';
            if (specialties.length > 0) {
                specialties.forEach(spec => {
                    const badge = document.createElement('span');
                    badge.className = 'badge bg-primary-subtle text-primary border border-primary-subtle px-2 py-1 rounded';
                    badge.innerText = spec;
                    specialtiesContainer.appendChild(badge);
                });
            } else {
                specialtiesContainer.innerHTML = '<span class="text-muted small">None specified</span>';
            }

            // Skills list
            const skillsContainer = document.getElementById('modalSkillsContainer');
            skillsContainer.innerHTML = '';
            if (skills.length > 0) {
                skills.forEach(skill => {
                    const badge = document.createElement('span');
                    badge.className = 'badge bg-secondary-subtle text-secondary border border-secondary-subtle px-2 py-1 rounded';
                    badge.innerText = skill;
                    skillsContainer.appendChild(badge);
                });
            } else {
                skillsContainer.innerHTML = '<span class="text-muted small">None specified</span>';
            }

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

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