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

/* ===============================
   LOGIN CHECK (FIRST PRIORITY)
================================ */
if (!isset($_SESSION['user_id'])) {
    header("Location: userlogin.php");
    exit;
}

/* ===============================
   DB CHECK
================================ */
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed.");
}

$user_id = (int)$_SESSION['user_id'];
$success = $error = "";

/* ===============================
   HANDLE PASSWORD UPDATE
================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $current_password = trim($_POST['current_password'] ?? '');
    $new_password     = trim($_POST['new_password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');

    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $error = "All fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error = "New password and confirm password do not match.";
    } elseif (strlen($new_password) < 6) {
        $error = "Password must be at least 6 characters long.";
    } else {

        // Fetch existing password hash
        $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $res = $stmt->get_result();
        $user = $res->fetch_assoc();

        if (!$user || !password_verify($current_password, $user['password'])) {
            $error = "Current password is incorrect.";
        } else {

            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $update->bind_param("si", $hashed_password, $user_id);

            if ($update->execute()) {
                $success = "Password updated successfully.";
            } else {
                $error = "Something went wrong. Please try again.";
            }
        }
    }
}

include(__DIR__ . '/../includes/header.php');
include(__DIR__ . '/../includes/navbar.php');
?>

<main class="content">
<div class="container-fluid">

    <div class="row justify-content-center">
        <div class="col-lg-5 col-md-7">

            <div class="card shadow-sm border-0">
                <div class="card-header bg-dark text-white text-center">
                    <h5 class="mb-0">Account Security</h5>
                </div>

                <div class="card-body">

                    <?php if ($success): ?>
                        <div class="alert alert-success"><?= htmlspecialchars($success); ?></div>
                    <?php endif; ?>

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

                    <form method="POST" autocomplete="off">

                        <div class="mb-3">
                            <label class="form-label">Current Password</label>
                            <div class="input-group">
                                <input type="password" name="current_password" id="currentPass" class="form-control" required>
                                <button type="button" class="btn btn-outline-secondary" onclick="togglePass('currentPass')">👁</button>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">New Password</label>
                            <div class="input-group">
                                <input type="password" name="new_password" id="newPass" class="form-control" required>
                                <button type="button" class="btn btn-outline-secondary" onclick="togglePass('newPass')">👁</button>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Confirm New Password</label>
                            <div class="input-group">
                                <input type="password" name="confirm_password" id="confirmPass" class="form-control" required>
                                <button type="button" class="btn btn-outline-secondary" onclick="togglePass('confirmPass')">👁</button>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary w-100">
                            Update Password
                        </button>

                    </form>

                </div>
            </div>

        </div>
    </div>

</div>
</main>

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

<!-- ===============================
     SHOW / HIDE PASSWORD
================================ -->
<script>
function togglePass(id) {
    const input = document.getElementById(id);
    input.type = input.type === "password" ? "text" : "password";
}
</script>
