<?php
require 'includes/auth.php';
require_once '../app/db.php';

if ($_SESSION['admin_role'] !== 'superadmin') {
    die("Access denied.");
}

$message = "";

/* ===== CREATE ADMIN ===== */
if (isset($_POST['create_admin'])) {

    $name  = trim($_POST['name']);
    $email = trim($_POST['email']);
    $role  = $_POST['role'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    if (!$name || !$email || !$_POST['password']) {
        $message = "All fields are required.";
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO admins (name,email,password,role)
                VALUES (?,?,?,?)
            ");
            $stmt->execute([$name,$email,$password,$role]);
            $message = "Admin created successfully.";
        } catch (Exception $e) {
            $message = "Email already exists.";
        }
    }
}

/* ===== DELETE ADMIN ===== */
if (isset($_GET['delete'])) {

    $id = (int)$_GET['delete'];

    if ($id == $_SESSION['admin_id']) {
        $message = "You cannot delete yourself.";
    } else {

        // Check last superadmin
        $roleCheck = $pdo->prepare("SELECT role FROM admins WHERE id=?");
        $roleCheck->execute([$id]);
        $target = $roleCheck->fetch();

        if ($target && $target['role'] === 'superadmin') {

            $count = $pdo->query("
                SELECT COUNT(*) FROM admins WHERE role='superadmin'
            ")->fetchColumn();

            if ($count <= 1) {
                $message = "Cannot delete the last superadmin.";
            } else {
                $pdo->prepare("DELETE FROM admins WHERE id=?")
                    ->execute([$id]);
                $message = "Admin deleted.";
            }
        } else {
            $pdo->prepare("DELETE FROM admins WHERE id=?")
                ->execute([$id]);
            $message = "Admin deleted.";
        }
    }
}

/* ===== RESET PASSWORD ===== */
if (isset($_POST['reset_password'])) {

    $id = $_POST['admin_id'];
    $newPass = password_hash($_POST['new_password'], PASSWORD_DEFAULT);

    $pdo->prepare("UPDATE admins SET password=? WHERE id=?")
        ->execute([$newPass,$id]);

    $message = "Password reset successfully.";
}

/* ===== FETCH ADMINS ===== */
$admins = $pdo->query("
    SELECT * FROM admins
    ORDER BY created_at DESC
");

$totalAdmins = $pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();
$totalSuper  = $pdo->query("
    SELECT COUNT(*) FROM admins WHERE role='superadmin'
")->fetchColumn();

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

<style>
.content-wrapper { background:#0B0F19; }

.card-luxury {
    background: linear-gradient(135deg,#1F2937,#0B0F19);
    border-left:4px solid #C9A24D;
    color:#E5E7EB;
}

.btn-gold {
    background:#C9A24D;
    color:#0B0F19;
    font-weight:600;
}
.btn-gold:hover {
    background:#b88f3f;
    color:#0B0F19;
}

.form-control {
    background:#0B0F19;
    color:#E5E7EB;
    border:1px solid #1F2937;
}

.badge-super {
    background:#C9A24D;
    color:#0B0F19;
    font-weight:600;
}

.badge-manager {
    background:#6c757d;
}

.stats-box {
    background:#1F2937;
    padding:15px;
    border-radius:6px;
    text-align:center;
}
</style>

<div class="content-wrapper">
<section class="content pt-4">
<div class="container-fluid">

<h3 class="text-warning mb-4">Admin User Management</h3>

<?php if($message): ?>
<div class="alert alert-info"><?= $message ?></div>
<?php endif; ?>

<!-- STATISTICS -->
<div class="row mb-4">

<div class="col-md-6">
<div class="stats-box">
<h4 class="text-warning"><?= $totalAdmins ?></h4>
<small>Total Admin Accounts</small>
</div>
</div>

<div class="col-md-6">
<div class="stats-box">
<h4 class="text-warning"><?= $totalSuper ?></h4>
<small>Superadmins</small>
</div>
</div>

</div>

<div class="row">

<!-- CREATE ADMIN -->
<div class="col-md-4">
<div class="card card-luxury p-4">

<h5>Create New Admin</h5>

<form method="POST">

<div class="form-group">
<input type="text" name="name"
class="form-control"
placeholder="Full Name" required>
</div>

<div class="form-group">
<input type="email" name="email"
class="form-control"
placeholder="Email" required>
</div>

<div class="form-group">
<input type="password" name="password"
class="form-control"
placeholder="Password" required>
</div>

<div class="form-group">
<select name="role" class="form-control">
<option value="manager">Manager</option>
<option value="superadmin">Superadmin</option>
</select>
</div>

<button type="submit"
name="create_admin"
class="btn btn-gold btn-block">
Create Admin
</button>

</form>

</div>
</div>

<!-- ADMIN TABLE -->
<div class="col-md-8">
<div class="card card-luxury p-4">

<h5>Existing Admin Users</h5>

<table class="table table-dark table-bordered mt-3">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Created</th>
<th width="220">Actions</th>
</tr>
</thead>

<tbody>
<?php foreach($admins as $admin): ?>
<tr>
<td><?= htmlspecialchars($admin['name']) ?></td>
<td><?= htmlspecialchars($admin['email']) ?></td>
<td>
<?php if($admin['role']=='superadmin'): ?>
<span class="badge badge-super">SUPERADMIN</span>
<?php else: ?>
<span class="badge badge-manager">MANAGER</span>
<?php endif; ?>
</td>
<td><?= $admin['created_at'] ?></td>

<td>

<a href="admin_edit.php?id=<?= $admin['id'] ?>"
class="btn btn-sm btn-info">
Edit
</a>

<button class="btn btn-sm btn-secondary"
data-toggle="modal"
data-target="#resetModal<?= $admin['id'] ?>">
Reset
</button>

<?php if($admin['id'] != $_SESSION['admin_id']): ?>
<a href="?delete=<?= $admin['id'] ?>"
class="btn btn-sm btn-danger"
onclick="return confirm('Delete this admin?')">
Delete
</a>
<?php endif; ?>

</td>
</tr>

<!-- RESET PASSWORD MODAL -->
<div class="modal fade"
id="resetModal<?= $admin['id'] ?>">
<div class="modal-dialog">
<div class="modal-content bg-dark text-light">

<div class="modal-header">
<h5>Reset Password</h5>
<button type="button"
class="close text-light"
data-dismiss="modal">&times;</button>
</div>

<form method="POST">
<div class="modal-body">

<input type="hidden"
name="admin_id"
value="<?= $admin['id'] ?>">

<input type="password"
name="new_password"
class="form-control"
placeholder="New Password"
required>

</div>

<div class="modal-footer">
<button type="submit"
name="reset_password"
class="btn btn-gold">
Reset Password
</button>
</div>
</form>

</div>
</div>
</div>

<?php endforeach; ?>
</tbody>

</table>

</div>
</div>

</div>

</div>
</section>
</div>

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