<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$message = '';
$user_id = $_SESSION['user_id'] ?? 0;

// ================= HANDLE PASSWORD CHANGE =================
if(isset($_POST['change_password'])){

    $current_password = $_POST['current_password'] ?? '';
    $new_password     = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Get current hash
    $user = $conn->query("SELECT password FROM users WHERE id=$user_id")->fetch_assoc();

    if(!$user || !password_verify($current_password, $user['password'])){
        $message = "<div class='alert alert-danger'>Current password is incorrect!</div>";

    } elseif($new_password !== $confirm_password){
        $message = "<div class='alert alert-danger'>New passwords do not match!</div>";

    } elseif(strlen($new_password) < 6){
        $message = "<div class='alert alert-warning'>Password must be at least 6 characters!</div>";

    } else {
        $new_hash = password_hash($new_password, PASSWORD_DEFAULT);

        $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
        $stmt->bind_param("si", $new_hash, $user_id);

        if($stmt->execute()){
            $message = "<div class='alert alert-success'>Password changed successfully!</div>";
        } else {
            $message = "<div class='alert alert-danger'>Error: ".$stmt->error."</div>";
        }

        $stmt->close();
    }
}
?>

<div class="container mt-4">
    <h4><i class="fa fa-key"></i> Change Password</h4>
    <hr>

    <div class="card">
        <div class="card-header bg-warning text-dark">
            Update Your Password
        </div>
        <div class="card-body">

            <?= $message ?>

            <form method="POST" class="row g-3">
                <div class="col-md-4">
                    <label>Current Password</label>
                    <input type="password" name="current_password" class="form-control" required>
                </div>

                <div class="col-md-4">
                    <label>New Password</label>
                    <input type="password" name="new_password" class="form-control" required>
                </div>

                <div class="col-md-4">
                    <label>Confirm New Password</label>
                    <input type="password" name="confirm_password" class="form-control" required>
                </div>

                <div class="col-md-12 mt-2">
                    <button name="change_password" class="btn btn-success">
                        <i class="fa fa-check"></i> Change Password
                    </button>
                </div>
            </form>

        </div>
    </div>
</div>

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