<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION["user_id"])) {
    echo json_encode(["success"=>false,"error"=>"Not logged in"]); exit;
}

require_once '../config/database.php';
$userId = (int)$_SESSION["user_id"];
$input  = json_decode(file_get_contents("php://input"), true);

$current     = $input["current"]      ?? "";
$newPassword = $input["new_password"] ?? "";

if (!$current || !$newPassword) {
    echo json_encode(["success"=>false,"error"=>"Missing fields"]); exit;
}

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

if (!password_verify($current, $hash)) {
    echo json_encode(["success"=>false,"error"=>"Current password is incorrect"]); exit;
}

/* Update */
$pdo->prepare("UPDATE users SET password=? WHERE id=?")
    ->execute([password_hash($newPassword, PASSWORD_DEFAULT), $userId]);

echo json_encode(["success"=>true]);