<?php
session_start();
include '../includes/session_control.php';
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../cotizaciones/api/_node.php';

$idG = intval($_POST['idGasto'] ?? 0);
$dir = __DIR__ . "/../archivoDigital/soporteGastos/$idG";
if (!is_dir($dir)) mkdir($dir, 0755, true);

$filesOK = [];
foreach ($_FILES['soporteGasto']['error'] as $i => $err) {
    if ($err === UPLOAD_ERR_OK) {
        $tmp  = $_FILES['soporteGasto']['tmp_name'][$i];
        $orig = pathinfo($_FILES['soporteGasto']['name'][$i], PATHINFO_FILENAME);
        $ext  = pathinfo($_FILES['soporteGasto']['name'][$i], PATHINFO_EXTENSION);
        $count = count(glob("$dir/*"));
        $name = "{$orig}-" . ($count + 1) . "." . $ext;
        move_uploaded_file($tmp, "$dir/$name");
        $filesOK[] = $name;
    }
}

$total = count(glob("$dir/*"));
// Persistir contador en Node
$token = cpn_node_token_or_fail();
$url = cpn_node_api_base() . '/api/gastos/soportes/set-count';
cpn_node_request('POST', $url, $token, ['idGasto' => $idG, 'archivos' => $total]);

// Devolver lista de URLs
$out = [];
foreach (glob("$dir/*") as $f) {
    $n = basename($f);
    $out[] = [
        'name' => $n,
        'url' => "/archivoDigital/soporteGastos/$idG/$n"
    ];
}
echo json_encode($out);
