<?php
require_once __DIR__ . '/../../includes/init.php';
middleware();

$db      = getDBConnection();
$uid     = (int)getSession('user_id');
$success = '';
$error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        $current  = $_POST['current_pass'] ?? '';
        $newPass  = $_POST['new_pass']     ?? '';
        $confirm  = $_POST['confirm_pass'] ?? '';

        if (!$current || !$newPass || !$confirm) {
            $error = 'All fields are required.';
        } elseif (strlen($newPass) < 6) {
            $error = 'New password must be at least 6 characters.';
        } elseif ($newPass !== $confirm) {
            $error = 'New passwords do not match.';
        } else {
            $user = dbRow($db, "SELECT password FROM users WHERE id=?", [$uid]);
            if ($user && password_verify($current, $user['password'])) {
                $db->prepare("UPDATE users SET password=? WHERE id=?")
                   ->execute([password_hash($newPass, PASSWORD_BCRYPT), $uid]);
                $success = 'Password changed successfully.';
            } else {
                $error = 'Current password is incorrect.';
            }
        }
    }
}

$pageTitle = 'Change Password';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><h1><i class="bi bi-shield-lock me-2 text-primary"></i>Change Password</h1></div>
</div>

<?php if ($success): ?>
<div class="alert alert-success d-flex align-items-center gap-2">
    <i class="bi bi-check-circle-fill"></i><?= h($success) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger"><?= h($error) ?></div>
<?php endif; ?>

<div class="erp-card" style="max-width:440px;">
    <form method="POST" novalidate>
        <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

        <div class="mb-3">
            <label class="form-label fw-semibold" style="font-size:.86rem;">Current Password <span class="text-danger">*</span></label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-lock-fill text-muted"></i></span>
                <input type="password" name="current_pass" id="cp1" class="form-control" required autocomplete="current-password">
                <button type="button" class="input-group-text bg-white border-start-0" onclick="toggleP('cp1','ci1')" style="cursor:pointer;">
                    <i class="bi bi-eye" id="ci1"></i>
                </button>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold" style="font-size:.86rem;">New Password <span class="text-danger">*</span></label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-lock-fill text-muted"></i></span>
                <input type="password" name="new_pass" id="cp2" class="form-control" required autocomplete="new-password" placeholder="Min 6 characters">
                <button type="button" class="input-group-text bg-white border-start-0" onclick="toggleP('cp2','ci2')" style="cursor:pointer;">
                    <i class="bi bi-eye" id="ci2"></i>
                </button>
            </div>
        </div>

        <div class="mb-4">
            <label class="form-label fw-semibold" style="font-size:.86rem;">Confirm New Password <span class="text-danger">*</span></label>
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-lock-fill text-muted"></i></span>
                <input type="password" name="confirm_pass" id="cp3" class="form-control" required autocomplete="new-password">
                <button type="button" class="input-group-text bg-white border-start-0" onclick="toggleP('cp3','ci3')" style="cursor:pointer;">
                    <i class="bi bi-eye" id="ci3"></i>
                </button>
            </div>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-erp flex-fill">
                <i class="bi bi-shield-check me-2"></i>Change Password
            </button>
            <a href="<?= BASE_URL ?>/modules/profile/index.php" class="btn btn-outline-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
function toggleP(id, ico) {
    const i = document.getElementById(id), c = document.getElementById(ico);
    i.type = i.type === 'password' ? 'text' : 'password';
    c.className = i.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}
</script>

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