<?php
require_once __DIR__ . '/../includes/functions.php';
requireLogin();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonResponse(['success'=>false,'error'=>'Method not allowed'], 405);

$current = $_POST['current_password'] ?? '';
$newPw   = $_POST['new_password']     ?? '';

if (!$current || !$newPw) jsonResponse(['success'=>false,'error'=>'All fields are required.']);
if (strlen($newPw) < 6)   jsonResponse(['success'=>false,'error'=>'Password must be at least 6 characters.']);

$db   = getDB();
$stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

if (!$user || !password_verify($current, $user['password'])) {
    jsonResponse(['success'=>false,'error'=>'Current password is incorrect.']);
}

$hash = password_hash($newPw, PASSWORD_DEFAULT);
$db->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hash, $_SESSION['user_id']]);

jsonResponse(['success'=>true, 'message'=>'Password updated.']);
