<?php
// Check permission - only admins can access
if (!isAdmin()) {
    echo "<div class='alert alert-danger'><i class='bi bi-shield-exclamation'></i> Access Denied. Admin only.</div>";
    exit();
}

// Handle approval actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' || isset($_GET['action'])) {
    $user_id = $_GET['id'] ?? $_POST['user_id'];
    $action = $_GET['action'] ?? $_POST['action'];
    
    if ($action == 'approve') {
        // Activate user
        $stmt = $pdo->prepare("UPDATE users SET is_active = 1 WHERE id = ?");
        $stmt->execute([$user_id]);
        
        // Get user email to send notification
        $stmt = $pdo->prepare("SELECT email, username FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        echo "<div class='alert alert-success alert-dismissible fade show'>
                <i class='bi bi-check-circle'></i> 
                User account activated successfully!
                <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
              </div>";
        
    } elseif ($action == 'reject') {
        // Get reason for rejection
        $reason = $_POST['rejection_reason'] ?? 'Registration not approved';
        
        // Store rejection reason
        $stmt = $pdo->prepare("UPDATE users SET notes = CONCAT(COALESCE(notes, ''), '\nRejection: ', ?) WHERE id = ?");
        $stmt->execute([$reason, $user_id]);
        
        echo "<div class='alert alert-warning alert-dismissible fade show'>
                <i class='bi bi-x-circle'></i> 
                User registration rejected!
                <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
              </div>";
        
    } elseif ($action == 'delete') {
        // Delete user and associated records
        $pdo->beginTransaction();
        try {
            // First, delete from leave_balance
            $stmt = $pdo->prepare("DELETE lb FROM leave_balance lb 
                                   JOIN employees e ON lb.employee_id = e.id 
                                   WHERE e.user_id = ?");
            $stmt->execute([$user_id]);
            
            // Delete from employees
            $stmt = $pdo->prepare("DELETE FROM employees WHERE user_id = ?");
            $stmt->execute([$user_id]);
            
            // Delete from users
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            
            $pdo->commit();
            
            echo "<div class='alert alert-info alert-dismissible fade show'>
                    <i class='bi bi-trash'></i> 
                    User registration deleted successfully!
                    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                  </div>";
            
        } catch (Exception $e) {
            $pdo->rollBack();
            echo "<div class='alert alert-danger alert-dismissible fade show'>
                    <i class='bi bi-exclamation-triangle'></i> 
                    Error deleting user: " . htmlspecialchars($e->getMessage()) . "
                    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                  </div>";
        }
    }
}

// Get pending registrations
$query = "SELECT u.id, u.username, u.email, u.created_at, 
          e.full_name, e.nic_passport, e.contact_number, e.department 
          FROM users u 
          JOIN employees e ON u.id = e.user_id 
          WHERE u.is_active = 0 AND u.role = 'employee' 
          ORDER BY u.created_at DESC";
$stmt = $pdo->query($query);
$pending_users = $stmt->fetchAll();

// Get pending count
$stmt = $pdo->query("SELECT COUNT(*) as count FROM users WHERE is_active = 0 AND role = 'employee'");
$pending_count = $stmt->fetch()['count'];
?>

<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-people me-2"></i>Pending Registrations</h5>
                <span class="badge bg-warning"><?php echo $pending_count; ?> Pending</span>
            </div>
            <div class="card-body">
                <?php if (empty($pending_users)): ?>
                <div class="alert alert-info text-center">
                    <i class="bi bi-check-circle fs-1 d-block mb-3"></i>
                    <h5>No pending registrations!</h5>
                    <p>All user accounts have been processed.</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-warning">
                            <tr>
                                <th>#</th>
                                <th>Full Name</th>
                                <th>Username</th>
                                <th>Contact</th>
                                <th>Department</th>
                                <th>Registered On</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($pending_users as $index => $user): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($user['full_name']); ?></strong>
                                    <br><small class="text-muted">NIC: <?php echo $user['nic_passport']; ?></small>
                                </td>
                                <td>
                                    <?php echo htmlspecialchars($user['username']); ?>
                                    <br><small class="text-muted"><?php echo $user['email']; ?></small>
                                </td>
                                <td><?php echo htmlspecialchars($user['contact_number']); ?></td>
                                <td><?php echo htmlspecialchars($user['department']); ?></td>
                                <td><?php echo date('d M Y, h:i A', strtotime($user['created_at'])); ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-success" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#approveModal<?php echo $user['id']; ?>">
                                            <i class="bi bi-check-circle"></i> Approve
                                        </button>
                                        <button class="btn btn-outline-danger" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#rejectModal<?php echo $user['id']; ?>">
                                            <i class="bi bi-x-circle"></i> Reject
                                        </button>
                                        <button class="btn btn-outline-secondary" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#viewModal<?php echo $user['id']; ?>">
                                            <i class="bi bi-eye"></i> View
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            
                            <!-- View Details Modal -->
                            <div class="modal fade" id="viewModal<?php echo $user['id']; ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Registration Details</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="mb-3">
                                                <h6>Personal Information</h6>
                                                <p><strong>Full Name:</strong> <?php echo htmlspecialchars($user['full_name']); ?></p>
                                                <p><strong>NIC/Passport:</strong> <?php echo $user['nic_passport']; ?></p>
                                                <p><strong>Contact:</strong> <?php echo $user['contact_number']; ?></p>
                                                <p><strong>Email:</strong> <?php echo $user['email']; ?></p>
                                            </div>
                                            <div class="mb-3">
                                                <h6>Account Information</h6>
                                                <p><strong>Username:</strong> <?php echo $user['username']; ?></p>
                                                <p><strong>Department:</strong> <?php echo $user['department']; ?></p>
                                                <p><strong>Registered:</strong> <?php echo date('d M Y, h:i A', strtotime($user['created_at'])); ?></p>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Approve Modal -->
                            <div class="modal fade" id="approveModal<?php echo $user['id']; ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST" action="">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <input type="hidden" name="action" value="approve">
                                            
                                            <div class="modal-header">
                                                <h5 class="modal-title">Approve Registration</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="alert alert-info">
                                                    <i class="bi bi-info-circle"></i> 
                                                    Are you sure you want to approve this registration?
                                                </div>
                                                <p><strong>User:</strong> <?php echo htmlspecialchars($user['full_name']); ?></p>
                                                <p><strong>Username:</strong> <?php echo $user['username']; ?></p>
                                                <p><strong>Department:</strong> <?php echo $user['department']; ?></p>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                <button type="submit" class="btn btn-success">Approve Registration</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Reject Modal -->
                            <div class="modal fade" id="rejectModal<?php echo $user['id']; ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST" action="">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <input type="hidden" name="action" value="reject">
                                            
                                            <div class="modal-header">
                                                <h5 class="modal-title">Reject Registration</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <div class="alert alert-warning">
                                                    <i class="bi bi-exclamation-triangle"></i> 
                                                    Are you sure you want to reject this registration?
                                                </div>
                                                <p><strong>User:</strong> <?php echo htmlspecialchars($user['full_name']); ?></p>
                                                <p><strong>Username:</strong> <?php echo $user['username']; ?></p>
                                                
                                                <div class="mb-3">
                                                    <label>Reason for Rejection *</label>
                                                    <textarea name="rejection_reason" class="form-control" rows="3" required 
                                                              placeholder="Please provide a reason for rejection..."></textarea>
                                                </div>
                                            </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">Reject Registration</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Bulk Actions -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h6 class="mb-0">Quick Actions</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <a href="dashboard.php?page=users" class="btn btn-primary w-100">
                                    <i class="bi bi-people"></i> View All Users
                                </a>
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-outline-secondary w-100" onclick="window.print()">
                                    <i class="bi bi-printer"></i> Print List
                                </button>
                            </div>
                            <div class="col-md-4">
                                <a href="dashboard.php" class="btn btn-secondary w-100">
                                    <i class="bi bi-house"></i> Back to Dashboard
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>