<?php
/**
 * ADMIN VENDORS MANAGEMENT PAGE
 * File: admin/vendors.php
 * Manage all vendors, approve/reject pending vendors, view statistics
 */


require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "Vendors Management";
$active_menu = "vendors";

// Get filter parameters
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = ADMIN_ITEMS_PER_PAGE;

// Initialize vendor model
$vendor_model = new Vendor();

// Build filters
$filters = [];
if (!empty($search)) {
    $filters['search'] = $search;
}
if (!empty($status)) {
    $filters['approval_status'] = $status;
}

// Get vendors
try {
    $total_vendors = $vendor_model->count($filters);
    $pagination = paginate($total_vendors, $per_page, $page);
    $vendors = $vendor_model->getAll($per_page, $pagination['offset'], $filters);
} catch (Exception $e) {
    log_message("Vendors page error: " . $e->getMessage(), 'error');
    $vendors = [];
    $pagination = ['total_pages' => 0, 'current_page' => 1];
}

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/admin/head.php';
?>

<style>
    /* Add to your main admin CSS file */
.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    color: white;
}

.status-pending {
    background: var(--warning);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-approved {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-rejected {
    background: var(--danger);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-info {
    background: var(--info);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-success {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-suspended {
    background: #6c757d;
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}
</style>

    <!-- Main Content -->
    <div class="main-content">

        <?php include '../templates/layouts/admin/header.php'; ?>
        
        <!-- Page Header -->
        <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
            <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">Vendors Management</h1>
            <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
                <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
                <span>/</span>
                <span>Vendors</span>
            </div>
        </div>
        
        <!-- Content -->
        <div style="padding: 30px;">
            
            <!-- Flash Messages -->
            <?php if ($flash_message): ?>
                <div class="alert alert-<?= $flash_message['type'] ?>">
                    <?= Security::escapeOutput($flash_message['message']) ?>
                </div>
            <?php endif; ?>
            
            <!-- Filter Section -->
            <div class="filter-section">
                <form method="GET" action="">
                    <div class="filter-row">
                        <div class="filter-group">
                            <label>Search</label>
                            <input type="text" name="search" placeholder="Search by name, email..." value="<?= Security::escapeOutput($search) ?>">
                        </div>
                        
                        <div class="filter-group">
                            <label>Status</label>
                            <select name="status" class="form-control">
                                <option value="">All Status</option>
                                <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                                <option value="approved" <?= $status === 'approved' ? 'selected' : '' ?>>Approved</option>
                                <option value="rejected" <?= $status === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                            </select>
                        </div>
                        
                        <div class="filter-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> Filter
                            </button>
                            <a href="vendors.php" class="btn btn-secondary">
                                <i class="fas fa-redo"></i> Reset
                            </a>
                        </div>
                    </div>
                </form>
            </div>
            
            <!-- Vendors Table -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="font-size: 18px; font-weight: 600; color: var(--dark); margin: 0;">All Vendors</h3>
                    <div style="color: #666; font-size: 14px;">
                        Total: <?= $total_vendors ?> vendors
                    </div>
                </div>
                
                <div style="overflow-x: auto;">
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background: #f8f9fa;">
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">ID</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">Business Name</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">Email/Phone</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">Status</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">Items</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">Joined On</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666; text-transform: uppercase;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($vendors)): ?>
                                <tr>
                                    <td colspan="8" style="padding: 30px; text-align: center; color: #999;">
                                        No vendors found
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php $numbering = 1; foreach ($vendors as $vendor): ?>
                                    <tr style="border-bottom: 1px solid #f0f0f0;">
                                        <td style="padding: 15px;"><?= $numbering++; ?></td>
                                        <td>
                                            <b><?= Security::escapeOutput($vendor['business_name']) ?></b><br>
                                            <?= Security::escapeOutput($vendor['city'] . ', ' . $vendor['state']) ?>
                                        </td>
                                        <td style="padding: 15px;"><?= Security::escapeOutput($vendor['email']) ?><br><?= format_phone($vendor['phone']) ?></td>
                                        <td style="padding: 15px;">
                                            <?php
                                            //registration confirmation
                                            $reg_confirmation = '';
                                            switch($vendor['reg_verification']) {
                                                case '0':
                                                    $reg_confirmation = 'status-pending';
                                                    break;
                                                case '1':
                                                    $reg_confirmation = 'status-approved';
                                                    break;
                                            }

                                            //admin approval
                                            $status_class = '';
                                            switch($vendor['approval_status']) {
                                                case 'pending':
                                                    $status_class = 'status-pending';
                                                    break;
                                                case 'approved':
                                                    $status_class = 'status-approved';
                                                    break;
                                                case 'rejected':
                                                    $status_class = 'status-rejected';
                                                    break;
                                                case 'suspended':
                                                    $status_class = 'status-suspended';
                                                    break;
                                            }
                                            ?>
                                            <span class="status-badge <?= $reg_confirmation ?>">
                                                <?= ucfirst($vendor['reg_verification'] == 1 ? 'Verified' : 'Unverified') ?>
                                            </span>
                                            <span class="status-badge <?= $status_class ?>">
                                                <?= ucfirst($vendor['approval_status']) ?>
                                            </span>
                                        </td>
                                        <td style="padding: 15px;"><?= $vendor['total_items'] ?? 0 ?></td>
                                        <td style="padding: 15px;"><?php echo date('M j, Y', strtotime($vendor['registered_at'])); ?></td>
                                        <td style="padding: 15px;">
                                            <div class="action-buttons">
                                                <a href="vendor-details.php?id=<?= $vendor['id'] ?>" class="btn-action btn-view" title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                
                                                <?php if ($vendor['approval_status'] === 'pending'): ?>
                                                    <button onclick="approveVendor(<?= $vendor['id'] ?>)" class="btn-action btn-approve" title="Approve">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                    <button onclick="rejectVendor(<?= $vendor['id'] ?>)" class="btn-action btn-reject" title="Reject">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <?php if ($pagination['total_pages'] > 1): ?>
                    <div class="pagination-wrapper">
                        <ul class="pagination">
                            <?php if ($pagination['has_prev']): ?>
                                <li>
                                    <a href="?page=<?= $pagination['prev_page'] ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($status) ? '&status=' . $status : '' ?>">
                                        &laquo; Previous
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php for ($i = 1; $i <= $pagination['total_pages']; $i++): ?>
                                <li class="<?= $i == $pagination['current_page'] ? 'active' : '' ?>">
                                    <?php if ($i == $pagination['current_page']): ?>
                                        <span><?= $i ?></span>
                                    <?php else: ?>
                                        <a href="?page=<?= $i ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($status) ? '&status=' . $status : '' ?>">
                                            <?= $i ?>
                                        </a>
                                    <?php endif; ?>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($pagination['has_next']): ?>
                                <li>
                                    <a href="?page=<?= $pagination['next_page'] ?><?= !empty($search) ? '&search=' . urlencode($search) : '' ?><?= !empty($status) ? '&status=' . $status : '' ?>">
                                        Next &raquo;
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php include '../templates/layouts/admin/footer.php'; ?>
    
    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Menu Toggle
        document.getElementById('menuToggle')?.addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('active');
        });
        
        // Approve Vendor
        function approveVendor(vendorId) {
            if (confirm('Are you sure you want to approve this vendor?')) {
                window.location.href = 'vendor-approve.php?id=' + vendorId;
            }
        }
        
        // Reject Vendor
        function rejectVendor(vendorId) {
            const reason = prompt('Please enter rejection reason:');
            if (reason !== null && reason.trim() !== '') {
                window.location.href = 'vendor-reject.php?id=' + vendorId + '&reason=' + encodeURIComponent(reason);
            }
        }
    </script>
</body>
</html>