<?php
session_start();
require_once __DIR__ . '/../includes/config.php';
requireAdminLogin();

$adminPageTitle = 'Change Password';
$db = getDB();
$errors  = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current  = $_POST['current_password'] ?? '';
    $new      = $_POST['new_password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';

    $stmt = $db->prepare("SELECT password FROM admin_users WHERE username = ?");
    $stmt->execute([$_SESSION['admin_username']]);
    $admin = $stmt->fetch();

    if (!$admin || !password_verify($current, $admin['password'])) {
        $errors[] = 'Current password is incorrect.';
    } elseif (strlen($new) < 6) {
        $errors[] = 'New password must be at least 6 characters.';
    } elseif ($new !== $confirm) {
        $errors[] = 'New passwords do not match.';
    } else {
        $db->prepare("UPDATE admin_users SET password=? WHERE username=?")
           ->execute([password_hash($new, PASSWORD_DEFAULT), $_SESSION['admin_username']]);
        $success = 'Password changed successfully!';
    }
}

include __DIR__ . '/partials/admin_header.php';
?>

<div class="row justify-content-center">
<div class="col-xl-5 col-lg-7">
<?php if ($success): ?>
<div class="alert alert-success"><i class="fas fa-check-circle me-2"></i><?= sanitize($success) ?></div>
<?php endif; ?>
<?php if ($errors): ?>
<div class="alert alert-danger"><?php foreach ($errors as $e): ?><div><?= sanitize($e) ?></div><?php endforeach; ?></div>
<?php endif; ?>

<div class="table-card">
    <div class="card-header"><i class="fas fa-key me-2 text-primary"></i>Change Admin Password</div>
    <div class="p-4">
        <form method="POST" action="">
            <div class="mb-3">
                <label class="form-label fw-semibold">Current Password</label>
                <input type="password" name="current_password" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label fw-semibold">New Password</label>
                <input type="password" name="new_password" class="form-control" minlength="6" required>
                <small class="text-muted">Minimum 6 characters</small>
            </div>
            <div class="mb-4">
                <label class="form-label fw-semibold">Confirm New Password</label>
                <input type="password" name="confirm_password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary w-100 py-2">
                <i class="fas fa-key me-2"></i>Update Password
            </button>
        </form>
    </div>
</div>
</div>
</div>

<?php include __DIR__ . '/partials/admin_footer.php'; ?>
