<?php
session_start();
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../includes/helpers.php';

$database = new Database();
$db = $database->getConnection();

$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $day_of_week = $_POST['day_of_week'] ?? 1;
    $start_time = $_POST['start_time'] ?? '';
    $end_time = $_POST['end_time'] ?? '';
    $video_path = $_POST['video_path'] ?? '';
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($action === 'add') {
        $stmt = $db->prepare("INSERT INTO schedule (title, description, day_of_week, start_time, end_time, video_path, is_active) VALUES (:title, :description, :day_of_week, :start_time, :end_time, :video_path, :is_active)");
        $stmt->execute([
            ':title' => $title,
            ':description' => $description,
            ':day_of_week' => $day_of_week,
            ':start_time' => $start_time,
            ':end_time' => $end_time,
            ':video_path' => $video_path,
            ':is_active' => $is_active
        ]);
        $message = 'Broadcast added successfully.';
        $action = 'list';
    } elseif ($action === 'edit' && $id) {
        $stmt = $db->prepare("UPDATE schedule SET title = :title, description = :description, day_of_week = :day_of_week, start_time = :start_time, end_time = :end_time, video_path = :video_path, is_active = :is_active WHERE id = :id");
        $stmt->execute([
            ':title' => $title,
            ':description' => $description,
            ':day_of_week' => $day_of_week,
            ':start_time' => $start_time,
            ':end_time' => $end_time,
            ':video_path' => $video_path,
            ':is_active' => $is_active,
            ':id' => $id
        ]);
        $message = 'Broadcast updated successfully.';
        $action = 'list';
    }
}

