<?php
session_start();
header('Content-Type: application/json');
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/database/connection.php';

try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  $clientId = isset($_SESSION['client_id']) ? (int)$_SESSION['client_id'] : 0;
  if ($clientId <= 0) { http_response_code(401); echo json_encode(['success'=>false,'message'=>'No autenticado']); exit; }

  $cur = trim($_POST['current_password'] ?? '');
  $nw = trim($_POST['new_password'] ?? '');
  $cf = trim($_POST['confirm_password'] ?? '');
  if ($cur === '' || $nw === '' || $cf === '') { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Completa todos los campos']); exit; }
  if ($nw !== $cf) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Las contraseñas no coinciden']); exit; }
  if (strlen($nw) < 6) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'La nueva contraseña debe tener al menos 6 caracteres']); exit; }

  $sel = $pdo->prepare('SELECT password_hash FROM clients WHERE id = ? LIMIT 1');
  $sel->execute([$clientId]);
  $row = $sel->fetch(PDO::FETCH_ASSOC);
  if (!$row || empty($row['password_hash'])) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Cuenta inválida']); exit; }
  if (!password_verify($cur, $row['password_hash'])) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Contraseña actual incorrecta']); exit; }

  $newHash = password_hash($nw, PASSWORD_DEFAULT);
  $upd = $pdo->prepare('UPDATE clients SET password_hash = ?, updated_at = NOW() WHERE id = ?');
  $upd->execute([$newHash, $clientId]);
  echo json_encode(['success'=>true]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
?>
