<?php
require_once '../config/config.php';

// Require admin login
requireRole('secretariat');

$pageTitle = 'Account Approvals - Secretariat - PSAU GAD';
$db = getDB();
$auth = new Auth();

// Handle approval/rejection
if (isPost()) {
    $action = post('action');
    $userId = (int)post('user_id');
    
    try {
        if ($action === 'approve') {
            $auth->approveAccount($userId);
            setFlashMessage('success', 'Account approved successfully');
        } elseif ($action === 'reject') {
            $auth->rejectAccount($userId);
            setFlashMessage('success', 'Account rejected');
        }
    } catch (Exception $e) {
        setFlashMessage('error', 'Failed to process request');
        logError('Account approval error: ' . $e->getMessage());
    }
    
    redirect('account-approvals.php');
}

// Get pending accounts
$stmt = $db->query("
    SELECT 
        u.*,
        ep.first_name,
        ep.last_name,
        ep.gender,
        ep.category,
        ep.contact_number
    FROM users u
    LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
    WHERE u.is_approved = 0 AND u.is_active = 1
    ORDER BY u.created_at DESC
");
$pendingAccounts = $stmt->fetchAll();

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">
                <i class="fas fa-user-clock text-secretariat mr-3"></i>
                Account Approvals
            </h1>
            <p class="text-gray-600">Review and approve employee account registrations</p>
        </div>

        <?php displayFlashMessage(); ?>

        <!-- Pending Accounts -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <?php if (empty($pendingAccounts)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-check-circle text-6xl text-green-300 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">All Caught Up!</h3>
                    <p class="text-gray-500">No pending account approvals at the moment</p>
                </div>
            <?php else: ?>
                <div class="p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-xl font-bold text-gray-900">
                            Pending Accounts (<?php echo count($pendingAccounts); ?>)
                        </h2>
                        <p class="text-sm text-gray-600">
                            <i class="fas fa-info-circle mr-1"></i>
                            PSAU accounts (@psau.edu.ph) are auto-approved
                        </p>
                    </div>

                    <div class="space-y-4">
                        <?php foreach ($pendingAccounts as $account): ?>
                            <div class="border border-gray-200 rounded-lg p-6 hover:border-secretariat transition">
                                <div class="flex items-start justify-between">
                                    <!-- Account Info -->
                                    <div class="flex-1">
                                        <div class="flex items-center mb-3">
                                            <div class="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center text-yellow-600 font-semibold mr-4">
                                                <?php 
                                                if ($account['first_name']) {
                                                    echo strtoupper(substr($account['first_name'], 0, 1) . substr($account['last_name'], 0, 1));
                                                } else {
                                                    echo strtoupper(substr($account['email'], 0, 2));
                                                }
                                                ?>
                                            </div>
                                            <div>
                                                <h3 class="font-semibold text-gray-900 text-lg">
                                                    <?php 
                                                    if ($account['first_name']) {
                                                        echo htmlspecialchars($account['first_name'] . ' ' . $account['last_name']);
                                                    } else {
                                                        echo 'Profile Incomplete';
                                                    }
                                                    ?>
                                                </h3>
                                                <p class="text-sm text-gray-600">
                                                    <i class="fas fa-envelope mr-1"></i>
                                                    <?php echo htmlspecialchars($account['email']); ?>
                                                </p>
                                            </div>
                                        </div>

                                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                                            <div>
                                                <p class="text-xs text-gray-500 mb-1">Role</p>
                                                <p class="font-semibold text-gray-900">
                                                    <i class="fas fa-user-tag mr-1 text-secretariat"></i>
                                                    <?php echo ucfirst($account['role']); ?>
                                                </p>
                                            </div>
                                            <?php if ($account['category']): ?>
                                                <div>
                                                    <p class="text-xs text-gray-500 mb-1">Category</p>
                                                    <p class="font-semibold text-gray-900">
                                                        <i class="fas fa-briefcase mr-1 text-secretariat"></i>
                                                        <?php echo htmlspecialchars($account['category']); ?>
                                                    </p>
                                                </div>
                                            <?php endif; ?>
                                            <?php if ($account['gender']): ?>
                                                <div>
                                                    <p class="text-xs text-gray-500 mb-1">Gender</p>
                                                    <p class="font-semibold text-gray-900">
                                                        <?php if ($account['gender'] === 'Male'): ?>
                                                            <i class="fas fa-male mr-1 text-blue-500"></i>
                                                        <?php elseif ($account['gender'] === 'Female'): ?>
                                                            <i class="fas fa-female mr-1 text-pink-500"></i>
                                                        <?php else: ?>
                                                            <i class="fas fa-user mr-1 text-gray-500"></i>
                                                        <?php endif; ?>
                                                        <?php echo $account['gender']; ?>
                                                    </p>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <div class="flex items-center text-sm text-gray-600">
                                            <i class="fas fa-clock mr-2"></i>
                                            Registered: <?php echo formatDateTime($account['created_at']); ?>
                                        </div>
                                    </div>

                                    <!-- Actions -->
                                    <div class="ml-6 flex flex-col space-y-2">
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="approve">
                                            <input type="hidden" name="user_id" value="<?php echo $account['user_id']; ?>">
                                            <button type="submit" 
                                                    class="w-32 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition text-sm font-semibold">
                                                <i class="fas fa-check mr-2"></i> Approve
                                            </button>
                                        </form>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="reject">
                                            <input type="hidden" name="user_id" value="<?php echo $account['user_id']; ?>">
                                            <button type="submit" 
                                                    onclick="return confirm('Are you sure you want to reject this account?')"
                                                    class="w-32 bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition text-sm font-semibold">
                                                <i class="fas fa-times mr-2"></i> Reject
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Recently Approved -->
        <?php
        $stmt = $db->query("
            SELECT 
                u.*,
                ep.first_name,
                ep.last_name
            FROM users u
            LEFT JOIN employee_profiles ep ON u.user_id = ep.user_id
            WHERE u.is_approved = 1 AND u.is_active = 1
            ORDER BY u.updated_at DESC
            LIMIT 5
        ");
        $recentlyApproved = $stmt->fetchAll();
        ?>

        <?php if (!empty($recentlyApproved)): ?>
            <div class="bg-white rounded-xl shadow-lg overflow-hidden mt-8">
                <div class="p-6">
                    <h2 class="text-xl font-bold text-gray-900 mb-4">
                        <i class="fas fa-check-circle text-green-500 mr-2"></i>
                        Recently Approved
                    </h2>
                    <div class="space-y-3">
                        <?php foreach ($recentlyApproved as $account): ?>
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center">
                                    <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center text-green-600 font-semibold mr-3">
                                        <?php 
                                        if ($account['first_name']) {
                                            echo strtoupper(substr($account['first_name'], 0, 1) . substr($account['last_name'], 0, 1));
                                        } else {
                                            echo strtoupper(substr($account['email'], 0, 2));
                                        }
                                        ?>
                                    </div>
                                    <div>
                                        <h4 class="font-semibold text-gray-900">
                                            <?php 
                                            if ($account['first_name']) {
                                                echo htmlspecialchars($account['first_name'] . ' ' . $account['last_name']);
                                            } else {
                                                echo htmlspecialchars($account['email']);
                                            }
                                            ?>
                                        </h4>
                                        <p class="text-xs text-gray-600">
                                            <?php echo htmlspecialchars($account['email']); ?>
                                        </p>
                                    </div>
                                </div>
                                <span class="px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                                    <i class="fas fa-check mr-1"></i> Approved
                                </span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<?php include '../includes/footer.php'; ?>

