<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['admin_id'])) { 
    header("Location: login.php"); 
    exit(); 
}
include '../include/config.php';

// Handle approval/rejection
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $user_type = $_POST['user_type'];
    $user_id = intval($_POST['user_id']);
    $action = $_POST['action'];
    $rejection_reason = isset($_POST['rejection_reason']) ? $conn->real_escape_string($_POST['rejection_reason']) : '';
    
    if ($action == 'approve') {
        // Update the specific table (nurses or staff)
        $conn->query("UPDATE $user_type SET approval_status = 'approved', status = 'active', approved_by = '{$_SESSION['admin_id']}', approved_at = NOW() WHERE user_id = $user_id");
        // Update users table
        $conn->query("UPDATE users SET approval_status = 'approved', status = 'active', approved_at = NOW(), approved_by = '{$_SESSION['admin_id']}' WHERE user_id = $user_id");
        $success_msg = "User has been approved successfully!";
    } else if ($action == 'reject') {
        // Update the specific table
        $conn->query("UPDATE $user_type SET approval_status = 'rejected', status = 'inactive', rejection_reason = '$rejection_reason', approved_by = '{$_SESSION['admin_id']}', approved_at = NOW() WHERE user_id = $user_id");
        // Update users table
        $conn->query("UPDATE users SET approval_status = 'rejected', status = 'inactive', approved_at = NOW(), approved_by = '{$_SESSION['admin_id']}' WHERE user_id = $user_id");
        $success_msg = "User has been rejected.";
    }
}

