<?php
session_start();

/* Both staff and company_admin can use this page */
if (!isset($_SESSION["user_id"]) || !in_array($_SESSION["role"], ["staff","company_admin"])) {
    header("Location: ../auth/login.php");
    exit;
}

require_once '../config/database.php';

$userId  = (int)$_SESSION["user_id"];
$role    = $_SESSION["role"];
$errors  = [];
$success = false;

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

    /* Load current hash */
    $st = $pdo->prepare("SELECT password FROM users WHERE id = ?");
    $st->execute([$userId]);
    $hash = $st->fetchColumn();

    /* Validate */
    if (!password_verify($current, $hash)) {
        $errors[] = "Current password is incorrect.";
    }
    if ($new === "") {
        $errors[] = "New password is required.";
    }
    if ($new !== $confirm) {
        $errors[] = "New passwords do not match.";
    }

    if (empty($errors)) {
        $newHash = password_hash($new, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$newHash, $userId]);
        $success = true;
    }
}

/* Back link depends on role */
$backLink = $role === "company_admin" ? "dashboard.php" : "dashboard.php";
$portalName = $role === "company_admin"
    ? htmlspecialchars($_SESSION["company_name"] ?? "Company Portal")
    : htmlspecialchars($_SESSION["company_name"] ?? "Staff Portal");
