<?php
/**
 * SAC 2026 - API: Sincronizar Recaudación Mensual
 * Calcula y guarda el resumen de facturación vs recaudación del mes anterior.
 */
header('Content-Type: application/json');
require_once 'config.php';

// Solo permitir a roles administrativos
if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['admin', 'programmer', 'board', 'manager'])) {
    http_response_code(403);
    echo json_encode(['error' => 'No autorizado']);
    exit;
}

try {
    // 1. Obtener todos los meses que tienen cuotas generadas, agrupando por mes/año
    // Esto evita problemas si hay múltiples IDs de cuota para el mismo periodo
    $stmtFees = $pdo->query("SELECT month, year, GROUP_CONCAT(id) as fee_ids 
                             FROM monthly_fees 
                             GROUP BY month, year 
                             ORDER BY year DESC, month DESC");
    $allPeriods = $stmtFees->fetchAll();

    if (empty($allPeriods)) {
        echo json_encode([
            'success' => false, 
            'message' => "No se encontró facturación generada en el sistema. Genere las cuotas primero."
        ]);
        exit;
    }

    $syncedCount = 0;
    $lastSynced = null;

    foreach ($allPeriods as $period) {
        $feeIds = explode(',', $period['fee_ids']);
        $targetMonth = (int)$period['month'];
        $targetYear = (int)$period['year'];

        // 2. Calcular totales desde property_debts para todos los fee_ids de este periodo
        $placeholders = implode(',', array_fill(0, count($feeIds), '?'));
        $statsStmt = $pdo->prepare("SELECT 
                                        SUM(amount_usd) as totalBilled, 
                                        SUM(paid_amount) as totalCollected 
                                      FROM property_debts 
                                      WHERE fee_id IN ($placeholders)");
        $statsStmt->execute($feeIds);
        $stats = $statsStmt->fetch();

        $amountBilled = (float)($stats['totalBilled'] ?? 0);
        $amountCollected = (float)($stats['totalCollected'] ?? 0);

        // 3. Insertar o Actualizar en monthly_collection
        $upsertStmt = $pdo->prepare("INSERT INTO monthly_collection (month, year, amount_billed, amount_collected) 
                                     VALUES (?, ?, ?, ?) 
                                     ON DUPLICATE KEY UPDATE 
                                        amount_billed = VALUES(amount_billed), 
                                        amount_collected = VALUES(amount_collected)");
        $upsertStmt->execute([$targetMonth, $targetYear, $amountBilled, $amountCollected]);
        
        $syncedCount++;
    }

    echo json_encode([
        'success' => true,
        'message' => "Sincronización completada. Se procesaron $syncedCount meses.",
        'count' => $syncedCount
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Error de base de datos: ' . $e->getMessage()]);
}
?>