<?php
/**
 * SAC 2026 - NUCLEAR BULK LOAD PROPERTIES
 * Procesa la carga masiva de inmuebles. Clave: code.
 */
require_once 'config.php';
checkAccess(['admin', 'programmer']);

$data = $REQUEST_DATA;

if (!isset($data['rows']) || !is_array($data['rows'])) {
    response(["error" => "Estructura de datos inválida"], 400);
}

try {
    $pdo->beginTransaction();
    $inserted = 0;
    $updated = 0;

    $stmt = $pdo->prepare("INSERT INTO properties 
        (code, type, number, aliquot, has_uncommon, initial_debt, credit_balance, status) 
        VALUES (:code, :type, :num, :ali, :gnc, :deb, :cre, :sta)
        ON DUPLICATE KEY UPDATE 
        type = VALUES(type), 
        number = VALUES(number), 
        aliquot = VALUES(aliquot), 
        has_uncommon = VALUES(has_uncommon), 
        initial_debt = VALUES(initial_debt), 
        credit_balance = VALUES(credit_balance), 
        status = VALUES(status)");

    foreach ($data['rows'] as $row) {
        // Mapeo estricto de campos CSV
        $params = [
            ':code' => trim($row['codigo']),
            ':type' => trim($row['tipo']), // Casa, Apartamento, Local
            ':num'  => trim($row['numero']),
            ':ali'  => (float)$row['alicuota'],
            ':gnc'  => (int)$row['es_gnc'], // 1 o 0
            ':deb'  => (float)$row['deuda_inicial'],
            ':cre'  => (float)$row['saldo_favor'],
            ':sta'  => trim($row['estatus']) // Ocupada, Vacía
        ];
        
        $stmt->execute($params);
        if ($stmt->rowCount() == 1) $inserted++; else $updated++;
    }

    $pdo->commit();
    logSystemAction("CARGA MASIVA PROPIEDADES: $inserted nuevos, $updated actualizados", "CÁTALOGO");
    response(["success" => true, "inserted" => $inserted, "updated" => $updated]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    response(["error" => "Fallo Nuclear: " . $e->getMessage()], 500);
}
?>