<?php
require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/session.php";

header('Content-Type: application/json');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check login
$user_id = $_SESSION['user_id'] ?? null;

if (!$user_id) {
    echo json_encode([
        "status" => false,
        "message" => "Unauthorized access"
    ]);
    exit;
}

// Get POST data
$old_password = $_POST['old_password'] ?? '';
$new_password = $_POST['new_password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

if (!$old_password || !$new_password || !$confirm_password) {
    echo json_encode([
        "status" => false,
        "message" => "All fields are required"
    ]);
    exit;
}

// Check if new passwords match
if ($new_password !== $confirm_password) {
    echo json_encode([
        "status" => false,
        "message" => "New password and confirm password do not match"
    ]);
    exit;
}

$conn = db();

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

if (!$user) {
    echo json_encode([
        "status" => false,
        "message" => "User not found"
    ]);
    exit;
}

// Verify old password
if (!password_verify($old_password, $user['password'])) {
    echo json_encode([
        "status" => false,
        "message" => "Old password is incorrect"
    ]);
    exit;
}

// Hash new password
$new_hash = password_hash($new_password, PASSWORD_DEFAULT);

// Update in DB
$stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
$stmt->bind_param("si", $new_hash, $user_id);
$updated = $stmt->execute();

if ($updated) {
    echo json_encode([
        "status" => true,
        "message" => "Password changed successfully"
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Failed to update password"
    ]);
}