<?php
/**
 * sports.php — Panel de Deportes: gestión de ligas y eventos.
 *
 * Ligas (catálogo): nombre + league_id (id externo opcional). Add/list/delete.
 * Eventos: liga, local, visitante, fecha, hora, canales (separados por comas)
 * y orden. Add/edit/list/delete.
 *
 * Ambos se exponen en GET /api/sports (eventos filtrados a los próximos N días).
 * Todo se guarda por POST con CSRF y sentencias preparadas.
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';

require_login();

$pdo = db();
$flash = '';
$flashType = 'ok';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();
    $action = (string) ($_POST['action'] ?? '');

    try {
        /* ----------------------- Ligas ----------------------- */
        if ($action === 'league_create') {
            $name     = trim((string) ($_POST['name'] ?? ''));
            $leagueId = trim((string) ($_POST['league_id'] ?? ''));
            if ($name === '') {
                $flash = 'El nombre de la liga es obligatorio.';
                $flashType = 'error';
            } else {
                $ins = $pdo->prepare('INSERT INTO leagues (name, league_id, created_at) VALUES (?, ?, ?)');
                $ins->execute([$name, $leagueId, now_iso()]);
                $flash = 'Liga creada.';
            }
        } elseif ($action === 'league_delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM leagues WHERE id = ?');
                $del->execute([$delId]);
                $flash = 'Liga eliminada.';
            }
        /* ----------------------- Eventos ----------------------- */
        } elseif ($action === 'event_create' || $action === 'event_update') {
            $league   = trim((string) ($_POST['league'] ?? ''));
            $home     = trim((string) ($_POST['home'] ?? ''));
            $away     = trim((string) ($_POST['away'] ?? ''));
            $date     = valid_date((string) ($_POST['event_date'] ?? '')) ?? '';
            $time     = valid_time((string) ($_POST['event_time'] ?? ''));
            $channels = normalize_channels((string) ($_POST['channels'] ?? ''));
            $sort     = (int) ($_POST['sort'] ?? 0);

            if ($home === '' || $away === '' || $date === '') {
                $flash = 'Local, visitante y fecha son obligatorios.';
                $flashType = 'error';
            } else {
                if ($action === 'event_create') {
                    $ins = $pdo->prepare(
                        'INSERT INTO sport_events (league, home, away, event_date, event_time, channels, sort, created_at)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                    );
                    $ins->execute([$league, $home, $away, $date, $time, $channels, $sort, now_iso()]);
                    $flash = 'Evento creado.';
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        $upd = $pdo->prepare(
                            'UPDATE sport_events
                                SET league = ?, home = ?, away = ?, event_date = ?, event_time = ?, channels = ?, sort = ?
                              WHERE id = ?'
                        );
                        $upd->execute([$league, $home, $away, $date, $time, $channels, $sort, $editId]);
                        $flash = 'Evento actualizado.';
                    }
                }
            }
        } elseif ($action === 'event_delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM sport_events WHERE id = ?');
                $del->execute([$delId]);
                $flash = 'Evento eliminado.';
            }
        }
    } catch (Throwable $ex) {
        error_log('[sports] ' . $ex->getMessage());
        $flash = 'No se pudo completar la operación.';
        $flashType = 'error';
    }
}

/**
 * Normaliza una hora HH:MM (24h). Devuelve '' si no es válida.
 */
function valid_time(string $time): string
{
    $time = trim($time);
    if ($time === '') {
        return '';
    }
    return preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time) ? $time : '';
}

/**
 * Limpia una lista de canales separados por comas: recorta y elimina vacíos.
 */
function normalize_channels(string $raw): string
{
    $parts = array_filter(array_map('trim', explode(',', $raw)), static fn ($p) => $p !== '');
    return implode(', ', $parts);
}

// ¿Editando un evento?
$editing = null;
$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM sport_events WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

$leagues = $pdo->query('SELECT id, name, league_id, created_at FROM leagues ORDER BY name ASC, id ASC')->fetchAll();
$events  = $pdo->query('SELECT id, league, home, away, event_date, event_time, channels, sort FROM sport_events ORDER BY event_date ASC, event_time ASC, sort ASC, id ASC')->fetchAll();

$pageTitle = 'Deportes';
require __DIR__ . '/lib/header.php';
?>

<?php if ($flash !== ''): ?>
    <div class="alert <?= $flashType === 'ok' ? 'alert-success' : 'alert-danger' ?>"><?= e($flash) ?></div>
<?php endif; ?>