// Get pending nurses
$pending_nurses = $conn->query("
    SELECT n.*, u.username, u.email, u.created_at 
    FROM nurses n 
    JOIN users u ON n.user_id = u.user_id 
    WHERE n.approval_status = 'pending'
    ORDER BY n.created_at ASC
");

// Get pending staff
$pending_staff = $conn->query("
    SELECT s.*, u.username, u.email, u.created_at 
    FROM staff s 
    JOIN users u ON s.user_id = u.user_id 
    WHERE s.approval_status = 'pending'
    ORDER BY s.created_at ASC
");

// Get recently approved
$recent_approved = $conn->query("
    (SELECT 'Nurse' as type, n.first_name, n.email, n.approved_at 
     FROM nurses n 
     WHERE n.approval_status = 'approved' AND n.approved_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
     ORDER BY n.approved_at DESC LIMIT 5)
    UNION ALL
    (SELECT 'Staff' as type, s.first_name, s.email, s.approved_at 
     FROM staff s 
     WHERE s.approval_status = 'approved' AND s.approved_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
     ORDER BY s.approved_at DESC LIMIT 5)
    ORDER BY approved_at DESC LIMIT 10
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Approvals - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #0a3d2f; font-family: 'Segoe UI', sans-serif; }
        .navbar { background: #064e3b !important; box-shadow: 0 2px 10px rgba(0,0,0,0.2); padding: 12px 0; }
        .navbar-brand img { height: 45px; margin-right: 12px; }
        .brand-title { font-size: 1.4rem; font-weight: 800; line-height: 1.2; color: white; }
        .brand-sub { font-size: 0.7rem; font-weight: 400; letter-spacing: 1px; color: #c0c0c0; }
        .stat-card { background: rgba(255,255,255,0.1); backdrop-filter: blur(5px); border-radius: 20px; padding: 20px; text-align: center; color: white; transition: 0.3s; }
        .btn-approve { background: #28a745; color: white; }
        .btn-approve:hover { background: #218838; }
        .btn-reject { background: #dc3545; color: white; }
        .btn-reject:hover { background: #c82333; }
        footer { background: #064e3b; color: white; margin-top: auto; padding: 30px 0 20px; border-top: 1px solid rgba(255,255,255,0.1); }
        .table-dark-custom { background: #2c1a0e; color: white; }
        .table-dark-custom th { background: #1a0f08; color: #d4a017; }
        .modal-content { background: #2c1a0e; color: white; }
        .modal-header { border-bottom-color: #d4a017; }
        .modal-footer { border-top-color: #d4a017; }
        .form-control { background: #3d2b1f; border: 1px solid #d4a017; color: white; }
        .form-control:focus { background: #4a3828; color: white; border-color: #d4a017; }
    </style>
</head>
<body>

<!-- Header -->
<nav class="navbar navbar-dark">
    <div class="container">
        <a class="navbar-brand d-flex align-items-center" href="../index.php">
            <img src="https://od.lk/s/MzdfODgyMDMwNTZf/IMG-20260414-WA0014%20%281%29.jpg" alt="UHD Logo">
            <div>
                <div class="brand-title">UNITY HEALTHCARE DATABASE</div>
                <div class="brand-sub">NIGERIA | ADMIN</div>
            </div>
        </a>
        <div class="d-flex align-items-center">
            <span class="text-white me-3"><i class="fas fa-user-shield"></i> <?= htmlspecialchars($_SESSION['admin_name']) ?></span>
            <a href="dashboard.php" class="btn btn-outline-light btn-sm me-2">Dashboard</a>
            <a href="logout.php" class="btn btn-danger btn-sm">Logout</a>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <!-- Success/Error Message -->
    <?php if(isset($success_msg)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?= $success_msg ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Page Title -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="text-white"><i class="fas fa-user-check"></i> User Approvals</h2>
        <a href="dashboard.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
    </div>

    <!-- Pending Nurses Section -->
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-user-nurse"></i> Pending Nurse Approvals 
                <span class="badge bg-light text-dark ms-2"><?= $pending_nurses ? $pending_nurses->num_rows : 0 ?></span>
            </h5>
        </div>
        <div class="card-body">
            <?php if($pending_nurses && $pending_nurses->num_rows > 0): ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-dark-custom">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Full Name</th>
                                <th>Username</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>License #</th>
                                <th>Specialization</th>
                                <th>Registered</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($nurse = $pending_nurses->fetch_assoc()): ?>
                            <tr>
                                <td><?= $nurse['nurse_id'] ?></td>
                                <td><strong><?= htmlspecialchars($nurse['first_name']) ?></strong></td>
                                <td><?= htmlspecialchars($nurse['username']) ?></td>
                                <td><?= htmlspecialchars($nurse['email']) ?></td>
                                <td><?= htmlspecialchars($nurse['phone'] ?? 'N/A') ?></td>
                                <td><code><?= htmlspecialchars($nurse['license_number'] ?? 'N/A') ?></code></td>
                                <td><?= htmlspecialchars($nurse['specialization'] ?? 'General') ?></td>
                                <td><?= date('M d, Y h:i A', strtotime($nurse['created_at'])) ?></td>
                                <td>
                                    <form method="POST" style="display:inline-block">
                                        <input type="hidden" name="user_type" value="nurses">
                                        <input type="hidden" name="user_id" value="<?= $nurse['user_id'] ?>">
                                        <button type="submit" name="action" value="approve" class="btn btn-success btn-sm" onclick="return confirm('Approve this nurse?')">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                    </form>
                                    <button class="btn btn-danger btn-sm" onclick="showRejectModal('nurses', <?= $nurse['user_id'] ?>, '<?= htmlspecialchars($nurse['first_name']) ?>')">
                                        <i class="fas fa-times"></i> Reject
                                    </button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info text-center mb-0">
                    <i class="fas fa-info-circle"></i> No pending nurse registrations.
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Pending Staff Section -->
    <div class="card mb-4">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="fas fa-user-tie"></i> Pending Staff Approvals 
                <span class="badge bg-light text-dark ms-2"><?= $pending_staff ? $pending_staff->num_rows : 0 ?></span>
            </h5>
        </div>
        <div class="card-body">
            <?php if($pending_staff && $pending_staff->num_rows > 0): ?>
                <div class="table-responsive">
                    <table class="table table-bordered table-dark-custom">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Full Name</th>
                                <th>Username</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Department</th>
                                <th>Position</th>
                                <th>Registered</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($staff = $pending_staff->fetch_assoc()): ?>
                            <tr>
                                <td><?= $staff['staff_id'] ?></td>
                                <td><strong><?= htmlspecialchars($staff['first_name']) ?></strong></td>
                                <td><?= htmlspecialchars($staff['username']) ?></td>
                                <td><?= htmlspecialchars($staff['email']) ?></td>
                                <td><?= htmlspecialchars($staff['phone'] ?? 'N/A') ?></td>
                                <td><span class="badge bg-info"><?= ucfirst(htmlspecialchars($staff['department'])) ?></span></td>
                                <td><?= htmlspecialchars($staff['position']) ?></td>
                                <td><?= date('M d, Y h:i A', strtotime($staff['created_at'])) ?></td>
                                <td>
                                    <form method="POST" style="display:inline-block">
                                        <input type="hidden" name="user_type" value="staff">
                                        <input type="hidden" name="user_id" value="<?= $staff['user_id'] ?>">
                                        <button type="submit" name="action" value="approve" class="btn btn-success btn-sm" onclick="return confirm('Approve this staff member?')">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                    </form>
                                    <button class="btn btn-danger btn-sm" onclick="showRejectModal('staff', <?= $staff['user_id'] ?>, '<?= htmlspecialchars($staff['first_name']) ?>')">
                                        <i class="fas fa-times"></i> Reject
                                    </button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info text-center mb-0">
                    <i class="fas fa-info-circle"></i> No pending staff registrations.
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Recently Approved Section -->
    <div class="card">
        <div class="card-header bg-secondary text-white">
            <h5 class="mb-0"><i class="fas fa-history"></i> Recently Approved (Last 7 Days)</h5>
        </div>
        <div class="card-body">
            <?php if($recent_approved && $recent_approved->num_rows > 0): ?>
                <div class="table-responsive">
                    <table class="table table-sm table-dark-custom">
                        <thead>
                            <tr><th>Type</th><th>Name</th><th>Email</th><th>Approved Date</th></tr>
                        </thead>
                        <tbody>
                            <?php while($approved = $recent_approved->fetch_assoc()): ?>
                            <tr>
                                <td><span class="badge bg-success"><?= $approved['type'] ?></span></td>
                                <td><?= htmlspecialchars($approved['first_name']) ?></td>
                                <td><?= htmlspecialchars($approved['email']) ?></td>
                                <td><?= date('M d, Y h:i A', strtotime($approved['approved_at'])) ?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p class="text-muted text-center mb-0">No users approved in the last 7 days.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle"></i> Reject User Registration</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="rejectForm">
                <div class="modal-body">
                    <p>Are you sure you want to reject <strong id="rejectUserName"></strong>?</p>
                    <div class="mb-3">
                        <label class="form-label">Reason for Rejection:</label>
                        <textarea name="rejection_reason" class="form-control" rows="3" placeholder="Please provide a reason for rejection..." required></textarea>
                        <small class="text-muted">This reason will be shown to the user.</small>
                    </div>
                    <input type="hidden" name="user_type" id="rejectUserType">
                    <input type="hidden" name="user_id" id="rejectUserId">
                    <input type="hidden" name="action" value="reject">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Confirm Rejection</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Footer -->
<footer>
    <div class="container text-center">
        <small>&copy; <?= date('Y') ?> Unity Healthcare Database. All rights reserved.</small><br>
        <small>Powered by Fulgent Digital Clinic (R)</small>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function showRejectModal(userType, userId, userName) {
    document.getElementById('rejectUserType').value = userType;
    document.getElementById('rejectUserId').value = userId;
    document.getElementById('rejectUserName').innerText = userName;
    new bootstrap.Modal(document.getElementById('rejectModal')).show();
}
</script>
</body>
</html>