<?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"><?= __('vendors') ?></h2>
</div>

<form action="?page=vendors&action=bulk" method="POST" id="bulkForm">
    <!-- Filters and Bulk Actions -->
    <div class="row g-3 mb-4">
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm" style="border-radius: 16px;">
                <div class="card-body p-3">
                    <div class="row g-3 align-items-center">
                        <div class="col-md-7">
                            <div class="input-group">
                                <span class="input-group-text bg-white border-end-0"
                                    style="border-radius: 10px 0 0 10px;"><i
                                        class="fas fa-search text-muted"></i></span>
                                <input type="text" name="search" class="form-control border-start-0"
                                    placeholder="<?= __('search_placeholder_vendors') ?>"
                                    value="<?= htmlspecialchars($_GET['search'] ?? '') ?>"
                                    style="border-radius: 0 10px 10px 0;">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <select name="status" class="form-select" style="border-radius: 10px;">
                                <option value=""><?= __('all_status') ?></option>
                                <option value="pending" <?= ($_GET['status'] ?? '') === 'pending' ? 'selected' : '' ?>>
                                    <?= __('pending') ?>
                                </option>
                                <option value="approved" <?= ($_GET['status'] ?? '') === 'approved' ? 'selected' : '' ?>>
                                    <?= __('approved') ?>
                                </option>
                                <option value="suspended" <?= ($_GET['status'] ?? '') === 'suspended' ? 'selected' : '' ?>>
                                    <?= __('suspended') ?>
                                </option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="button" onclick="applyFilters()" class="btn btn-primary w-100"
                                style="border-radius: 10px;"><?= __('filter') ?></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div id="bulkActionBar" class="card border-0 shadow-sm bg-primary text-white d-none"
                style="border-radius: 16px;">
                <div class="card-body p-3 d-flex align-items-center justify-content-between">
                    <span class="small fw-bold"><span id="selectedCount">0</span> <?= __('selected') ?></span>
                    <div class="d-flex gap-2">
                        <select name="bulk_action" class="form-select form-select-sm border-0"
                            style="width: auto; border-radius: 8px;">
                            <option value=""><?= __('actions') ?></option>
                            <option value="approve"><?= __('approve') ?></option>
                            <option value="suspend"><?= __('suspend') ?></option>
                        </select>
                        <button type="submit" class="btn btn-white btn-sm fw-bold px-3"
                            style="border-radius: 8px; background: white; color: var(--primary);"><?= __('apply') ?></button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="table-container">
        <div class="table-responsive">
            <table class="table align-middle">
                <thead>
                    <tr>
                        <th style="width: 40px;">
                            <input type="checkbox" class="form-check-input" id="selectAll">
                        </th>
                        <th><?= __('id') ?></th>
                        <th><?= __('agency_name') ?></th>
                        <th><?= __('email') ?></th>
                        <th><?= __('phone') ?></th>
                        <th><?= __('status') ?></th>
                        <th>Featured</th>
                        <th>Verified</th>
                        <th><?= __('joined_date') ?></th>
                        <th class="text-end"><?= __('actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($vendors)): ?>
                        <tr>
                            <td colspan="10" class="text-center py-5 text-muted"><?= __('no_data_found') ?></td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($vendors as $vendor): ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="ids[]" value="<?= $vendor['id'] ?>"
                                        class="form-check-input row-checkbox">
                                </td>
                                <td class="text-secondary fw-semibold">#<?= htmlspecialchars($vendor['id']) ?></td>
                                <td>
                                    <div class="d-flex align-items-center gap-3">
                                        <?php if (!empty($vendor['logo'])): ?>
                                            <img src="<?= htmlspecialchars($vendor['logo']) ?>" class="rounded-circle shadow-sm"
                                                width="40" height="40" style="object-fit: cover;">
                                        <?php else: ?>
                                            <div
                                                style="width: 40px; height: 40px; border-radius: 50%; background: var(--bg-main); display: flex; align-items: center; justify-content: center; font-weight: bold; color: var(--text-secondary);">
                                                    <?= strtoupper(substr($vendor['agency_name'], 0, 1)) ?>
                                            </div>
                                        <?php endif; ?>
                                        <a href="?page=vendor_documents&vendor_id=<?= $vendor['id'] ?>"
                                            class="fw-bold text-dark text-decoration-none hover-primary">
                                            <?= htmlspecialchars($vendor['agency_name']) ?>
                                        </a>
                                    </div>
                                </td>
                                <td><?= htmlspecialchars($vendor['email'] ?? 'N/A') ?></td>
                                <td dir="ltr" class="<?= isRTL() ? 'text-end' : '' ?>">
                                    <?= htmlspecialchars(($vendor['phone_code'] ?? '') . ' ' . ($vendor['phone'] ?? 'N/A')) ?>
                                </td>
                                <td>
                                    <?php if ($vendor['status'] === 'approved'): ?>
                                        <span class="badge badge-success"><?= __('approved') ?></span>
                                    <?php elseif ($vendor['status'] === 'rejected'): ?>
                                        <span class="badge badge-danger"><?= __('rejected') ?></span>
                                    <?php elseif ($vendor['status'] === 'suspended'): ?>
                                        <span class="badge badge-warning"><?= __('suspended') ?></span>
                                    <?php else: ?>
                                        <span class="badge badge-secondary"><?= __('pending') ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="?page=vendors&action=toggle_featured&id=<?= $vendor['id'] ?>" class="text-decoration-none" title="Toggle Featured">
                                        <?php if ($vendor['is_featured']): ?>
                                            <i class="fas fa-star text-warning" style="font-size: 1.25rem;"></i>
                                        <?php else: ?>
                                            <i class="far fa-star text-muted" style="font-size: 1.25rem;"></i>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td>
                                    <a href="?page=vendors&action=toggle_verified&id=<?= $vendor['id'] ?>" class="text-decoration-none" title="Toggle Verified / Insurance Coverage">
                                        <?php if ($vendor['is_verified']): ?>
                                            <i class="fas fa-check-circle text-success" style="font-size: 1.25rem;"></i>
                                        <?php else: ?>
                                            <i class="far fa-check-circle text-muted" style="font-size: 1.25rem;"></i>
                                        <?php endif; ?>
                                    </a>
                                </td>
                                <td class="text-secondary"><?= date('M d, Y', strtotime($vendor['created_at'])) ?></td>
                                <td class="text-end">
                                    <button type="button" class="btn btn-light btn-sm text-primary me-2 view-vendor-btn"
                                        data-id="<?= htmlspecialchars($vendor['id']) ?>"
                                        data-agency-name="<?= htmlspecialchars($vendor['agency_name']) ?>"
                                        data-tagline="<?= htmlspecialchars($vendor['tagline'] ?? '') ?>"
                                        data-email="<?= htmlspecialchars($vendor['email'] ?? '') ?>"
                                        data-phone="<?= htmlspecialchars(($vendor['phone_code'] ?? '') . ' ' . ($vendor['phone'] ?? '')) ?>"
                                        data-logo="<?= htmlspecialchars($vendor['logo'] ?? '') ?>"
                                        data-cover="<?= htmlspecialchars($vendor['cover_image'] ?? '') ?>"
                                        data-description="<?= htmlspecialchars($vendor['description'] ?? '') ?>"
                                        data-trade-license="<?= htmlspecialchars($vendor['trade_license_number'] ?? '') ?>"
                                        data-address="<?= htmlspecialchars($vendor['address'] ?? '') ?>"
                                        data-status="<?= htmlspecialchars($vendor['status']) ?>"
                                        data-created="<?= date('M d, Y', strtotime($vendor['created_at'])) ?>">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button type="button" class="btn btn-light btn-sm text-danger"><i
                                            class="fas fa-ban"></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=vendors&p=<?= $page - 1 ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&status=<?= urlencode($_GET['status'] ?? '') ?>"
                            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=vendors&p=<?= $i ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&status=<?= urlencode($_GET['status'] ?? '') ?>"
                                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=vendors&p=<?= $page + 1 ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&status=<?= urlencode($_GET['status'] ?? '') ?>"
                            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>

    </div>
</form>

<!-- Vendor Details Modal -->
<div class="modal fade" id="vendorDetailsModal" tabindex="-1" aria-labelledby="vendorDetailsModalLabel"
    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 id="modalCoverBanner"
                style="height: 150px; background: linear-gradient(135deg, var(--primary), #818cf8); background-size: cover; background-position: center; position: relative;">
                <!-- Status Badge top-right -->
                <div class="position-absolute" style="top: 15px; <?= isRTL() ? 'left: 20px;' : 'right: 20px;' ?>">
                    <span id="modalVendorStatus" class="badge px-3 py-2 rounded-pill fw-bold"></span>
                </div>
            </div>

            <div class="modal-body p-4" style="position: relative;">
                <!-- Logo overlaying banner -->
                <div class="d-flex align-items-end mb-4" style="margin-top: -75px;">
                    <div class="bg-white p-1 rounded-circle shadow"
                        style="width: 100px; height: 100px; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                        <img id="modalVendorLogo" src="" alt="Logo" class="rounded-circle img-fluid"
                            style="width: 100%; height: 100%; object-fit: cover;">
                        <div id="modalVendorLogoFallback" class="rounded-circle text-white fw-bold d-none"
                            style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 32px;">
                        </div>
                    </div>
                    <div class="ms-3 mb-2">
                        <h4 id="modalVendorName" class="fw-bold mb-1 text-dark"></h4>
                        <p id="modalVendorTagline" class="text-secondary small mb-0"></p>
                    </div>
                </div>

                <div class="row g-4">
                    <!-- Left Column - Details -->
                    <div class="col-md-7">
                        <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><?= __('description') ?></h6>
                        <p id="modalVendorDescription" class="text-dark mb-4" style="line-height: 1.6;"></p>

                        <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><?= __('contact_information') ?>
                        </h6>
                        <div class="d-flex flex-column gap-3">
                            <div class="d-flex align-items-center gap-3">
                                <div class="bg-light text-primary rounded-circle d-flex align-items-center justify-content-center"
                                    style="width: 36px; height: 36px;">
                                    <i class="fas fa-envelope"></i>
                                </div>
                                <div>
                                    <div class="text-secondary small"><?= __('email') ?></div>
                                    <div id="modalVendorEmail" class="fw-semibold text-dark"></div>
                                </div>
                            </div>
                            <div class="d-flex align-items-center gap-3">
                                <div class="bg-light text-primary rounded-circle d-flex align-items-center justify-content-center"
                                    style="width: 36px; height: 36px;">
                                    <i class="fas fa-phone"></i>
                                </div>
                                <div>
                                    <div class="text-secondary small"><?= __('phone') ?></div>
                                    <div id="modalVendorPhone" class="fw-semibold text-dark" dir="ltr"></div>
                                </div>
                            </div>
                            <div class="d-flex align-items-center gap-3">
                                <div class="bg-light text-primary rounded-circle d-flex align-items-center justify-content-center"
                                    style="width: 36px; height: 36px;">
                                    <i class="fas fa-map-marker-alt"></i>
                                </div>
                                <div>
                                    <div class="text-secondary small"><?= __('address') ?></div>
                                    <div id="modalVendorAddress" class="fw-semibold text-dark"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column - Sidebar info -->
                    <div class="col-md-5">
                        <div class="card bg-light border-0 p-3 rounded-4">
                            <h6 class="text-uppercase text-secondary fw-bold mb-3 small"><?= __('agency_overview') ?>
                            </h6>
                            <ul class="list-group list-group-flush bg-transparent">
                                <li
                                    class="list-group-item bg-transparent px-0 d-flex justify-content-between py-2.5 border-0">
                                    <span class="text-secondary small"><?= __('vendor_id') ?></span>
                                    <span id="modalVendorId" class="fw-bold text-dark"></span>
                                </li>
                                <li
                                    class="list-group-item bg-transparent px-0 d-flex justify-content-between py-2.5 border-bottom border-light">
                                    <span class="text-secondary small"><?= __('trade_license') ?></span>
                                    <span id="modalVendorLicense" class="fw-bold text-dark"></span>
                                </li>
                                <li
                                    class="list-group-item bg-transparent px-0 d-flex justify-content-between py-2.5 border-0">
                                    <span class="text-secondary small"><?= __('joined_date') ?></span>
                                    <span id="modalVendorCreated" class="fw-bold text-dark"></span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 p-4 pt-0 d-flex justify-content-between align-items-center">
                <div class="d-flex gap-2">
                    <a id="btnApproveVendor" href="" class="btn btn-success rounded-pill px-3 py-1.5 small text-white"
                        onclick="return confirm('Approve this vendor?')"><i class="fas fa-check-circle me-1"></i>
                        Approve</a>
                    <a id="btnSuspendVendor" href="" class="btn btn-warning rounded-pill px-3 py-1.5 small text-dark"
                        onclick="return confirm('Suspend this vendor?')"><i class="fas fa-ban me-1"></i> Suspend</a>
                    <a id="btnRejectVendor" href="" class="btn btn-danger rounded-pill px-3 py-1.5 small text-dark"
                        onclick="return confirm('Reject this vendor?')"><i class="fas fa-times-circle me-1"></i>
                        Reject</a>
                    <a id="btnPendingVendor" href="" class="btn btn-secondary rounded-pill px-3 py-1.5 small text-dark"
                        onclick="return confirm('Reset this vendor to Pending?')"><i class="fas fa-clock me-1"></i> Set
                        Pending</a>
                </div>
                <button type="button" class="btn btn-secondary rounded-pill px-4"
                    data-bs-dismiss="modal"><?= __('close') ?></button>
            </div>
        </div>
    </div>
</div>

<script>
    function applyFilters() {
        const search = document.querySelector('input[name="search"]').value;
        const status = document.querySelector('select[name="status"]').value;
        window.location.href = `?page=vendors&search=${encodeURIComponent(search)}&status=${encodeURIComponent(status)}`;
    }

    document.getElementById('selectAll').addEventListener('change', function () {
        const checkboxes = document.querySelectorAll('.row-checkbox');
        checkboxes.forEach(cb => cb.checked = this.checked);
        toggleBulkActions();
    });

    document.querySelectorAll('.row-checkbox').forEach(cb => {
        cb.addEventListener('change', toggleBulkActions);
    });

    function toggleBulkActions() {
        const checked = document.querySelectorAll('.row-checkbox:checked').length;
        const bar = document.getElementById('bulkActionBar');
        const count = document.getElementById('selectedCount');

        if (checked > 0) {
            bar.classList.remove('d-none');
            count.innerText = checked;
        } else {
            bar.classList.add('d-none');
        }
    }

    // Vendor Details Modal Handler
    document.querySelectorAll('.view-vendor-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-agency-name');
            const tagline = this.getAttribute('data-tagline');
            const email = this.getAttribute('data-email');
            const phone = this.getAttribute('data-phone');
            const logo = this.getAttribute('data-logo');
            const cover = this.getAttribute('data-cover');
            const description = this.getAttribute('data-description');
            const tradeLicense = this.getAttribute('data-trade-license');
            const address = this.getAttribute('data-address');
            const status = this.getAttribute('data-status');
            const created = this.getAttribute('data-created');

            // Populate Modal Fields
            document.getElementById('modalVendorId').innerText = '#' + id;
            document.getElementById('modalVendorName').innerText = name;
            document.getElementById('modalVendorTagline').innerText = tagline || 'HelperLink Verified Agency';
            document.getElementById('modalVendorEmail').innerText = email || 'N/A';
            document.getElementById('modalVendorPhone').innerText = phone || 'N/A';
            document.getElementById('modalVendorDescription').innerText = description || <?= json_encode(__('no_description')) ?>;
            document.getElementById('modalVendorLicense').innerText = tradeLicense || 'N/A';
            document.getElementById('modalVendorAddress').innerText = address || 'N/A';
            document.getElementById('modalVendorCreated').innerText = created;

            // Cover Banner
            const coverBanner = document.getElementById('modalCoverBanner');
            if (cover) {
                coverBanner.style.backgroundImage = `url('${cover}')`;
            } else {
                coverBanner.style.backgroundImage = 'linear-gradient(135deg, var(--primary), #818cf8)';
            }

            // Logo & Fallback
            const img = document.getElementById('modalVendorLogo');
            const fallback = document.getElementById('modalVendorLogoFallback');
            if (logo) {
                img.src = logo;
                img.classList.remove('d-none');
                fallback.classList.add('d-none');
            } else {
                img.classList.add('d-none');
                fallback.innerText = name.charAt(0).toUpperCase();
                fallback.style.backgroundColor = 'var(--primary)';
                fallback.classList.remove('d-none');
            }

            // Status Badge Style
            const statusBadge = document.getElementById('modalVendorStatus');
            statusBadge.innerText = status.toUpperCase();
            statusBadge.className = 'badge px-3 py-2 rounded-pill fw-bold';
            if (status === 'approved') {
                statusBadge.classList.add('bg-success');
            } else if (status === 'suspended') {
                statusBadge.classList.add('bg-warning', 'text-dark');
            } else if (status === 'rejected') {
                statusBadge.classList.add('bg-danger');
            } else {
                statusBadge.classList.add('bg-secondary');
            }

            // Populate Action Button URLs and toggle visibility
            document.getElementById('btnApproveVendor').href = `?page=vendors&action=update_status&id=${id}&status=approved`;
            document.getElementById('btnApproveVendor').style.display = (status === 'approved') ? 'none' : 'inline-block';

            document.getElementById('btnSuspendVendor').href = `?page=vendors&action=update_status&id=${id}&status=suspended`;
            document.getElementById('btnSuspendVendor').style.display = (status === 'suspended') ? 'none' : 'inline-block';

            document.getElementById('btnRejectVendor').href = `?page=vendors&action=update_status&id=${id}&status=rejected`;
            document.getElementById('btnRejectVendor').style.display = (status === 'rejected') ? 'none' : 'inline-block';

            document.getElementById('btnPendingVendor').href = `?page=vendors&action=update_status&id=${id}&status=pending`;
            document.getElementById('btnPendingVendor').style.display = (status === 'pending') ? 'none' : 'inline-block';

            // Show Modal
            const modal = new bootstrap.Modal(document.getElementById('vendorDetailsModal'));
            modal.show();
        });
    });
</script>

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