<?php
require_once __DIR__ . '/../config/master_database.php';
session_start();
if (empty($_SESSION['super_admin_id'])) { header('Location: login.php'); exit; }
$myId = (int) $_SESSION['super_admin_id'];

$errors = [];
$success = '';

// Toggle active/inactive (can't deactivate yourself)
if (($_GET['action'] ?? '') === 'toggle' && !empty($_GET['id'])) {
    $targetId = (int) $_GET['id'];
    if ($targetId === $myId) {
        $errors[] = "You can't deactivate your own account.";
    } else {
        $pdoMaster->prepare("UPDATE super_admins SET status = IF(status=1,0,1) WHERE id = ?")->execute([$targetId]);
        header('Location: admins.php'); exit;
    }
}

// Add a new super admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (!$name) $errors[] = 'Name is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
    if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters.';

    if (empty($errors)) {
        $chk = $pdoMaster->prepare("SELECT id FROM super_admins WHERE email = ?");
        $chk->execute([$email]);
        if ($chk->fetch()) {
            $errors[] = 'That email is already used by another super admin account.';
        } else {
            $pdoMaster->prepare("INSERT INTO super_admins (name, email, password, status) VALUES (?,?,?,1)")
                ->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT)]);
            $success = "Super admin '{$name}' created.";
        }
    }
}

$admins = $pdoMaster->query("SELECT * FROM super_admins ORDER BY created_at ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Super Admins</title>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/style.css?v=5">
</head>
<body style="padding:40px;max-width:800px;margin:0 auto;">
    <h2 style="font-family:var(--font-display);">Super Admins</h2>
    <p><a href="dashboard.php">&larr; Back to companies list</a></p>

    <?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
    <?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

    <table style="width:100%;border-collapse:collapse;margin-top:20px;">
        <thead>
            <tr style="text-align:left;border-bottom:2px solid #ddd;">
                <th style="padding:10px;">Name</th>
                <th style="padding:10px;">Email</th>
                <th style="padding:10px;">Status</th>
                <th style="padding:10px;">Created</th>
                <th style="padding:10px;"></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($admins as $a): ?>
            <tr style="border-bottom:1px solid #eee;">
                <td style="padding:10px;"><?= htmlspecialchars($a['name']) ?> <?= $a['id']==$myId ? '<span class="text-faint">(you)</span>' : '' ?></td>
                <td style="padding:10px;"><?= htmlspecialchars($a['email']) ?></td>
                <td style="padding:10px;"><?= $a['status'] ? 'Active' : 'Inactive' ?></td>
                <td style="padding:10px;"><?= htmlspecialchars($a['created_at']) ?></td>
                <td style="padding:10px;">
                    <?php if ($a['id'] != $myId): ?>
                    <a href="?action=toggle&id=<?= $a['id'] ?>" onclick="return confirm('Toggle status for this super admin?')">
                        <?= $a['status'] ? 'Deactivate' : 'Activate' ?>
                    </a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <h3 style="margin-top:32px;font-family:var(--font-display);">Add Super Admin</h3>
    <form method="POST">
        <input type="hidden" name="action" value="create">
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" required>
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="email" name="email" required>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="text" name="password" required>
        </div>
        <button type="submit" class="btn btn-primary">Create Super Admin</button>
    </form>
</body>
</html>