<?php
include('includes/auth.php');

$table_name = 'user';
$page = 'user.php';
$res = [get_admin_user($db)];

$error = '';
$success = false;

if (isset($_POST['submit'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request. Please try again.';
    } else {
        $newUsername = trim($_POST['username'] ?? '');
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if (empty($newUsername)) {
            $error = 'Username cannot be empty.';
        } elseif ($newUsername === 'admin') {
            $error = 'Please choose a username other than "admin".';
        } elseif (!empty($newPassword)) {
            if (!verify_password($currentPassword, $res[0]['password'])) {
                $error = 'Current password is incorrect.';
            } elseif (strlen($newPassword) < 8) {
                $error = 'New password must be at least 8 characters.';
            } elseif ($newPassword !== $confirmPassword) {
                $error = 'New passwords do not match.';
            } elseif ($newPassword === 'admin' || $newPassword === $newUsername) {
                $error = 'Password cannot be "admin" or the same as your username.';
            } else {
                $hashedPassword = hash_password($newPassword);
                $db->update($table_name, [
                    'username' => $newUsername,
                    'password' => $hashedPassword,
                    'password_changed_at' => date('Y-m-d H:i:s'),
                    'failed_attempts' => 0,
                    'locked_until' => null,
                ], 'id = :id', [':id' => 1]);

                session_regenerate_id(true);
                $_SESSION['name'] = $newUsername;
                $success = true;
                $res = [get_admin_user($db)];
            }
        } else {
            $db->update($table_name, [
                'username' => $newUsername,
            ], 'id = :id', [':id' => 1]);

            session_regenerate_id(true);
            $_SESSION['name'] = $newUsername;
            $success = true;
            $res = [get_admin_user($db)];
        }
    }
}

// --- All processing done, now output HTML ---
include('includes/header.php');

$csrfToken = generate_token();
$passwordAge = '';
if (!empty($res[0]['password_changed_at'])) {
    $changedAt = strtotime($res[0]['password_changed_at']);
    $daysAgo = floor((time() - $changedAt) / 86400);
    $passwordAge = $daysAgo === 0 ? 'Changed today' : "Changed {$daysAgo} day(s) ago";
}
?>

<div class="md-card md-card--elevated" style="max-width: 600px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('manage_accounts', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Update Credentials</h2>
    </div>
    <div class="md-card__content">
        <?php if ($res[0]['username'] === 'admin' || (!str_starts_with($res[0]['password'], '$2y$') && !str_starts_with($res[0]['password'], '$2b$'))): ?>
        <div class="md-alert md-alert--warning">
            <?= icon('warning') ?>
            <div>
                <strong>Security Notice:</strong> Please change the default credentials immediately.
            </div>
        </div>
        <?php endif; ?>

        <?php if ($error): ?>
        <div class="md-alert md-alert--error">
            <?= icon('error') ?>
            <span><?= htmlspecialchars($error) ?></span>
        </div>
        <?php endif; ?>

        <?php if ($success): ?>
        <div class="md-alert md-alert--success">
            <?= icon('check_circle') ?>
            <span>Credentials updated successfully.</span>
        </div>
        <?php endif; ?>

        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="username" id="username" class="md-text-field__input" placeholder=" " required
                       value="<?= htmlspecialchars($res[0]['username'] ?? '') ?>" autocomplete="username">
                <label for="username" class="md-text-field__label">Username</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <div class="md-divider-text">
                <span>Change Password</span>
            </div>

            <div class="md-text-field md-text-field--outlined">
                <input type="password" name="current_password" id="current_password" class="md-text-field__input" placeholder=" " autocomplete="current-password">
                <label for="current_password" class="md-text-field__label">Current Password</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <div class="md-text-field md-text-field--outlined">
                <input type="password" name="new_password" id="new_password" class="md-text-field__input" placeholder=" " minlength="8" autocomplete="new-password">
                <label for="new_password" class="md-text-field__label">New Password (min. 8 characters)</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <div class="md-text-field md-text-field--outlined">
                <input type="password" name="confirm_password" id="confirm_password" class="md-text-field__input" placeholder=" " autocomplete="new-password">
                <label for="confirm_password" class="md-text-field__label">Confirm New Password</label>
                <div class="md-text-field__indicator"></div>
            </div>

            <?php if ($passwordAge): ?>
            <p class="md-helper-text">
                <span style="font-size: 16px; vertical-align: middle;"><?= icon('schedule') ?></span>
                <?= htmlspecialchars($passwordAge) ?>
            </p>
            <?php endif; ?>

            <div class="md-card__actions">
                <button type="submit" name="submit" class="md-button md-button--filled">
                    <?= icon('save') ?>
                    <span class="md-button__label">Save Changes</span>
                </button>
            </div>
        </form>
    </div>
</div>

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