<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';
require_once 'auth.php';

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

$currentPassword = $data['current_password'] ?? '';
$newPassword = $data['new_password'] ?? '';

if (!$currentPassword || !$newPassword) {
    sendError('Current password and new password required', 400);
}

if (strlen($newPassword) < 6) {
    sendError('New password must be at least 6 characters', 400);
}

// Verify current password
$stmt = $pdo->prepare("SELECT password FROM public_users WHERE id = ?");
$stmt->execute([$user['id']]);
$userData = $stmt->fetch();

if (!password_verify($currentPassword, $userData['password'])) {
    sendError('Current password is incorrect', 401);
}

// Update password
$hashed = password_hash($newPassword, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("UPDATE public_users SET password = ? WHERE id = ?");
$stmt->execute([$hashed, $user['id']]);

// Invalidate all existing tokens (force re-login)
$stmt = $pdo->prepare("DELETE FROM public_user_tokens WHERE user_id = ?");
$stmt->execute([$user['id']]);

sendSuccess(null, 'Password changed successfully. Please login again.');
?>