if ($action === 'delete' && $id) {
    $stmt = $db->prepare("DELETE FROM schedule WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $message = 'Broadcast deleted successfully.';
    $action = 'list';
}

$cdnLinks = $db->query("SELECT id, name, url FROM cdn_links")->fetchAll(PDO::FETCH_ASSOC);

$days = [
    1 => 'Понедельник',
    2 => 'Вторник',
    3 => 'Среда',
    4 => 'Четверг',
    5 => 'Пятница',
    6 => 'Суббота',
    7 => 'Воскресенье'
];

?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Schedule Management - Admin</title>
    <link rel="stylesheet" href="css/admin.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">MYRIADONICA</div>
        <a href="index.php" class="nav-item"><i class="fas fa-home"></i> Панель</a>
        <a href="schedule.php" class="nav-item active"><i class="fas fa-calendar-alt"></i> Расписание</a>
        <a href="cdn.php" class="nav-item"><i class="fas fa-server"></i> CDN Серверы</a>
        <a href="info_blocks.php" class="nav-item"><i class="fas fa-info-circle"></i> Инфо-блоки</a>
        <a href="settings.php" class="nav-item"><i class="fas fa-cog"></i> Настройки</a>
        <a href="telegram.php" class="nav-item"><i class="fab fa-telegram"></i> Телеграм</a>
        <a href="database.php" class="nav-item"><i class="fas fa-database"></i> База данных</a>
        <a href="logout.php" class="nav-item" style="margin-top: auto;"><i class="fas fa-sign-out-alt"></i> Выход</a>
    </div>

    <div class="main-content">
        <div class="header">
            <div>
                <h1>Управление расписанием</h1>
                <p style="color: var(--secondary-color); margin: 0;">
                    <i class="fas fa-clock"></i> Время сервера: <strong><?php echo date('H:i'); ?></strong> (МСК)
                </p>
            </div>
            <?php if ($action === 'list'): ?>
                <a href="schedule.php?action=add" class="btn btn-primary">Добавить трансляцию</a>
            <?php endif; ?>
        </div>

        <?php if ($message): ?>
            <div class="card" style="color: var(--secondary-color);"><?php echo $message; ?></div>
        <?php endif; ?>

        <?php if ($action === 'list'): ?>
            <div class="card">
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="text-align: left; border-bottom: 1px solid var(--border-color);">
                            <th style="padding: 10px;">ID</th>
                            <th style="padding: 10px;">День</th>
                            <th style="padding: 10px;">Заголовок</th>
                            <th style="padding: 10px;">Начало</th>
                            <th style="padding: 10px;">Конец</th>
                            <th style="padding: 10px;">Активно</th>
                            <th style="padding: 10px;">Действия</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $stmt = $db->query("SELECT * FROM schedule ORDER BY FIELD(day_of_week, 1, 2, 3, 4, 5, 6, 7), start_time ASC");
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):
                        ?>
                        <tr style="border-bottom: 1px solid var(--border-color);">
                            <td style="padding: 10px;"><?php echo $row['id']; ?></td>
                            <td style="padding: 10px;"><?php echo $days[$row['day_of_week']] ?? '-'; ?></td>
                            <td style="padding: 10px;"><?php echo $row['title']; ?></td>
                            <td style="padding: 10px;"><?php echo substr($row['start_time'], 0, 5); ?></td>
                            <td style="padding: 10px;"><?php echo substr($row['end_time'], 0, 5); ?></td>
                            <td style="padding: 10px;"><?php echo $row['is_active'] ? 'Да' : 'Нет'; ?></td>
                            <td style="padding: 10px;">
                                <a href="schedule.php?action=edit&id=<?php echo $row['id']; ?>" style="color: var(--accent-color); margin-right: 10px;"><i class="fas fa-edit"></i></a>
                                <a href="schedule.php?action=delete&id=<?php echo $row['id']; ?>" style="color: var(--error-color);" onclick="return confirm('Вы уверены?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php elseif ($action === 'add' || $action === 'edit'): 
            $item = ['title' => '', 'description' => '', 'day_of_week' => 1, 'start_time' => '', 'end_time' => '', 'cdn_id' => '', 'video_path' => '', 'is_active' => 1];
            if ($action === 'edit' && $id) {
                $stmt = $db->prepare("SELECT * FROM schedule WHERE id = :id");
                $stmt->execute([':id' => $id]);
                $item = $stmt->fetch(PDO::FETCH_ASSOC);
            }
        ?>
            <div class="card">
                <form method="POST">
                    <div class="form-group">
                        <label>Заголовок</label>
                        <input type="text" name="title" value="<?php echo htmlspecialchars($item['title'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Описание</label>
                        <textarea name="description" rows="3"><?php echo htmlspecialchars($item['description'] ?? ''); ?></textarea>
                    </div>
                    <div class="form-group">
                        <label>День недели</label>
                        <select name="day_of_week" required>
                            <?php foreach ($days as $num => $name): ?>
                                <option value="<?php echo $num; ?>" <?php echo $item['day_of_week'] == $num ? 'selected' : ''; ?>><?php echo $name; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div style="display: flex; gap: 20px;">
                        <div class="form-group" style="flex: 1;">
                            <label>Время начала (МСК)</label>
                            <input type="time" name="start_time" value="<?php echo substr($item['start_time'], 0, 5); ?>" required>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Время окончания (МСК)</label>
                            <input type="time" name="end_time" value="<?php echo substr($item['end_time'], 0, 5); ?>" required>
                        </div>
                    </div>
                    <!-- CDN selector removed as per global CDN requirement -->
                    <div class="form-group">
                        <label>Путь к видео (например: video/rose/master.m3u8)</label>
                        <input type="text" name="video_path" value="<?php echo htmlspecialchars($item['video_path']); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" name="is_active" <?php echo $item['is_active'] ? 'checked' : ''; ?> style="width: auto;"> Активна
                        </label>
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo $action === 'add' ? 'Добавить' : 'Сохранить'; ?></button>
                    <a href="schedule.php" class="btn btn-secondary">Отмена</a>
                </form>
            </div>
            <!-- updateCdnUrl removed as CDN editing is moved to CDN section -->
        <?php endif; ?>
    </div>

    <?php if ($action === 'list'): ?>
    <script>
        console.log("Schedule list loaded");
    </script>
    <?php endif; ?>
</body>
</html>
