<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../src/db.php';

use function App\get_db;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Metodo no permitido']);
    exit;
}

$eventId = (int)($_POST['event_id'] ?? 0);
if ($eventId <= 0) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'event_id requerido']);
    exit;
}

if (!isset($_FILES['excel']) || !is_uploaded_file($_FILES['excel']['tmp_name'])) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'Archivo requerido (campo: excel)']);
    exit;
}

$pdo = get_db();
$tmpPath = $_FILES['excel']['tmp_name'];
$fileName = (string)($_FILES['excel']['name'] ?? '');
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

$rows = [];

if (class_exists('PhpOffice\\PhpSpreadsheet\\IOFactory')) {
    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($tmpPath);
    $sheet = $spreadsheet->getActiveSheet();
    $rows = $sheet->toArray(null, true, true, false);
} else {
    if ($ext !== 'csv') {
        http_response_code(422);
        echo json_encode([
            'ok' => false,
            'error' => 'Sin PhpSpreadsheet solo se permite CSV. Sube .csv o actualiza a PHP 8.3+'
        ]);
        exit;
    }

    $fh = fopen($tmpPath, 'r');
    if ($fh === false) {
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => 'No se pudo leer el archivo CSV']);
        exit;
    }

    while (($data = fgetcsv($fh, 0, ',')) !== false) {
        $rows[] = $data;
    }
    fclose($fh);
}

if (!$rows || count($rows) < 2) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'Archivo vacio o sin filas de datos']);
    exit;
}

$normalize = static function (string $value): string {
    $value = trim(mb_strtolower($value));
    $value = str_replace([' ', '-'], '_', $value);
    return $value;
};

$headers = array_map(static function ($h) use ($normalize) {
    return $normalize((string)$h);
}, $rows[0]);

$required = ['nombre'];
foreach ($required as $req) {
    if (!in_array($req, $headers, true)) {
        http_response_code(422);
        echo json_encode(['ok' => false, 'error' => "Falta columna requerida: {$req}"]);
        exit;
    }
}

$idx = array_flip($headers);

$eventStmt = $pdo->prepare('SELECT id, user_id FROM user_events WHERE id = ? LIMIT 1');
$eventStmt->execute([$eventId]);
$event = $eventStmt->fetch(\PDO::FETCH_ASSOC);
if (!$event) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'event_id no existe en user_events']);
    exit;
}
$ownerUserId = (int)$event['user_id'];

$insert = $pdo->prepare(
    'INSERT INTO user_guests (user_id, event_id, name, phone, email, adults, kids, pass_count, pass_type, dietary_notes)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);

$errors = [];
$imported = 0;

try {
    $pdo->beginTransaction();

    for ($i = 1; $i < count($rows); $i++) {
        $rowNum = $i + 1;
        $row = $rows[$i];

        $name = trim((string)($row[$idx['nombre']] ?? ''));
        $phone = trim((string)($row[$idx['telefono']] ?? $row[$idx['phone']] ?? ''));
        $email = trim((string)($row[$idx['email']] ?? ''));
        $adults = max(1, (int)($row[$idx['adultos']] ?? $row[$idx['adults']] ?? 1));
        $kids = max(0, (int)($row[$idx['ninos']] ?? $row[$idx['kids']] ?? 0));
        $passCount = max(1, (int)($row[$idx['pass_count']] ?? 1));
        $passTypeRaw = trim(mb_strtolower((string)($row[$idx['pass_type']] ?? 'individual')));
        $passType = $passTypeRaw === 'familiar' ? 'familiar' : 'individual';
        $diet = trim((string)($row[$idx['dieta']] ?? ''));

        if ($name === '') {
            $errors[] = "Fila {$rowNum}: nombre vacio";
            continue;
        }

        if ($phone !== '' && !preg_match('/^[0-9+\-\s()]{7,25}$/', $phone)) {
            $errors[] = "Fila {$rowNum}: telefono invalido";
            continue;
        }

        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Fila {$rowNum}: email invalido";
            continue;
        }

        $insert->execute([
            $ownerUserId,
            $eventId,
            $name,
            $phone !== '' ? $phone : null,
            $email !== '' ? $email : null,
            $adults,
            $kids,
            $passCount,
            $passType,
            $diet !== '' ? $diet : null,
        ]);

        $imported++;
    }

    $pdo->commit();

    echo json_encode([
        'ok' => true,
        'event_id' => $eventId,
        'imported' => $imported,
        'errors' => $errors,
        'mode' => class_exists('PhpOffice\\PhpSpreadsheet\\IOFactory') ? 'excel' : 'csv'
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Error al importar archivo', 'detail' => $e->getMessage()]);
}