<!-- Ligas -->
<div class="card mb-4">
    <div class="card-header"><h2 class="h6 mb-0">Ligas</h2></div>
    <div class="card-body">
        <form method="post" action="sports.php">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="league_create">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label" for="name">Nombre</label>
                    <input type="text" class="form-control" id="name" name="name" placeholder="LaLiga" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="league_id">League ID (opcional)</label>
                    <input type="text" class="form-control mono" id="league_id" name="league_id" placeholder="140">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button class="btn btn-primary w-100" type="submit"><i class="la la-plus"></i> Añadir</button>
                </div>
            </div>
        </form>
    </div>

    <?php if (count($leagues) === 0): ?>
        <div class="card-body border-top">
            <p class="text-body-secondary mb-0">Aún no hay ligas. Añade una arriba.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Nombre</th>
                        <th>League ID</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($leagues as $lg): ?>
                        <tr>
                            <td><?= e($lg['name']) ?></td>
                            <td class="mono"><?= e($lg['league_id'] ?: '—') ?></td>
                            <td class="text-end">
                                <form method="post" action="sports.php" onsubmit="return confirm('¿Eliminar esta liga?');" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="league_delete">
                                    <input type="hidden" name="id" value="<?= (int) $lg['id'] ?>">
                                    <button class="btn btn-sm btn-danger" type="submit"><i class="la la-trash"></i> Borrar</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Evento (alta/edición) -->
<div class="card mb-4">
    <div class="card-header"><h2 class="h6 mb-0"><?= $editing ? 'Editar evento' : 'Añadir evento' ?></h2></div>
    <div class="card-body">
        <form method="post" action="sports.php">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="<?= $editing ? 'event_update' : 'event_create' ?>">
            <?php if ($editing): ?>
                <input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
            <?php endif; ?>
            <div class="row g-3">
                <div class="col-md-4">
                    <label class="form-label" for="league">Liga</label>
                    <input type="text" class="form-control" id="league" name="league" value="<?= e($editing['league'] ?? '') ?>" list="leagues-list" placeholder="LaLiga">
                    <datalist id="leagues-list">
                        <?php foreach ($leagues as $lg): ?>
                            <option value="<?= e($lg['name']) ?>"></option>
                        <?php endforeach; ?>
                    </datalist>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="home">Local</label>
                    <input type="text" class="form-control" id="home" name="home" value="<?= e($editing['home'] ?? '') ?>" placeholder="Real Madrid" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="away">Visitante</label>
                    <input type="text" class="form-control" id="away" name="away" value="<?= e($editing['away'] ?? '') ?>" placeholder="Barcelona" required>
                </div>
            </div>
            <div class="row g-3 mt-0">
                <div class="col-md-3">
                    <label class="form-label" for="event_date">Fecha</label>
                    <input type="date" class="form-control" id="event_date" name="event_date" value="<?= e($editing['event_date'] ?? '') ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label" for="event_time">Hora</label>
                    <input type="time" class="form-control" id="event_time" name="event_time" value="<?= e($editing['event_time'] ?? '') ?>">
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="channels">Canales (separados por comas)</label>
                    <input type="text" class="form-control" id="channels" name="channels" value="<?= e($editing['channels'] ?? '') ?>" placeholder="Canal 1, Canal 2">
                </div>
                <div class="col-md-2">
                    <label class="form-label" for="sort">Orden</label>
                    <input type="number" class="form-control" id="sort" name="sort" value="<?= e((string) ($editing['sort'] ?? '0')) ?>" min="0">
                </div>
            </div>
            <div class="mt-3 actions-row">
                <button class="btn btn-primary" type="submit"><?= $editing ? 'Guardar cambios' : 'Añadir evento' ?></button>
                <?php if ($editing): ?>
                    <a class="btn btn-outline-secondary" href="sports.php">Cancelar</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<!-- Lista de eventos -->
<div class="card">
    <div class="card-header"><h2 class="h6 mb-0"><?= count($events) ?> evento<?= count($events) === 1 ? '' : 's' ?></h2></div>

    <?php if (count($events) === 0): ?>
        <div class="card-body">
            <p class="text-body-secondary mb-0">Aún no hay eventos. Añade uno arriba.</p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Fecha</th>
                        <th>Hora</th>
                        <th>Liga</th>
                        <th>Partido</th>
                        <th>Canales</th>
                        <th class="text-end">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($events as $ev): ?>
                        <tr>
                            <td class="mono"><?= e($ev['event_date']) ?></td>
                            <td class="mono"><?= e($ev['event_time'] ?: '—') ?></td>
                            <td><?= e($ev['league'] ?: '—') ?></td>
                            <td><?= e($ev['home']) ?> <span class="text-body-tertiary">vs</span> <?= e($ev['away']) ?></td>
                            <td><?= e($ev['channels'] ?: '—') ?></td>
                            <td class="text-end actions-row">
                                <a class="btn btn-sm btn-outline-primary" href="sports.php?edit=<?= (int) $ev['id'] ?>"><i class="la la-edit"></i> Editar</a>
                                <form method="post" action="sports.php" onsubmit="return confirm('¿Eliminar este evento?');" class="d-inline">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="event_delete">
                                    <input type="hidden" name="id" value="<?= (int) $ev['id'] ?>">
                                    <button class="btn btn-sm btn-danger" type="submit"><i class="la la-trash"></i> Borrar</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php require __DIR__ . '/lib/footer.php'; ?>
