<?php
/**
 * ============================================================================
 * admin/approval-details.php - Detailed view and approval with assignment
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Check permissions
if (!hasPermission('manage_users')) {
    redirectTo('/admin/');
}

$approvalId = $_GET['id'] ?? 0;

if (!$approvalId) {
    redirectTo('/admin/approvals.php');
}

// Get approval details
$sql = "SELECT 
            ua.*,
            u.full_name,
            u.phone_number,
            u.email,
            u.created_at as registration_date,
            u.region_id,
            u.district_id,
            u.subcounty_id,
            u.parish_id,
            u.village_id,
            r.region_name,
            d.district_name,
            s.subcounty_name,
            p.parish_name,
            v.village_name,
            bp.business_name,
            bp.buyer_type,
            bp.business_registration,
            bp.tax_id,
            eo.organization,
            eo.qualification,
            eo.years_of_experience,
            eo.specialization
        FROM user_approvals ua
        JOIN users u ON ua.user_id = u.id
        LEFT JOIN regions r ON u.region_id = r.id
        LEFT JOIN districts d ON u.district_id = d.id
        LEFT JOIN subcounties s ON u.subcounty_id = s.id
        LEFT JOIN parishes p ON u.parish_id = p.id
        LEFT JOIN villages v ON u.village_id = v.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 ua.id = ?";

$stmt = $db->prepare($sql);
$stmt->execute([$approvalId]);
$approval = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$approval) {
    redirectTo('/admin/approvals.php');
}

// Get extension roles if extension officer
$extensionRoles = [];
if ($approval['user_type'] === 'extension_officer') {
    $sql = "SELECT * FROM extension_roles WHERE is_active = 1 ORDER BY role_level, role_name";
    $stmt = $db->query($sql);
    $extensionRoles = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$breadcrumbs = [
    ['title' => 'User Approvals', 'url' => 'approvals.php'],
    ['title' => 'Approval Details', 'url' => '']
];

renderAdminHeader('Approval Details', $breadcrumbs);
?>

<style>
.info-section {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
}

.info-label {
    font-weight: 600;
    color: #6b7280;
    font-size: 0.875rem;
    margin-bottom: 5px;
}

.info-value {
    font-size: 1rem;
    color: #1f2937;
    margin-bottom: 15px;
}

.status-pending { background: #fef3c7; color: #92400e; }
.status-approved { background: #d1fae5; color: #065f46; }
.status-rejected { background: #fee2e2; color: #991b1b; }
</style>

<!-- Back Button -->
<div class="mb-4">
    <a href="approvals.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Back to Approvals
    </a>
</div>

<!-- Status Banner -->
<div class="alert alert-<?php 
    echo $approval['approval_status'] === 'approved' ? 'success' : 
        ($approval['approval_status'] === 'rejected' ? 'danger' : 'warning'); 
?> mb-4">
    <div class="row align-items-center">
        <div class="col-md-8">
            <h5 class="mb-1">
                <i class="bi bi-<?php 
                    echo $approval['approval_status'] === 'approved' ? 'check-circle' : 
                        ($approval['approval_status'] === 'rejected' ? 'x-circle' : 'hourglass-split'); 
                ?> me-2"></i>
                <?php echo ucfirst($approval['approval_status']); ?> Application
            </h5>
            <p class="mb-0 small">
                <?php if ($approval['approval_status'] === 'pending'): ?>
                    This application is awaiting your review and decision.
                <?php elseif ($approval['approval_status'] === 'approved'): ?>
                    Approved on <?php echo formatDate($approval['updated_at']); ?>
                <?php else: ?>
                    Rejected on <?php echo formatDate($approval['updated_at']); ?>
                    <?php if ($approval['rejection_reason']): ?>
                        <br><strong>Reason:</strong> <?php echo htmlspecialchars($approval['rejection_reason']); ?>
                    <?php endif; ?>
                <?php endif; ?>
            </p>
        </div>
        <?php if ($approval['approval_status'] === 'pending'): ?>
        <div class="col-md-4 text-md-end mt-3 mt-md-0">
            <button class="btn btn-success me-2" onclick="approveUser()">
                <i class="bi bi-check-circle me-2"></i>Approve
            </button>
            <button class="btn btn-danger" onclick="rejectUser()">
                <i class="bi bi-x-circle me-2"></i>Reject
            </button>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- User Information -->
<div class="row">
    <div class="col-lg-8">
        <!-- Basic Information -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-person-circle me-2"></i>Basic Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-label">Full Name</div>
                        <div class="info-value"><?php echo htmlspecialchars($approval['full_name']); ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">User Type</div>
                        <div class="info-value">
                            <span class="badge bg-<?php echo $approval['user_type'] === 'buyer' ? 'primary' : 'success'; ?> rounded-pill">
                                <?php echo ucfirst(str_replace('_', ' ', $approval['user_type'])); ?>
                            </span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Phone Number</div>
                        <div class="info-value">
                            <i class="bi bi-phone me-2"></i><?php echo formatPhone($approval['phone_number']); ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Email</div>
                        <div class="info-value">
                            <?php if ($approval['email']): ?>
                                <i class="bi bi-envelope me-2"></i><?php echo htmlspecialchars($approval['email']); ?>
                            <?php else: ?>
                                <span class="text-muted">Not provided</span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="info-label">Registration Date</div>
                        <div class="info-value">
                            <i class="bi bi-calendar me-2"></i>
                            <?php echo formatDate($approval['registration_date']); ?>
                            <small class="text-muted">(<?php echo timeAgo($approval['registration_date']); ?>)</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Location Information -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-geo-alt me-2"></i>Location Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-label">Region</div>
                        <div class="info-value"><?php echo $approval['region_name'] ?? 'Not specified'; ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">District</div>
                        <div class="info-value"><?php echo $approval['district_name'] ?? 'Not specified'; ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Subcounty</div>
                        <div class="info-value"><?php echo $approval['subcounty_name'] ?? 'Not specified'; ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Parish</div>
                        <div class="info-value"><?php echo $approval['parish_name'] ?? 'Not specified'; ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Village</div>
                        <div class="info-value"><?php echo $approval['village_name'] ?? 'Not specified'; ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Buyer-specific Information -->
        <?php if ($approval['user_type'] === 'buyer'): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-briefcase me-2"></i>Business Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-label">Buyer Type</div>
                        <div class="info-value">
                            <span class="badge bg-info"><?php echo ucfirst($approval['buyer_type']); ?></span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Business Name</div>
                        <div class="info-value"><?php echo htmlspecialchars($approval['business_name']) ?: 'Not provided'; ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Business Registration</div>
                        <div class="info-value"><?php echo htmlspecialchars($approval['business_registration']) ?: 'Not provided'; ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Tax ID</div>
                        <div class="info-value"><?php echo htmlspecialchars($approval['tax_id']) ?: 'Not provided'; ?></div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Extension Officer Information -->
        <?php if ($approval['user_type'] === 'extension_officer'): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">
                    <i class="bi bi-mortarboard me-2"></i>Professional Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-label">Organization</div>
                        <div class="info-value">
                            <i class="bi bi-building me-2"></i>
                            <?php echo htmlspecialchars($approval['organization']) ?: 'Not provided'; ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Qualification</div>
                        <div class="info-value">
                            <i class="bi bi-award me-2"></i>
                            <?php echo ucfirst($approval['qualification']) ?: 'Not provided'; ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Years of Experience</div>
                        <div class="info-value">
                            <i class="bi bi-calendar me-2"></i>
                            <?php echo $approval['years_of_experience'] ?: '0'; ?> years
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="info-label">Specialization</div>
                        <div class="info-value">
                            <i class="bi bi-star me-2"></i>
                            <?php echo htmlspecialchars($approval['specialization']) ?: 'Not provided'; ?>
                        </div>
                    </div>
                </div>

                <?php if ($approval['approval_status'] === 'approved'): ?>
                <hr>
                <div class="alert alert-info mb-0">
                    <h6 class="mb-2">
                        <i class="bi bi-info-circle me-2"></i>Extension Assignment
                    </h6>
                    <p class="mb-2 small">This officer needs to be assigned to a role and geographic area.</p>
                    <a href="extension-assignments.php?user_id=<?php echo $approval['user_id']; ?>" class="btn btn-sm btn-primary">
                        <i class="bi bi-person-badge me-2"></i>Manage Assignments
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Sidebar -->
    <div class="col-lg-4">
        <!-- Quick Actions -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white py-3">
                <h6 class="mb-0 fw-bold">Quick Actions</h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="users.php?user_id=<?php echo $approval['user_id']; ?>" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-person me-2"></i>View User Profile
                    </a>
                    <?php if ($approval['approval_status'] === 'approved' && $approval['user_type'] === 'extension_officer'): ?>
                    <a href="extension-assignments.php?user_id=<?php echo $approval['user_id']; ?>" class="btn btn-outline-success btn-sm">
                        <i class="bi bi-person-badge me-2"></i>Manage Assignment
                    </a>
                    <?php endif; ?>
                    <button class="btn btn-outline-secondary btn-sm" onclick="window.print()">
                        <i class="bi bi-printer me-2"></i>Print Details
                    </button>
                </div>
            </div>
        </div>

        <!-- Timeline -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h6 class="mb-0 fw-bold">Application Timeline</h6>
            </div>
            <div class="card-body">
                <div class="timeline">
                    <div class="timeline-item mb-3">
                        <div class="timeline-badge bg-primary">
                            <i class="bi bi-person-plus"></i>
                        </div>
                        <div class="timeline-content">
                            <small class="text-muted d-block">Registered</small>
                            <small class="fw-semibold"><?php echo formatDate($approval['registration_date']); ?></small>
                        </div>
                    </div>

                    <?php if ($approval['approval_status'] !== 'pending'): ?>
                    <div class="timeline-item">
                        <div class="timeline-badge bg-<?php echo $approval['approval_status'] === 'approved' ? 'success' : 'danger'; ?>">
                            <i class="bi bi-<?php echo $approval['approval_status'] === 'approved' ? 'check' : 'x'; ?>"></i>
                        </div>
                        <div class="timeline-content">
                            <small class="text-muted d-block"><?php echo ucfirst($approval['approval_status']); ?></small>
                            <small class="fw-semibold"><?php echo formatDate($approval['updated_at']); ?></small>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const approvalData = <?php echo json_encode($approval); ?>;
const extensionRoles = <?php echo json_encode($extensionRoles); ?>;

function approveUser() {
    <?php if ($approval['user_type'] === 'extension_officer'): ?>
    // For extension officers, show assignment modal
    Swal.fire({
        title: 'Approve Extension Officer?',
        html: `
            <p>This officer will be approved. You can assign them to a role now or later.</p>
            <div class="form-check text-start">
                <input class="form-check-input" type="checkbox" id="assignNow">
                <label class="form-check-label" for="assignNow">
                    Assign to role immediately
                </label>
            </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#22c55e',
        confirmButtonText: 'Approve',
        preConfirm: () => {
            return document.getElementById('assignNow').checked;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            processApproval(result.value);
        }
    });
    <?php else: ?>
    // For buyers, simple approval
    Swal.fire({
        title: 'Approve User?',
        text: 'This user will gain full access to the platform.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#22c55e',
        confirmButtonText: 'Yes, approve'
    }).then((result) => {
        if (result.isConfirmed) {
            processApproval(false);
        }
    });
    <?php endif; ?>
}

function processApproval(assignNow) {
    showLoading();
    $.ajax({
        url: APP_URL + '/api/admin.php',
        method: 'POST',
        dataType: 'json',
        data: {
            action: 'approve_user',
            approval_id: <?php echo $approvalId; ?>
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                Swal.fire({
                    title: 'Approved!',
                    text: response.message,
                    icon: 'success',
                    confirmButtonColor: '#059669'
                }).then(() => {
                    if (assignNow) {
                        window.location.href = 'extension-assignments.php?user_id=<?php echo $approval['user_id']; ?>';
                    } else {
                        location.reload();
                    }
                });
            } else {
                Swal.fire('Error', response.message, 'error');
            }
        },
        error: function() {
            hideLoading();
            Swal.fire('Error', 'Failed to approve user', 'error');
        }
    });
}

function rejectUser() {
    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',
        confirmButtonText: 'Reject User',
        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: <?php echo $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('Error', response.message, 'error');
                    }
                },
                error: function() {
                    hideLoading();
                    Swal.fire('Error', 'Failed to reject user', 'error');
                }
            });
        }
    });
}
</script>

<style>
.timeline {
    position: relative;
    padding-left: 30px;
}

.timeline:before {
    content: '';
    position: absolute;
    left: 8px;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #e5e7eb;
}

.timeline-item {
    position: relative;
}

.timeline-badge {
    position: absolute;
    left: -30px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 0.7rem;
}

.timeline-content {
    padding-bottom: 10px;
}
</style>

<?php renderAdminFooter(); ?>