<?php
/**
 * ============================================================================
 * admin/approvals.php - User Approval Management
 * ============================================================================
 */

// Include admin base (handles authentication & permissions)
require_once __DIR__ . '/includes/base.php';

// Define breadcrumbs
$breadcrumbs = [
    ['title' => 'User Approvals', 'url' => '']
];

// Get filter parameters
$filterStatus = $_GET['status'] ?? 'pending';
$filterType = $_GET['type'] ?? '';

// Build query
$sql = "SELECT 
            ua.*,
            u.full_name,
            u.phone_number,
            u.email,
            u.created_at as registration_date,
            CASE 
                WHEN ua.user_type = 'buyer' THEN bp.business_name
                WHEN ua.user_type = 'extension_officer' THEN eo.organization
                ELSE NULL
            END as organization_name,
            CASE 
                WHEN ua.user_type = 'buyer' THEN bp.buyer_type
                ELSE NULL
            END as buyer_type
        FROM user_approvals ua
        JOIN users u ON ua.user_id = u.id
        LEFT JOIN buyer_profiles bp ON u.id = bp.user_id
        LEFT JOIN extension_officer_profiles eo ON u.id = eo.user_id
        WHERE 1=1";

if ($filterStatus) {
    $sql .= " AND ua.approval_status = :status";
}

if ($filterType) {
    $sql .= " AND ua.user_type = :type";
}

$sql .= " ORDER BY ua.created_at DESC";

$stmt = $db->prepare($sql);

if ($filterStatus) {
    $stmt->bindParam(':status', $filterStatus);
}
if ($filterType) {
    $stmt->bindParam(':type', $filterType);
}

$stmt->execute();
$approvals = $stmt->fetchAll();

// Get counts
$sql = "SELECT approval_status, COUNT(*) as count FROM user_approvals GROUP BY approval_status";
$stmt = $db->query($sql);
$statusCounts = [];
while ($row = $stmt->fetch()) {
    $statusCounts[$row['approval_status']] = $row['count'];
}

// Start rendering
renderAdminHeader('User Approvals', $breadcrumbs);
?>

