<?php
/**
 * Diagnostico: Lectura de fechas Excel para Calendario Tributario
 * Solo accesible para usuarios director o manager (autenticados via DokuWiki)
 */
if (!defined('DOKU_INC')) {
    define('DOKU_INC', realpath(__DIR__ . '/../../../../') . '/');
}
require_once DOKU_INC . 'inc/init.php';

// Verificar autenticacion
$user = $_SERVER['REMOTE_USER'] ?? '';
if (empty($user)) {
    http_response_code(403);
    die('Acceso denegado: debe iniciar sesion.');
}

// Verificar que sea director o manager
global $USERINFO;
$grps = $USERINFO['grps'] ?? [];
$isManager = (stripos($user, 'sie') === 0) || in_array('manager', $grps);
$isDirector = in_array('director', $grps);

if (!$isManager && !$isDirector && !auth_isadmin()) {
    http_response_code(403);
    die('Acceso denegado: requiere permisos de director o manager.');
}

echo "<h2>Diagnostico: Que lee SimpleXLSXReader de tu Excel</h2>";

if (!empty($_FILES['testfile']['tmp_name'])) {
    echo "<pre>";
    require_once __DIR__ . '/lib/SimpleXLSXReader.php';
    require_once __DIR__ . '/lib/CalendarImporter.php';

    $reader = new \dokuwiki\plugin\beztaxcalendar\lib\SimpleXLSXReader($_FILES['testfile']['tmp_name']);

    if ($reader->hasErrors()) {
        echo "ERRORES: " . implode(', ', $reader->getErrors()) . "\n";
    } else {
        $sheets = $reader->getSheetNames();
        echo "Hojas: " . implode(', ', $sheets) . "\n\n";

        // parseDate para testing
        $ref = new ReflectionClass('dokuwiki\plugin\beztaxcalendar\lib\CalendarImporter');
        $imp = $ref->newInstanceWithoutConstructor();
        $pd = $ref->getMethod('parseDate');
        $pd->setAccessible(true);

        foreach ($sheets as $sn) {
            $rows = $reader->getSheet($sn);
            echo "=== Hoja: {$sn} ===\n";
            foreach ($rows as $ri => $row) {
                if ($ri >= 8) { echo "  ... (" . count($rows) . " filas total)\n"; break; }
                echo "Fila {$ri}:\n";
                foreach ($row as $ci => $cell) {
                    $parsed = $pd->invoke($imp, $cell);
                    $parsedStr = ($parsed !== null) ? " -> parseDate={$parsed}" : "";
                    echo "  [{$ci}] = '{$cell}' (" . gettype($cell) . "){$parsedStr}\n";
                }
                echo "\n";
            }
        }
    }
    echo "</pre>";
}

echo '<form method="post" enctype="multipart/form-data">';
echo '<p>Sube tu Excel (el mismo que cargaste al calendario):</p>';
echo '<input type="file" name="testfile" accept=".xlsx" required>';
echo ' <button type="submit">Analizar</button>';
echo '</form>';
