<?php

session_start();

require_once __DIR__ . '/../../library/config.php';
require_once __DIR__ . '/../../library/super_admin_auth.php';
require_once __DIR__ . '/../../library/super_admin_audit_log.php';

$page_title = 'Manage Super Admins';

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';

$error = '';
$success = '';

// ======================================================
// GET SUPER ADMIN DATA
// ======================================================

$super_admin_id = $_SESSION['super_admin_id'] ?? null;
$super_admin_name = $_SESSION['super_admin_name'] ?? 'Unknown';
$super_admin_email = $_SESSION['super_admin_email'] ?? 'Unknown';

// ======================================================
// DELETE SUPER ADMIN
// ======================================================

if (isset($_GET['delete'])) {
    $delete_id = (int) $_GET['delete'];

    if ($delete_id == $super_admin_id) {
        $error = 'You cannot delete your own account!';
    } else {
        // Fetch admin data before delete
        $checkStmt = $pdo->prepare("
            SELECT id, full_name, email
            FROM super_admins
            WHERE id = ?
            LIMIT 1
        ");
        $checkStmt->execute([$delete_id]);
        $admin_to_delete = $checkStmt->fetch(PDO::FETCH_ASSOC);

        if ($admin_to_delete) {
            $deleteStmt = $pdo->prepare("
                DELETE FROM super_admins
                WHERE id = ?
                LIMIT 1
            ");
            $deleteStmt->execute([$delete_id]);

            // Audit Log
            logSuperAdminActivity($pdo, [
                'super_admin_id'   => $super_admin_id,
                'super_admin_email' => $super_admin_email,
                'super_admin_name'  => $super_admin_name,
                'module'            => 'Super Admin Management',
                'action'            => 'DELETE',
                'record_id'         => $delete_id,
                'message'           => "Super admin deleted: {$admin_to_delete['full_name']}",
                'old_data'          => [
                    'id'     => $delete_id,
                    'name'   => $admin_to_delete['full_name'],
                    'email'  => $admin_to_delete['email']
                ],
                'new_data'          => null
            ]);

            $success = 'Super admin deleted successfully!';
        } else {
            $error = 'Super admin not found!';
        }
    }
}

// ======================================================
// FORM SUBMIT (ADD/EDIT)
// ======================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_admin'])) {
    $admin_id = (int) ($_POST['admin_id'] ?? 0);
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');
    $password = $_POST['password'] ?? '';
    $status = trim($_POST['status'] ?? 'Active');

    // Validation
    if (empty($full_name) || empty($email)) {
        $error = 'Name and Email are required!';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email address!';
    } elseif (strlen($password) > 0 && strlen($password) < 6) {
        $error = 'Password must be at least 6 characters!';
    } elseif (!in_array($status, ['Active', 'Inactive'])) {
        $error = 'Invalid status!';
    } else {
        try {
            if ($admin_id > 0) {
                // EDIT MODE

                // Check if email exists for other admin
                $checkStmt = $pdo->prepare("
                    SELECT id, full_name, email, password, status
                    FROM super_admins
                    WHERE email = ?
                    AND id != ?
                    LIMIT 1
                ");
                $checkStmt->execute([$email, $admin_id]);
                $existing = $checkStmt->fetch(PDO::FETCH_ASSOC);

                if ($existing) {
                    $error = 'Email already exists!';
                } else {
                    // Store old data
                    $old_data = [
                        'full_name' => $existing['full_name'],
                        'email'     => $existing['email'],
                        'mobile'    => $existing['mobile'] ?? null,
                        'status'    => $existing['status']
                    ];

                    // Update query
                    if (!empty($password)) {
                        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                        $updateStmt = $pdo->prepare("
                            UPDATE super_admins
                            SET full_name = ?,
                                email = ?,
                                mobile = ?,
                                password = ?,
                                status = ?
                            WHERE id = ?
                            LIMIT 1
                        ");
                        $updateStmt->execute([
                            $full_name, $email, $mobile, $hashedPassword, $status, $admin_id
                        ]);
                    } else {
                        $updateStmt = $pdo->prepare("
                            UPDATE super_admins
                            SET full_name = ?,
                                email = ?,
                                mobile = ?,
                                status = ?
                            WHERE id = ?
                            LIMIT 1
                        ");
                        $updateStmt->execute([
                            $full_name, $email, $mobile, $status, $admin_id
                        ]);
                    }

                    // Audit Log
                    $new_data = [
                        'full_name' => $full_name,
                        'email'     => $email,
                        'mobile'    => $mobile,
                        'status'    => $status
                    ];

                    logSuperAdminActivity($pdo, [
                        'super_admin_id'   => $super_admin_id,
                        'super_admin_email' => $super_admin_email,
                        'super_admin_name'  => $super_admin_name,
                        'module'            => 'Super Admin Management',
                        'action'            => 'UPDATE',
                        'record_id'         => $admin_id,
                        'message'           => "Super admin updated: {$full_name}",
                        'old_data'          => $old_data,
                        'new_data'          => $new_data
                    ]);

                    $success = 'Super admin updated successfully!';
                }
            } else {
                // ADD MODE

                // Check if email exists
                $checkStmt = $pdo->prepare("
                    SELECT id, full_name
                    FROM super_admins
                    WHERE email = ?
                    LIMIT 1
                ");
                $checkStmt->execute([$email]);
                if ($checkStmt->fetch()) {
                    $error = 'Email already exists!';
                } elseif (empty($password)) {
                    $error = 'Password is required for new admin!';
                } else {
                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

                    $insertStmt = $pdo->prepare("
                        INSERT INTO super_admins
                        (full_name, email, mobile, password, status)
                        VALUES
                        (?, ?, ?, ?, ?)
                    ");
                    $insertStmt->execute([
                        $full_name, $email, $mobile, $hashedPassword, $status
                    ]);

                    $new_admin_id = $pdo->lastInsertId();

                    // Audit Log
                    logSuperAdminActivity($pdo, [
                        'super_admin_id'   => $super_admin_id,
                        'super_admin_email' => $super_admin_email,
                        'super_admin_name'  => $super_admin_name,
                        'module'            => 'Super Admin Management',
                        'action'            => 'CREATE',
                        'record_id'         => $new_admin_id,
                        'message'           => "Super admin created: {$full_name}",
                        'old_data'          => null,
                        'new_data'          => [
                            'full_name' => $full_name,
                            'email'     => $email,
                            'mobile'    => $mobile,
                            'status'    => $status
                        ]
                    ]);

                    $success = 'Super admin created successfully!';
                }
            }
        } catch (Exception $e) {
            error_log('Super Admin CRUD ERROR: ' . $e->getMessage());
            $error = 'Something went wrong!';
        }
    }
}

// ======================================================
// FETCH EDIT DATA
// ======================================================

$edit_data = [
    'admin_id' => '',
    'full_name' => '',
    'email' => '',
    'mobile' => '',
    'password' => '',
    'status' => 'Active'
];

if (isset($_GET['edit'])) {
    $edit_id = (int) $_GET['edit'];
    $stmt = $pdo->prepare("
        SELECT *
        FROM super_admins
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$edit_id]);
    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC) ?: $edit_data;
}

// ======================================================
// FETCH ALL SUPER ADMINS
// ======================================================

$stmt = $pdo->prepare("
    SELECT *
    FROM super_admins
    ORDER BY id DESC
");
$stmt->execute();
$admins = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ======================================================
// CSRF TOKEN
// ======================================================

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

?>
<section class="content-header">

    <div class="container-fluid">

        <div class="row mb-2">

            <div class="col-sm-6">

                <h1>

                    Manage Super Admins

                </h1>

            </div>

        </div>

    </div>

</section>

<!-- Main Content -->

<section class="content">

    <div class="container-fluid">

        <?php if ($error): ?>

            <div class="alert alert-danger">

                <?= htmlspecialchars($error); ?>

            </div>

        <?php endif; ?>

        <?php if ($success): ?>

            <div class="alert alert-success">

                <?= htmlspecialchars($success); ?>

            </div>

        <?php endif; ?>

        <!-- Add/Edit Form Card -->

        <div class="card card-<?= $edit_data['admin_id'] ? 'success' : 'primary' ?>">

            <div class="card-header">

                <h3 class="card-title">

                    <i class="fas fa-user-plus mr-2"></i>

                    <?= $edit_data['admin_id'] ? 'Edit' : 'Add' ?> Super Admin

                </h3>

            </div>

            <form method="POST">

                <input
                    type="hidden"
                    name="admin_id"
                    value="<?= htmlspecialchars($edit_data['admin_id']); ?>"
                >

                <input
                    type="hidden"
                    name="save_admin"
                    value="1"
                >

                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= htmlspecialchars($_SESSION['csrf_token']); ?>"
                >

                <div class="card-body">

                    <!-- Full Name -->

                    <div class="form-group">

                        <label>

                            Full Name <span class="text-danger">*</span>

                        </label>

                        <input
                            type="text"
                            name="full_name"
                            class="form-control"
                            required
                            maxlength="100"
                            value="<?= htmlspecialchars($edit_data['full_name'] ?? ''); ?>"
                            placeholder="Enter full name"
                        >

                    </div>

                    <!-- Email -->

                    <div class="form-group">

                        <label>

                            Email <span class="text-danger">*</span>

                        </label>

                        <input
                            type="email"
                            name="email"
                            class="form-control"
                            required
                            maxlength="150"
                            value="<?= htmlspecialchars($edit_data['email'] ?? ''); ?>"
                            placeholder="Enter email"
                            <?= $edit_data['admin_id'] ? 'readonly' : '' ?>
                        >

                    </div>

                    <!-- Mobile -->

                    <div class="form-group">

                        <label>

                            Mobile

                        </label>

                        <input
                            type="text"
                            name="mobile"
                            class="form-control"
                            maxlength="20"
                            value="<?= htmlspecialchars($edit_data['mobile'] ?? ''); ?>"
                            placeholder="Enter mobile number"
                        >

                    </div>

                    <!-- Password -->

                    <div class="form-group">

                        <label>

                            Password <?= !$edit_data['admin_id'] ? '<span class="text-danger">*</span>' : '' ?>

                        </label>

                        <input
                            type="password"
                            name="password"
                            class="form-control"
                            minlength="<?= $edit_data['admin_id'] ? '' : '6' ?>"
                            placeholder="<?= $edit_data['admin_id'] ? 'Leave blank to keep same' : 'Min 6 characters' ?>"
                            <?= $edit_data['admin_id'] ? '' : 'required' ?>
                        >

                    </div>

                    <!-- Status -->

                    <div class="form-group">

                        <label>

                            Status

                        </label>

                        <select
                            name="status"
                            class="form-control"
                        >

                            <option
                                value="Active"
                                <?= ($edit_data['status'] ?? '') === 'Active' ? 'selected' : '' ?>
                            >

                                Active

                            </option>

                            <option
                                value="Inactive"
                                <?= ($edit_data['status'] ?? '') === 'Inactive' ? 'selected' : '' ?>
                            >

                                Inactive

                            </option>

                        </select>

                    </div>

                </div>

                <div class="card-footer">

                    <button
                        type="submit"
                        class="btn btn-<?= $edit_data['admin_id'] ? 'success' : 'primary' ?>"
                    >

                        <i class="fas fa-save"></i>

                        <?= $edit_data['admin_id'] ? 'Update' : 'Create' ?> Admin

                    </button>

                    <?php if ($edit_data['admin_id']): ?>

                        <a
                            href="manage_super_admins.php"
                            class="btn btn-secondary"
                        >

                            Cancel

                        </a>

                    <?php endif; ?>

                    <a
                        href="index.php"
                        class="btn btn-info float-right"
                    >

                        <i class="fas fa-arrow-left"></i>

                        Back to Schools

                    </a>

                </div>

            </form>

        </div>

        <!-- Table Card -->

        <div class="card card-info mt-4">

            <div class="card-header">

                <h3 class="card-title">

                    <i class="fas fa-users mr-2"></i>

                    All Super Admins (<?= count($admins) ?>)

                </h3>

            </div>

            <div class="card-body p-0">

                <table
                    class="table table-bordered table-striped table-hover mb-0"
                >

                    <thead class="bg-info">

                        <tr>

                            <th width="5%" class="text-center">#</th>

                            <th width="25%">Name</th>

                            <th width="30%">Email</th>

                            <th width="15%">Mobile</th>

                            <th width="10%" class="text-center">Status</th>

                            <th width="15%">Last Login</th>

                        </tr>

                    </thead>

                    <tbody>

                        <?php if (count($admins) > 0): ?>

                            <?php foreach ($admins as $i => $admin): ?>

                                <tr>

                                    <td class="text-center"><?= $i + 1 ?></td>

                                    <td>

                                        <strong>

                                            <?= htmlspecialchars($admin['full_name']); ?>

                                        </strong>

                                    </td>

                                    <td>

                                        <?= htmlspecialchars($admin['email']); ?>

                                    </td>

                                    <td>

                                        <?= htmlspecialchars($admin['mobile'] ?? '-'); ?>

                                    </td>

                                    <td class="text-center">

                                        <span class="badge badge-<?= $admin['status'] === 'Active' ? 'success' : 'secondary' ?>">

                                            <?= $admin['status']; ?>

                                        </span>

                                    </td>

                                    <td>

                                        <small>

                                            <?= $admin['last_login'] ? date('d M y h:i A', strtotime($admin['last_login'])) : 'Never'; ?>

                                        </small>

                                    </td>

                                </tr>

                            <?php endforeach; ?>

                        <?php else: ?>

                            <tr>

                                <td
                                    colspan="6"
                                    class="text-center text-muted py-5"
                                >

                                    <i class="fas fa-inbox fa-3x mb-3 d-block"></i>

                                    <p class="mb-0">

                                        No Super Admins Found!

                                    </p>

                                </td>

                            </tr>

                        <?php endif; ?>

                    </tbody>

                </table>

            </div>

            <!-- Actions Footer -->

            <div class="card-footer">

                <small class="text-muted">

                    <i class="fas fa-info-circle mr-1"></i>

                    Total: <?= count($admins) ?> Super Admin(s)

                </small>

                <div class="float-right">

                    <?php foreach ($admins as $admin): ?>

                        <?php if ($admin['id'] != $super_admin_id): ?>

                            <a

                                href="?delete=<?= $admin['id']; ?>"

                                class="btn btn-sm btn-danger mr-1"

                                onclick="return confirm('Are you sure you want to delete <?= htmlspecialchars($admin['full_name']); ?>?')"

                                title="Delete <?= htmlspecialchars($admin['full_name']); ?>"

                            >

                                <i class="fas fa-trash"></i>

                                Delete

                            </a>

                        <?php endif; ?>

                    <?php endforeach; ?>

                </div>

            </div>

        </div>

    </div>

</section>
<?php
require_once __DIR__ . '/../includes/footer.php';
?>