<!-- Page Header -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">User Approvals</h2>
        <p class="text-muted mb-0">Review and approve user registrations</p>
    </div>
    <div>
        <button class="btn btn-outline-secondary" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise me-2"></i>Refresh
        </button>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-lg-4 mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Pending Approvals</p>
                        <h3 class="mb-0 fw-bold"><?php echo $statusCounts['pending'] ?? 0; ?></h3>
                        <small class="text-warning">Awaiting review</small>
                    </div>
                    <div class="text-warning" style="font-size: 2.5rem;">
                        <i class="bi bi-hourglass-split"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4 mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Approved</p>
                        <h3 class="mb-0 fw-bold"><?php echo $statusCounts['approved'] ?? 0; ?></h3>
                        <small class="text-success">Access granted</small>
                    </div>
                    <div class="text-success" style="font-size: 2.5rem;">
                        <i class="bi bi-check-circle"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4 mb-3">
        <div class="card stat-card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <p class="text-muted mb-1 small">Rejected</p>
                        <h3 class="mb-0 fw-bold"><?php echo $statusCounts['rejected'] ?? 0; ?></h3>
                        <small class="text-danger">Access denied</small>
                    </div>
                    <div class="text-danger" style="font-size: 2.5rem;">
                        <i class="bi bi-x-circle"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="row g-3 align-items-center">
            <div class="col-md-6">
                <label class="form-label small text-muted mb-2">Filter by Status</label>
                <div class="btn-group d-flex" role="group">
                    <a href="?status=pending<?php echo $filterType ? '&type=' . $filterType : ''; ?>" 
                       class="btn btn-outline-warning <?php echo $filterStatus === 'pending' ? 'active' : ''; ?>">
                        Pending (<?php echo $statusCounts['pending'] ?? 0; ?>)
                    </a>
                    <a href="?status=approved<?php echo $filterType ? '&type=' . $filterType : ''; ?>" 
                       class="btn btn-outline-success <?php echo $filterStatus === 'approved' ? 'active' : ''; ?>">
                        Approved (<?php echo $statusCounts['approved'] ?? 0; ?>)
                    </a>
                    <a href="?status=rejected<?php echo $filterType ? '&type=' . $filterType : ''; ?>" 
                       class="btn btn-outline-danger <?php echo $filterStatus === 'rejected' ? 'active' : ''; ?>">
                        Rejected (<?php echo $statusCounts['rejected'] ?? 0; ?>)
                    </a>
                </div>
            </div>
            
            <div class="col-md-4">
                <label class="form-label small text-muted mb-2">Filter by User Type</label>
                <select class="form-select" id="filterType" onchange="location.href='?status=<?php echo $filterStatus; ?>&type=' + this.value">
                    <option value="">All User Types</option>
                    <option value="buyer" <?php echo $filterType === 'buyer' ? 'selected' : ''; ?>>Buyers</option>
                    <option value="extension_officer" <?php echo $filterType === 'extension_officer' ? 'selected' : ''; ?>>Extension Officers</option>
                </select>
            </div>
            
            <div class="col-md-2 text-end">
                <label class="form-label small text-muted mb-2">&nbsp;</label>
                <button class="btn btn-outline-secondary w-100" onclick="location.href='approvals.php'">
                    <i class="bi bi-arrow-clockwise me-2"></i>Reset
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Approvals List -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-0 py-3">
        <h6 class="mb-0 fw-bold">
            <i class="bi bi-list-check text-primary me-2"></i>
            <?php echo ucfirst($filterStatus); ?> Approvals
            <span class="badge bg-light text-dark ms-2"><?php echo count($approvals); ?></span>
        </h6>
    </div>
    <div class="card-body p-0">
        <?php if (empty($approvals)): ?>
            <div class="text-center py-5">
                <div style="font-size: 4rem;" class="text-muted mb-3">
                    <i class="bi bi-inbox"></i>
                </div>
                <h5 class="text-muted">No <?php echo $filterStatus; ?> approvals found</h5>
                <p class="text-muted mb-4">
                    <?php if ($filterType): ?>
                        No <?php echo ucfirst(str_replace('_', ' ', $filterType)); ?> approvals match your filters.
                    <?php else: ?>
                        There are currently no <?php echo $filterStatus; ?> user approvals.
                    <?php endif; ?>
                </p>
                <?php if ($filterStatus !== 'pending'): ?>
                    <a href="?status=pending" class="btn btn-primary">
                        <i class="bi bi-hourglass-split me-2"></i>View Pending Approvals
                    </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>User Details</th>
                            <th>Type</th>
                            <th>Organization</th>
                            <th>Registered</th>
                            <th>Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($approvals as $approval): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="me-3">
                                        <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" 
                                             style="width: 40px; height: 40px;">
                                            <i class="bi bi-person fs-5"></i>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="fw-semibold"><?php echo htmlspecialchars($approval['full_name']); ?></div>
                                        <small class="text-muted">
                                            <i class="bi bi-phone me-1"></i><?php echo formatPhone($approval['phone_number']); ?>
                                            <?php if ($approval['email']): ?>
                                                <br><i class="bi bi-envelope me-1"></i><?php echo htmlspecialchars($approval['email']); ?>
                                            <?php endif; ?>
                                        </small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-<?php echo $approval['user_type'] === 'buyer' ? 'primary' : 'success'; ?> rounded-pill">
                                    <?php echo ucfirst(str_replace('_', ' ', $approval['user_type'])); ?>
                                </span>
                                <?php if ($approval['buyer_type']): ?>
                                    <br><small class="text-muted"><?php echo ucfirst($approval['buyer_type']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($approval['organization_name']): ?>
                                    <i class="bi bi-building me-1 text-muted"></i>
                                    <?php echo htmlspecialchars($approval['organization_name']); ?>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <small class="text-muted">
                                    <?php echo formatDate($approval['registration_date']); ?><br>
                                    <span class="badge bg-light text-dark"><?php echo timeAgo($approval['registration_date']); ?></span>
                                </small>
                            </td>
                            <td>
                                <?php
                                $statusConfig = [
                                    'pending' => ['class' => 'warning', 'icon' => 'hourglass-split'],
                                    'approved' => ['class' => 'success', 'icon' => 'check-circle'],
                                    'rejected' => ['class' => 'danger', 'icon' => 'x-circle']
                                ];
                                $status = $statusConfig[$approval['approval_status']];
                                ?>
                                <span class="badge bg-<?php echo $status['class']; ?> rounded-pill">
                                    <i class="bi bi-<?php echo $status['icon']; ?> me-1"></i>
                                    <?php echo ucfirst($approval['approval_status']); ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <div class="btn-group btn-group-sm">
                                    <a href="<?php echo APP_URL; ?>/admin/approval-details.php?id=<?php echo $approval['id']; ?>" 
                                       class="btn btn-outline-primary" title="View Details">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <?php if ($approval['approval_status'] === 'pending'): ?>
                                        <button class="btn btn-outline-success" 
                                                onclick="approveUser(<?php echo $approval['id']; ?>)" 
                                                title="Approve User">
                                            <i class="bi bi-check-circle"></i>
                                        </button>
                                        <button class="btn btn-outline-danger" 
                                                onclick="rejectUser(<?php echo $approval['id']; ?>)" 
                                                title="Reject User">
                                            <i class="bi bi-x-circle"></i>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function approveUser(approvalId) {
    Swal.fire({
        title: 'Approve User?',
        text: 'This user will gain full access to the platform.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#22c55e',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, approve',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.ajax({
                url: APP_URL + '/api/admin.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'approve_user',
                    approval_id: approvalId
                },
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        Swal.fire({
                            title: 'Approved!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonColor: '#059669'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error',
                            confirmButtonColor: '#059669'
                        });
                    }
                },
                error: function(xhr) {
                    hideLoading();
                    console.error(xhr);
                    Swal.fire({
                        title: 'Error',
                        text: 'Failed to approve user. Please try again.',
                        icon: 'error',
                        confirmButtonColor: '#059669'
                    });
                }
            });
        }
    });
}

function rejectUser(approvalId) {
    Swal.fire({
        title: 'Reject User?',
        html: '<textarea id="rejectionReason" class="form-control" rows="4" placeholder="Enter reason for rejection..." required></textarea>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Reject User',
        cancelButtonText: 'Cancel',
        preConfirm: () => {
            const reason = document.getElementById('rejectionReason').value;
            if (!reason || reason.trim() === '') {
                Swal.showValidationMessage('You need to provide a reason for rejection');
                return false;
            }
            return reason;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            showLoading();
            $.ajax({
                url: APP_URL + '/api/admin.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'reject_user',
                    approval_id: approvalId,
                    reason: result.value
                },
                success: function(response) {
                    hideLoading();
                    if (response.success) {
                        Swal.fire({
                            title: 'Rejected',
                            text: response.message,
                            icon: 'success',
                            confirmButtonColor: '#059669'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error',
                            confirmButtonColor: '#059669'
                        });
                    }
                },
                error: function(xhr) {
                    hideLoading();
                    console.error(xhr);
                    Swal.fire({
                        title: 'Error',
                        text: 'Failed to reject user. Please try again.',
                        icon: 'error',
                        confirmButtonColor: '#059669'
                    });
                }
            });
        }
    });
}
</script>

<?php renderAdminFooter(); ?>