<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('METODO NO PERMITIDO');
    }

    $input = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL PROCESAR DATOS');
    }
    if (empty($input['current_password']) || empty($input['new_password'])) {
        throw new Exception('CAMPOS REQUERIDOS FALTANTES');
    }

    $user_id = 1;
    $current_password = $input['current_password'];
    $new_password = $input['new_password'];

    if (strlen($new_password) < 6) {
        throw new Exception('CONTRASENA MUY CORTA');
    }

    $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($current_password, $user['password_hash'])) {
        throw new Exception('CONTRASENA ACTUAL INCORRECTA');
    }

    $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);

    $update_stmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE user_id = ?");
    $update_stmt->execute([$new_password_hash, $user_id]);
    
    $response['success'] = true;
    $response['message'] = 'CONTRASENA ACTUALIZADA';

} catch (PDOException $e) {
    error_log("Error PDO en user-password-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>