<?php
date_default_timezone_set('Europe/Samara');
session_start();
$max_attempts = 5;
$block_time = 900;

$valid_password_hash = '$2y$10$u7fFG/jte8oRpXbTog9QRezQAkK3QUSJ3yfPMFCj/RhOkMukXNHeS';
$file = __DIR__ . '/private/rsvp.csv';
$delimiter = ';';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_index']) && isset($_SESSION['auth']) && $_SESSION['auth'] === true) {
        $index = (int)$_POST['delete_index'];
        if (file_exists($file) && filesize($file) > 0) {
            $rows = [];
            $handle = fopen($file, 'r');
            if ($handle) {
                while (($data = fgetcsv($handle, 1000, $delimiter)) !== false) {
                    $rows[] = $data;
                }
                fclose($handle);
            }
            if (count($rows) > 0) {
                $header = $rows[0];
                $dataRows = array_slice($rows, 1);
                if (isset($dataRows[$index])) {
                    unset($dataRows[$index]);
                    $dataRows = array_values($dataRows);
                    $handle = fopen($file, 'w');
                    if ($handle) {
                        fputcsv($handle, $header, $delimiter);
                        foreach ($dataRows as $row) {
                            fputcsv($handle, $row, $delimiter);
                        }
                        fclose($handle);
                    }
                }
            }
        }
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }

    if (isset($_POST['password'])) {
        if (!isset($_SESSION['login_attempts'])) {
            $_SESSION['login_attempts'] = 0;
            $_SESSION['login_block_time'] = 0;
        }
        if ($_SESSION['login_block_time'] > time()) {
            $remaining = $_SESSION['login_block_time'] - time();
            $error = "Слишком много попыток. Попробуйте через $remaining секунд.";
            showLoginForm($error);
            exit;
        }
        if (password_verify($_POST['password'], $valid_password_hash)) {
            $_SESSION['auth'] = true;
            $_SESSION['login_attempts'] = 0;
            $_SESSION['login_block_time'] = 0;
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $_SESSION['login_attempts']++;
            if ($_SESSION['login_attempts'] >= $max_attempts) {
                $_SESSION['login_block_time'] = time() + $block_time;
                $_SESSION['login_attempts'] = 0;
                $error = "Превышено количество попыток. Блокировка на 15 минут.";
                showLoginForm($error);
                exit;
            }
            $error = 'Неверный пароль';
            showLoginForm($error);
            exit;
        }
    }

    $raw = file_get_contents('php://input');
    $input = json_decode($raw, true);
    if (!$input && !empty($_POST)) {
        $input = $_POST;
    }
    if (!$input) {
        echo json_encode(['status' => 'error', 'message' => 'Нет данных']);
        exit;
    }

    $name = trim($input['name'] ?? '');
    $attendance = $input['attendance'] ?? 'yes';
    $second_half = trim($input['second_half_name'] ?? '');
    $preferences = trim($input['preferences'] ?? '');
    $timestamp = date('Y-m-d H:i:s');

    if (empty($name)) {
        echo json_encode(['status' => 'error', 'message' => 'Имя обязательно']);
        exit;
    }

    $isNew = !file_exists($file) || filesize($file) === 0;
    $handle = fopen($file, 'a');
    if ($handle === false) {
        echo json_encode(['status' => 'error', 'message' => 'Ошибка записи в файл']);
        exit;
    }
    if ($isNew) {
        fputcsv($handle, ['Дата', 'Имя', 'Присутствие', 'Вторая половинка', 'Предпочтения'], $delimiter);
    }
    fputcsv($handle, [$timestamp, $name, $attendance, $second_half, $preferences], $delimiter);
    fclose($handle);

    echo json_encode(['status' => 'success', 'message' => 'Сохранено']);
    exit;
}

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

if (isset($_SESSION['auth']) && $_SESSION['auth'] === true) {
    showTable($file, $delimiter);
    exit;
}

showLoginForm();
exit;