?>
<!DOCTYPE html>
<html lang="lo">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #2563eb; --surface: #fff; --bg: #f0f4f8;
            --border: #e2e8f0; --text: #0f172a; --muted: #64748b;
            --green: #16a34a; --green-lt: #dcfce7;
            --red: #dc2626; --red-lt: #fee2e2;
            --radius: 14px; --shadow: 0 2px 14px rgba(15,23,42,.09);
        }
        body { font-family: "Noto Sans Lao","Inter",Arial,sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; }

        /* top bar */
        .top-bar { background: var(--surface); border-bottom: 1px solid var(--border); padding: 12px 32px; display: flex; align-items: center; gap: 14px; position: sticky; top: 0; z-index: 100; box-shadow: 0 1px 6px rgba(15,23,42,.06); }
        .back { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); text-decoration: none; font-size: 13px; font-weight: 600; padding: 6px 12px; border-radius: 8px; border: 1.5px solid var(--border); transition: all .15s; }
        .back:hover { border-color: var(--primary); color: var(--primary); }
        .top-bar h1 { font-size: 17px; font-weight: 800; flex: 1; }
        .top-bar-user { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--muted); }
        .avatar { width: 32px; height: 32px; border-radius: 50%; background: linear-gradient(135deg,#1e3a5f,#2563eb); display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 800; font-size: 13px; flex-shrink: 0; }

        /* page */
        .page-body { padding: 40px 32px; max-width: 520px; margin: auto; }

        /* card */
        .card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 32px; }

        .card-icon { width: 56px; height: 56px; border-radius: 16px; background: #eff6ff; display: flex; align-items: center; justify-content: center; font-size: 26px; margin-bottom: 18px; }
        .card-title { font-size: 20px; font-weight: 800; margin-bottom: 6px; }
        .card-sub { font-size: 13px; color: var(--muted); margin-bottom: 28px; line-height: 1.5; }

        /* alerts */
        .alert { padding: 14px 16px; border-radius: 10px; margin-bottom: 22px; font-size: 13px; font-weight: 600; display: flex; align-items: flex-start; gap: 10px; }
        .alert-success { background: var(--green-lt); color: var(--green); border: 1.5px solid #86efac; }
        .alert-error   { background: var(--red-lt);   color: var(--red);   border: 1.5px solid #fca5a5; }
        .alert ul { padding-left: 16px; margin-top: 4px; }
        .alert ul li { margin-bottom: 3px; }

        /* form */
        .form-group { margin-bottom: 20px; }
        label { display: block; font-size: 13px; font-weight: 700; color: var(--text); margin-bottom: 7px; }

        .input-wrap { position: relative; }
        .input-wrap input {
            width: 100%; padding: 11px 44px 11px 14px;
            border: 1.5px solid var(--border); border-radius: 10px;
            font-size: 14px; font-family: inherit; color: var(--text);
            background: #f8fafc; outline: none;
            transition: border-color .15s, box-shadow .15s;
        }
        .input-wrap input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37,99,235,.1);
            background: #fff;
        }
        .input-wrap input.is-error { border-color: var(--red); }
        .pw-toggle {
            position: absolute; right: 12px; top: 50%; transform: translateY(-50%);
            background: none; border: none; cursor: pointer;
            font-size: 17px; color: var(--muted); padding: 4px; line-height: 1;
        }

        /* strength bar */
        .strength-bar { height: 4px; border-radius: 999px; background: var(--border); margin-top: 8px; overflow: hidden; }
        .strength-fill { height: 100%; border-radius: 999px; transition: width .3s, background .3s; width: 0%; }
        .strength-label { font-size: 11px; color: var(--muted); margin-top: 4px; }

        /* match indicator */
        .match-hint { font-size: 12px; margin-top: 6px; font-weight: 600; }
        .match-ok  { color: var(--green); }
        .match-err { color: var(--red); }

        .divider { border: none; border-top: 1px solid var(--border); margin: 24px 0; }

        .btn-submit {
            width: 100%; padding: 13px;
            background: linear-gradient(135deg,#1e3a5f,#2563eb);
            color: #fff; border: none; border-radius: 10px;
            font-size: 15px; font-weight: 700; font-family: inherit;
            cursor: pointer; letter-spacing: .2px;
            box-shadow: 0 4px 14px rgba(37,99,235,.28);
            transition: opacity .15s, transform .1s;
        }
        .btn-submit:hover  { opacity: .9; }
        .btn-submit:active { transform: scale(.98); }
        .btn-submit:disabled { opacity: .5; cursor: not-allowed; transform: none; }

        .logout-note { margin-top: 16px; font-size: 12px; color: var(--muted); text-align: center; line-height: 1.6; }

        @media (max-width: 600px) { .page-body { padding: 20px 16px; } .card { padding: 22px; } .top-bar { padding: 10px 16px; } }
    </style>
</head>
<body>

<div class="top-bar">
    <a class="back" href="<?= $backLink ?>">← Dashboard</a>
    <h1>🔑 Change Password</h1>
    <div class="top-bar-user">
        <div class="avatar"><?= strtoupper(mb_substr($_SESSION["name"], 0, 1)) ?></div>
        <span><?= htmlspecialchars($_SESSION["name"]) ?></span>
    </div>
</div>

<div class="page-body">
<div class="card">

    <div class="card-icon">🔑</div>
    <div class="card-title">Change Password</div>
    <div class="card-sub">
        <?= $portalName ?> · <?= htmlspecialchars($_SESSION["name"]) ?><br>
        Enter your current password, then choose a new one.
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success">
            ✅ Password changed successfully! Use your new password next time you log in.
        </div>
        <div style="text-align:center;margin-top:8px;">
            <a href="<?= $backLink ?>" style="display:inline-flex;align-items:center;gap:6px;color:var(--primary);font-weight:700;font-size:14px;text-decoration:none;">
                ← Back to Dashboard
            </a>
        </div>

    <?php else: ?>

        <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <span>⚠️</span>
            <div>
                <?php if (count($errors) === 1): ?>
                    <?= htmlspecialchars($errors[0]) ?>
                <?php else: ?>
                    <ul><?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e) ?></li><?php endforeach; ?></ul>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <form method="POST" id="pwForm" onsubmit="return validateForm()">

            <!-- Current password -->
            <div class="form-group">
                <label for="current_password">Current Password</label>
                <div class="input-wrap">
                    <input type="password" id="current_password" name="current_password"
                        placeholder="Your current password" required
                        class="<?= !empty($errors) && str_contains($errors[0],'Current') ? 'is-error' : '' ?>">
                    <button type="button" class="pw-toggle" onclick="togglePw('current_password')">👁</button>
                </div>
            </div>

            <hr class="divider">

            <!-- New password -->
            <div class="form-group">
                <label for="new_password">New Password</label>
                <div class="input-wrap">
                    <input type="password" id="new_password" name="new_password"
                        placeholder="Enter new password" required
                        oninput="checkStrength(this.value); checkMatch()">
                    <button type="button" class="pw-toggle" onclick="togglePw('new_password')">👁</button>
                </div>
                <div class="strength-bar"><div class="strength-fill" id="strengthFill"></div></div>
                <div class="strength-label" id="strengthLabel">Enter a new password</div>
            </div>

            <!-- Confirm new password -->
            <div class="form-group">
                <label for="confirm_password">Confirm New Password</label>
                <div class="input-wrap">
                    <input type="password" id="confirm_password" name="confirm_password"
                        placeholder="Repeat new password" required
                        oninput="checkMatch()">
                    <button type="button" class="pw-toggle" onclick="togglePw('confirm_password')">👁</button>
                </div>
                <div class="match-hint" id="matchHint"></div>
            </div>

            <button class="btn-submit" type="submit" id="submitBtn">
                🔑 Change Password
            </button>

        </form>

        <div class="logout-note">
            After changing your password you will stay logged in.<br>
            Use the new password next time you log in.
        </div>

    <?php endif; ?>

</div>
</div>

<script>
function togglePw(id) {
    const el = document.getElementById(id);
    el.type = el.type === 'password' ? 'text' : 'password';
}

function checkStrength(pw) {
    const fill  = document.getElementById('strengthFill');
    const label = document.getElementById('strengthLabel');
    if (!pw) {
        fill.style.width = '0%';
        label.textContent = 'Enter a new password';
        label.style.color = 'var(--muted)';
        return;
    }
    let score = 0;
    if (pw.length >= 4)  score++;
    if (pw.length >= 8)  score++;
    if (/[0-9]/.test(pw))  score++;
    if (/[^a-zA-Z0-9]/.test(pw)) score++;

    const levels = [
        { pct: '20%', color: '#dc2626', text: 'Very weak' },
        { pct: '40%', color: '#d97706', text: 'Weak' },
        { pct: '65%', color: '#ca8a04', text: 'Fair' },
        { pct: '85%', color: '#16a34a', text: 'Strong' },
        { pct: '100%', color: '#15803d', text: 'Very strong' },
    ];
    const lvl = levels[Math.min(score, 4)];
    fill.style.width     = lvl.pct;
    fill.style.background = lvl.color;
    label.textContent    = lvl.text;
    label.style.color    = lvl.color;
}

function checkMatch() {
    const np  = document.getElementById('new_password').value;
    const cp  = document.getElementById('confirm_password').value;
    const hint = document.getElementById('matchHint');
    if (!cp) { hint.textContent = ''; return; }
    if (np === cp) {
        hint.textContent = '✅ Passwords match';
        hint.className = 'match-hint match-ok';
    } else {
        hint.textContent = '❌ Passwords do not match';
        hint.className = 'match-hint match-err';
    }
}

function validateForm() {
    const np = document.getElementById('new_password').value;
    const cp = document.getElementById('confirm_password').value;
    if (np !== cp) {
        document.getElementById('matchHint').textContent = '❌ Passwords do not match';
        document.getElementById('matchHint').className = 'match-hint match-err';
        return false;
    }
    return true;
}
</script>

</body>
</html>