<?php
// Endpoint staff: actualizar estado de documento
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

header('Content-Type: application/json; charset=utf-8');

function error_response($msg, $code = 400) {
    http_response_code($code);
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

if (!isset($_SESSION['user_id'])) { error_response('No autenticado', 401); }

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { error_response('Método no permitido', 405); }

$id = (int)($_POST['id'] ?? 0);
$status = trim($_POST['status'] ?? '');
if ($id <= 0 || !in_array($status, ['approved','rejected','submitted','pending'], true)) {
    error_response('Parámetros inválidos');
}

$db = Database::getInstance();
$pdo = $db->getConnection();

// Verificación de permiso: documents.update_status
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName(PDO $pdo, string $permName, int $userId): bool {
        if ($userId <= 0) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}
$current_user_id = (int)($_SESSION['user_id'] ?? 0);
if (!userHasPermissionByName($pdo, 'documents.update_status', $current_user_id)) {
    error_response('Permiso requerido: documents.update_status', 403);
}
$stmt = $pdo->prepare("UPDATE client_documents SET status = ?, updated_at = NOW() WHERE id = ?");
$stmt->execute([$status, $id]);

echo json_encode(['success' => true]);
?>