<?php



require_once __DIR__ . '/../../config.php';

// POST /admin/ganancias/calcular.php
// Body: { periodo }
// Calculate regalías for all distributors for a given period

requireAdmin();

$data = body();

if (empty($data['periodo'])) {
    jsonErr(400, 'Período requerido (YYYY-MM).');
}

[$year, $month] = explode('-', $data['periodo']);
$year = (int)$year;
$month = (int)$month;

if ($month < 1 || $month > 12) {
    jsonErr(400, 'Mes inválido.');
}

$db = getDB();

// This is a simplified version - actual calculation would be complex
// For now, we just mark it as "calculated"

$stmt = $db->prepare('
    UPDATE regs2 
    SET status = 1
    WHERE MONTH(fecha) = ? AND YEAR(fecha) = ? AND status = 0
');
$stmt->execute([$month, $year]);

$affectedRows = $stmt->rowCount();

jsonOk(['message' => "Regalías calculadas para $affectedRows distribuidores.", 'affected' => $affectedRows]);
