<?php
// change-password.php — User self-service password change
session_start();
include 'config.php';

$message = '';
$error = '';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

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

    if (empty($current) || empty($new) || empty($confirm)) {
        $error = "All fields are required.";
    } elseif (strlen($new) < 8) {
        $error = "New password must be at least 8 characters.";
    } elseif ($new !== $confirm) {
        $error = "New passwords do not match.";
    } else {
        // Verify current password
        $stmt = $conn->prepare("SELECT password FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();

        if (!password_verify($current, $user['password'])) {
            $error = "Current password is incorrect.";
        } else {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->bind_param("si", $hash, $user_id);
            if ($stmt->execute()) {
                // Audit log if available
                if (file_exists(__DIR__ . '/util/audit_logger.php')) {
                    include_once __DIR__ . '/util/audit_logger.php';
                    audit_log(
                        $conn,
                        'password_change',
                        'users',
                        $user_id,
                        $user_id,
                        $user_id,
                        null,
                        null,
                        "User changed their own password."
                    );
                }
                $message = "Password changed successfully.";
            } else {
                $error = "Error updating password.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Change Password - SaniBook</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        body {
            font-family: 'Inter', system-ui, sans-serif;
        }
    </style>
</head>

<body class="bg-gradient-to-br from-slate-50 to-blue-50/30 min-h-screen">
    <?php include 'navbar.php'; ?>

    <div class="max-w-md mx-auto mt-12 p-6">
        <div class="bg-white rounded-2xl shadow-lg p-8 border border-slate-200">
            <div class="text-center mb-6">
                <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3">
                    <i class="fa-solid fa-lock text-2xl text-blue-600"></i>
                </div>
                <h2 class="text-2xl font-bold text-slate-900">Change Password</h2>
                <p class="text-slate-500 text-sm mt-1">Keep your account secure</p>
            </div>

            <?php if ($message): ?>
                <div
                    class="bg-green-50 border border-green-200 text-green-800 p-3 rounded-lg mb-4 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-check-circle"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div
                    class="bg-red-50 border border-red-200 text-red-800 p-3 rounded-lg mb-4 text-sm flex items-center gap-2">
                    <i class="fa-solid fa-exclamation-circle"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form method="POST" class="space-y-5">
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-1">Current Password</label>
                    <div class="relative">
                        <input type="password" name="current_password" required
                            class="w-full border border-slate-300 rounded-lg p-3 pl-10 text-sm focus:ring-2 focus:ring-blue-500">
                        <i class="fa-solid fa-key absolute left-3 top-3.5 text-slate-400"></i>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-1">New Password</label>
                    <div class="relative">
                        <input type="password" name="new_password" required minlength="8"
                            class="w-full border border-slate-300 rounded-lg p-3 pl-10 text-sm focus:ring-2 focus:ring-blue-500">
                        <i class="fa-solid fa-lock absolute left-3 top-3.5 text-slate-400"></i>
                    </div>
                    <p class="text-xs text-slate-400 mt-1">Minimum 8 characters</p>
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-1">Confirm New Password</label>
                    <div class="relative">
                        <input type="password" name="confirm_password" required minlength="8"
                            class="w-full border border-slate-300 rounded-lg p-3 pl-10 text-sm focus:ring-2 focus:ring-blue-500">
                        <i class="fa-solid fa-shield-halved absolute left-3 top-3.5 text-slate-400"></i>
                    </div>
                </div>
                <button type="submit"
                    class="w-full py-3 bg-blue-600 text-white rounded-lg font-bold hover:bg-blue-700 transition-all shadow-md hover:shadow-lg text-sm">
                    <i class="fa-solid fa-save mr-1"></i> Update Password
                </button>
            </form>

            <div class="mt-4 text-center">
                <a href="/profile/" class="text-sm text-blue-600 hover:underline">
                    <i class="fa-solid fa-arrow-left mr-1"></i> Back to Profile
                </a>
            </div>
        </div>
    </div>
</body>

</html>