function showLoginForm($error = null) {
    ?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Вход для просмотра ответов</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Cormorant Garamond', Georgia, serif;
            background: #f5f0eb;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
        }
        .login-box {
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(12px);
            padding: 40px 35px;
            border-radius: 24px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.3);
            width: 100%;
            max-width: 400px;
            text-align: center;
        }
        h2 {
            font-weight: 400;
            font-size: 2.4rem;
            letter-spacing: 2px;
            color: #3a3836;
            margin-top: 0;
            margin-bottom: 20px;
            white-space: nowrap;
        }
        input {
            width: 100%;
            padding: 14px 18px;
            margin: 10px 0;
            border: 1px solid #dcd7d0;
            border-radius: 10px;
            font-family: 'Cormorant Garamond', Georgia, serif;
            font-size: 1.3rem;
            background: rgba(255, 255, 255, 0.9);
            outline: none;
            box-sizing: border-box;
        }
        input:focus { border-color: #3a3836; }
        button {
            width: 100%;
            padding: 16px;
            background: #3a3836;
            color: #fff;
            border: none;
            border-radius: 50px;
            font-family: 'Cormorant Garamond', Georgia, serif;
            font-size: 1.3rem;
            letter-spacing: 2px;
            cursor: pointer;
            transition: background 0.3s;
            margin-top: 10px;
            white-space: nowrap;
        }
        button:hover { background: #554e48; }
        .error { color: #b34a4a; margin: 10px 0; font-size: 1.2rem; }
        .footer-links { margin-top: 20px; }
        .footer-links a {
            color: #8a7a6a;
            text-decoration: none;
            font-size: 1.2rem;
            white-space: nowrap;
        }
        .footer-links a:hover { text-decoration: underline; }
        @media (max-width: 480px) {
            .login-box { padding: 30px 20px; }
            h2 { font-size: 1.8rem; }
            input, button { font-size: 1.1rem; padding: 12px 15px; }
            .footer-links a { font-size: 1rem; }
        }
    </style>
</head>
<body>
    <div class="login-box">
        <h2>🔐 Введите пароль</h2>
        <?php if ($error): ?>
            <div class="error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <form method="post">
            <input type="password" name="password" placeholder="Пароль" required>
            <button type="submit">Войти</button>
        </form>
        <div class="footer-links">
            <a href="index.html">← На главную</a>
        </div>
    </div>
</body>
</html>
<?php
}

function showTable($file, $delimiter) {
    $rows = [];
    if (file_exists($file) && filesize($file) > 0) {
        $handle = fopen($file, 'r');
        if ($handle) {
            while (($data = fgetcsv($handle, 1000, $delimiter)) !== false) {
                $rows[] = $data;
            }
            fclose($handle);
        }
    }

    $headers = ['Дата', 'Имя', 'Присутствие', 'Предпочтения'];
    if (!empty($rows) && count($rows) > 0) {
        $first = $rows[0];
        if (count($first) >= 5) {
            $headers = ['Дата', 'Имя', 'Присутствие', 'Вторая половинка', 'Предпочтения'];
        }
        if (in_array('Дата', $first) && in_array('Имя', $first)) {
            array_shift($rows);
        }
    }
    ?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ответы гостей</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
    <style>
        @font-face {
            font-family: 'Lastochka';
            src: url('fonts/Lastochka.ttf') format('truetype');
            font-weight: normal;
            font-style: normal;
            font-display: swap;
        }
        .font-lastochka {
            font-family: 'Lastochka', cursive, sans-serif !important;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Cormorant Garamond', Georgia, serif;
            background: #f5f0eb;
            margin: 30px 15px;
            color: #3a3836;
            font-size: 1.4rem;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.75);
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(12px);
            padding: 45px 40px;
            border-radius: 24px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        h1 {
            text-align: center;
            font-weight: 400;
            font-size: 4rem;
            letter-spacing: 2px;
            color: #3a3836;
            margin-top: 0;
            padding-bottom: 25px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            white-space: nowrap;
        }
        .stats {
            text-align: center;
            margin: 25px 0 30px;
            font-size: 1.6rem;
            color: #555;
        }
        .stats span {
            font-weight: 500;
            color: #3a3836;
        }
        .table-wrapper {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            margin: 0 -10px;
            padding: 0 10px;
        }
        table {
            width: 100%;
            min-width: 500px;
            table-layout: auto;
            border-collapse: collapse;
            font-size: 1.2rem;
            word-wrap: break-word;
        }
        th, td {
            padding: 10px 8px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.08);
            vertical-align: middle;
        }
        th {
            background: rgba(240, 235, 229, 0.6);
            font-weight: 500;
            letter-spacing: 0.5px;
            color: #2c2a28;
            font-size: 1.1rem;
            white-space: nowrap;
        }
        td:not(:nth-child(4)) {
            white-space: nowrap;
        }
        td:nth-child(4) {
            word-break: break-word;
            white-space: normal;
        }
        tr:hover {
            background: rgba(255, 255, 255, 0.4);
        }
        .attendance-yes {
            color: #2a7a3b;
            font-weight: 500;
        }
        .attendance-pair {
            color: #a67c52;
            font-weight: 500;
        }
        .attendance-no {
            color: #b34a4a;
            font-weight: 500;
        }
        .btn {
            display: inline-block;
            padding: 6px 12px;
            background: #3a3836;
            color: #fff !important;
            text-decoration: none;
            border-radius: 40px;
            font-size: 0.95rem;
            transition: background 0.2s;
            border: none;
            cursor: pointer;
            font-family: 'Cormorant Garamond', Georgia, serif;
            white-space: nowrap;
        }
        .btn:hover {
            background: #554e48;
        }
        .btn-danger {
            background: #b34a4a;
        }
        .btn-danger:hover {
            background: #8f3a3a;
        }
        .btn-out {
            background: #8a7a6a;
        }
        .btn-out:hover {
            background: #6b5f50;
        }
        .footer-links {
            text-align: center;
            margin-top: 35px;
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        .empty-msg {
            text-align: center;
            color: #777;
            padding: 50px 0;
            font-size: 1.6rem;
        }
        @media (max-width: 600px) {
            .container { padding: 20px 15px; }
            h1 { font-size: 2.8rem; white-space: normal; }
            .stats { font-size: 1.3rem; }
            .table-wrapper { margin: 0 -5px; padding: 0 5px; }
            table { font-size: 0.9rem; min-width: 400px; }
            th, td { padding: 6px 4px; }
            th { font-size: 0.85rem; }
            td:not(:nth-child(4)) { white-space: nowrap; }
        }
        @media (max-width: 400px) {
            table { font-size: 0.75rem; min-width: 320px; }
            th, td { padding: 4px 2px; }
            th { font-size: 0.7rem; }
            .btn { font-size: 0.65rem; padding: 3px 6px; }
        }
    </style>
    <script>
        function confirmDelete() {
            return confirm('⚠️ Вы уверены, что хотите удалить эту запись? Это действие нельзя отменить!');
        }
    </script>
</head>
<body>
<div class="container">
    <h1 class="font-lastochka">📋 Ответы гостей</h1>
    <?php if (!empty($rows)): ?>
        <div class="stats">
            Всего ответов: <span><?= count($rows) ?></span>
            &nbsp;|&nbsp;
            Придут: <span><?= count(array_filter($rows, fn($r) => in_array($r[2] ?? '', ['yes', 'pair']))) ?></span>
            &nbsp;|&nbsp;
            Не придут: <span><?= count(array_filter($rows, fn($r) => ($r[2] ?? '') === 'no')) ?></span>
        </div>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <?php foreach ($headers as $h): ?>
                            <th><?= htmlspecialchars($h) ?></th>
                        <?php endforeach; ?>
                        <th>Действие</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                foreach ($rows as $idx => $row):
                    while (count($row) < 5) $row[] = '';
                ?>
                    <tr>
                        <?php for ($i = 0; $i < count($headers); $i++):
                            $cell = $row[$i] ?? '';
                            if ($i === 2 && $headers[$i] === 'Присутствие'):
                                $val = trim($cell);
                                $label = match($val) {
                                    'yes' => '✅ Приду',
                                    'pair' => '👫 Приду с парой',
                                    'no' => '❌ Не смогу',
                                    default => htmlspecialchars($val)
                                };
                                echo "<td><span class='attendance-$val'>$label</span></td>";
                            else:
                                echo "<td>" . htmlspecialchars($cell) . "</td>";
                            endif;
                        endfor; ?>
                        <td>
                            <form method="post" onsubmit="return confirmDelete();">
                                <input type="hidden" name="delete_index" value="<?= $idx ?>">
                                <button type="submit" class="btn btn-danger">🗑</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <p class="empty-msg">Нет сохранённых ответов.</p>
    <?php endif; ?>
    <div class="footer-links">
        <a href="?logout=1" class="btn btn-out">🚪 Выйти</a>
        <a href="index.html" class="btn btn-out">← На главную</a>
    </div>
</div>
</body>
</html>
<?php
}
?>
