<?php
include '../includes/db.php';
include 'includes/header.php';

$message = "";

// Only super admin can add accounts
if ($_SESSION['role'] !== 'super_admin' && $_SESSION['email'] !== 'admin@uol.edu.pk') {
    header("Location: index.php");
    exit();
}

// Handle Add Admin
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_admin'])) {
    $full_name = $conn->real_escape_string($_POST['full_name']);
    $email = $conn->real_escape_string($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $role = $conn->real_escape_string($_POST['role']); // admin or super_admin

    if ($password === $confirm_password) {
        // Check if email already exists
        $check_sql = "SELECT id FROM users WHERE email = '$email'";
        if ($conn->query($check_sql)->num_rows > 0) {
            $message = "Error: Email already exists.";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            // Generate unique CNIC and phone for admin
            $unique_id = time() % 10000000000; // Generate 10-digit unique ID
            $cnic = str_pad($unique_id, 13, '0', STR_PAD_LEFT);
            $phone = '0000000000';
            
            $sql = "INSERT INTO users (full_name, email, password, role, cnic, phone) VALUES ('$full_name', '$email', '$hashed_password', '$role', '$cnic', '$phone')";
            
            if ($conn->query($sql) === TRUE) {
                $message = "New admin added successfully!";
            } else {
                $message = "Error adding admin: " . $conn->error;
            }
        }
    } else {
        $message = "Error: Passwords do not match.";
    }
}

// Handle Delete Admin
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    
    // Check if system admin
    $check_sys = $conn->query("SELECT email FROM users WHERE id = $id");
    if($check_sys->num_rows > 0 && $check_sys->fetch_assoc()['email'] == 'admin@uol.edu.pk') {
        $message = "Error: Cannot delete the System Administrator account.";
    } elseif ($_SESSION['user_id'] == $id) {
        $message = "Error: You cannot delete your own account.";
    } else {
        $sql = "DELETE FROM users WHERE id = $id AND role = 'admin'";
        if ($conn->query($sql) === TRUE) {
            $message = "Admin deleted successfully!";
        } else {
            $message = "Error deleting admin.";
        }
    }
}

// Fetch Admins
$sql = "SELECT * FROM users WHERE role = 'admin' ORDER BY created_at DESC";
$result = $conn->query($sql);
?>

<div class="dashboard-container">
    <div class="sidebar admin-sidebar">
        <?php include 'includes/sidebar.php'; ?>
    </div>

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Manage Admins</h3>
                <button onclick="document.getElementById('add-admin-form').style.display='block'" class="btn-primary" style="padding: 5px 15px;">
                    <i class="fas fa-plus"></i> Add New Admin
                </button>
            </div>
            
            <?php if($message): ?>
                <div class="alert alert-info"><?php echo $message; ?></div>
            <?php endif; ?>

            <div id="add-admin-form" style="display: none; background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px; border: 1px solid #ddd;">
                <h4 style="margin-top: 0;">Add New Administrator</h4>
                <form method="POST" action="">
                    <input type="hidden" name="add_admin" value="1">
                    <div class="form-group">
                        <label>Full Name</label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Role</label>
                        <select name="role" class="form-control" required>
                            <option value="">-- Select Role --</option>
                            <option value="admin">Admin</option>
                            <option value="super_admin">Super Admin</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Confirm Password</label>
                        <input type="password" name="confirm_password" class="form-control" required>
                    </div>
                    <div style="margin-top: 15px;">
                        <button type="submit" class="btn-primary">Create Admin</button>
                        <button type="button" onclick="document.getElementById('add-admin-form').style.display='none'" class="btn-outline">Cancel</button>
                    </div>
                </form>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): ?>
                        <tr>
                            <td>#<?php echo $row['id']; ?></td>
                            <td><?php echo $row['full_name']; ?></td>
                            <td><?php echo $row['email']; ?></td>
                            <td>
                                <?php
                                $role_class = '';
                                switch($row['role']) {
                                    case 'super_admin':
                                        $role_class = 'badge-danger';
                                        break;
                                    case 'admin':
                                        $role_class = 'badge-warning';
                                        break;
                                    case 'system_admin':
                                        $role_class = 'badge-info';
                                        break;
                                }
                                ?>
                                <span class="badge <?php echo $role_class; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $row['role'])); ?>
                                </span>
                            </td>
                            <td><?php echo date('d M, Y', strtotime($row['created_at'])); ?></td>
                            <td>
                                <?php if($row['email'] == 'admin@uol.edu.pk'): ?>
                                    <span class="badge badge-warning" style="background: #ff9800; color: white;">System Admin</span>
                                <?php elseif($row['id'] == $_SESSION['user_id']): ?>
                                    <span class="badge badge-info">You</span>
                                <?php else: ?>
                                    <a href="manage_admins.php?delete=<?php echo $row['id']; ?>" onclick="return confirm('Are you sure you want to delete this admin?');" style="color: #d32f2f; text-decoration: none;">
                                        <i class="fas fa-trash"></i> Delete
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center">No admins found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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