<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
$title = 'Account';
$notice = '';
$error = '';

if (!$pdo) {
    admin_redirect('index.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
        $error = 'Security token expired. Please try again.';
    } else {
        $current = (string) (isset($_POST['current_password']) ? $_POST['current_password'] : '');
        $new = (string) (isset($_POST['new_password']) ? $_POST['new_password'] : '');
        $confirm = (string) (isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '');

        $stmt = $pdo->prepare('SELECT * FROM admins WHERE id = ? LIMIT 1');
        $stmt->execute(array((int) $_SESSION['admin_id']));
        $admin = $stmt->fetch();

        if (!$admin || !password_verify($current, $admin['password_hash'])) {
            $error = 'Current password is incorrect.';
        } elseif (strlen($new) < 8) {
            $error = 'New password must be at least 8 characters.';
        } elseif ($new !== $confirm) {
            $error = 'New password confirmation does not match.';
        } else {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare('UPDATE admins SET password_hash = ? WHERE id = ?');
            $stmt->execute(array($hash, (int) $_SESSION['admin_id']));
            $notice = 'Password changed successfully.';
        }
    }
}

require __DIR__ . '/_header.php';
?>
<div class="admin-card p-4 p-lg-5" style="max-width:680px">
    <h1 class="h4 mb-2">Account Settings</h1>
    <p class="admin-muted">Change the default admin password after setup.</p>
    <?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>
    <form method="post">
        <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
        <div class="mb-3"><label class="form-label">Current password</label><input type="password" class="form-control" name="current_password" required></div>
        <div class="mb-3"><label class="form-label">New password</label><input type="password" class="form-control" name="new_password" required minlength="8"></div>
        <div class="mb-3"><label class="form-label">Confirm new password</label><input type="password" class="form-control" name="confirm_password" required minlength="8"></div>
        <button class="btn btn-primary" type="submit">Change Password</button>
    </form>
</div>
<?php require __DIR__ . '/_footer.php'; ?>
