<?php
session_start();
date_default_timezone_set('Europe/Moscow');
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../../config/db.php';

$database = new Database();
$db = $database->getConnection();

$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? null;
$message = '';

// Fetch Telegram Groups
$groups = $db->query("SELECT * FROM telegram_groups")->fetchAll(PDO::FETCH_ASSOC);

$edit_post = null;
if (($action === 'edit' || $action === 'add') && $id) {
    $stmt = $db->prepare("SELECT * FROM telegram_posts WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $edit_post = $stmt->fetch(PDO::FETCH_ASSOC);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['add_post']) || isset($_POST['edit_post']))) {
    $content = $_POST['content'] ?? '';
    $post_type = $_POST['post_type'] ?? 'text';
    $scheduled_at = $_POST['scheduled_at'] ?? '';
    $group_id = $_POST['group_id'] ?? null;
    $repeat_count = $_POST['repeat_count'] ?? 0;
    $repeat_interval = $_POST['repeat_interval'] ?? 1;
    $repeat_unit = $_POST['repeat_unit'] ?? 'days';
    $is_recurring = isset($_POST['is_recurring']) ? 1 : 0;
    $delete_after = $_POST['delete_after'] ?? 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $media_url = $_POST['media_url'] ?? '';
    
    $media_path = $_POST['existing_media'] ?? '';
    if (isset($_FILES['media']) && $_FILES['media']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['media']['name'], PATHINFO_EXTENSION);
        $filename = uniqid() . '.' . $ext;
        $target = __DIR__ . '/../public/uploads/telegram/' . $filename;
        if (move_uploaded_file($_FILES['media']['tmp_name'], $target)) {
            $media_path = 'uploads/telegram/' . $filename;
        }
    }

    if (isset($_POST['edit_post']) && $id) {
        $stmt = $db->prepare("UPDATE telegram_posts SET 
            content = :content, 
            media_path = :media_path, 
            media_type = :media_type, 
            schedule_time = :scheduled_at, 
            group_id = :group_id, 
            repeat_count = :repeat_count, 
            repeat_interval = :repeat_interval, 
            repeat_unit = :repeat_unit, 
            is_recurring = :is_recurring, 
            delete_after_minutes = :delete_after, 
            is_active = :is_active,
            media_url = :media_url,
            is_sent = 0,
            sent_at = NULL,
            sent_message_id = NULL,
            is_deleted = 0
            WHERE id = :id");
        $stmt->execute([
            ':content' => $content,
            ':media_path' => $media_path,
            ':media_type' => $post_type === 'text' ? 'none' : $post_type,
            ':scheduled_at' => $scheduled_at,
            ':group_id' => $group_id,
            ':repeat_count' => $repeat_count,
            ':repeat_interval' => $repeat_interval,
            ':repeat_unit' => $repeat_unit,
            ':is_recurring' => $is_recurring,
            ':delete_after' => $delete_after,
            ':is_active' => $is_active,
            ':media_url' => $media_url,
            ':id' => $id
        ]);
        header('Location: telegram.php?message=Post+updated');
        exit;
    } else {
        $stmt = $db->prepare("INSERT INTO telegram_posts (content, media_path, media_url, media_type, schedule_time, group_id, repeat_count, repeat_interval, repeat_unit, is_recurring, delete_after_minutes, is_active) VALUES (:content, :media_path, :media_url, :media_type, :scheduled_at, :group_id, :repeat_count, :repeat_interval, :repeat_unit, :is_recurring, :delete_after, :is_active)");
        $stmt->execute([
            ':content' => $content,
            ':media_path' => $media_path,
            ':media_url' => $media_url,
            ':media_type' => $post_type === 'text' ? 'none' : $post_type,
            ':scheduled_at' => $scheduled_at,
            ':group_id' => $group_id,
            ':repeat_count' => $repeat_count,
            ':repeat_interval' => $repeat_interval,
            ':repeat_unit' => $repeat_unit,
            ':is_recurring' => $is_recurring,
            ':delete_after' => $delete_after,
            ':is_active' => $is_active
        ]);
        $newId = $db->lastInsertId();
        // Immediately set chain_id to its own ID if it was just created
        $db->prepare("UPDATE telegram_posts SET chain_id = id WHERE id = :id")->execute([':id' => $newId]);
        header('Location: telegram.php?message=Post+scheduled');
        exit;
    }
}

if ($action === 'delete' && $id) {
    // Delete by ID or by matching chain_id (if not NULL)
    $stmt = $db->prepare("
        DELETE FROM telegram_posts 
        WHERE id = :id 
        OR (chain_id IS NOT NULL AND chain_id = (SELECT chain_id FROM (SELECT chain_id FROM telegram_posts WHERE id = :id2) as t))
    ");
    $stmt->execute([':id' => $id, ':id2' => $id]);
    header('Location: telegram.php');
    exit;
}

if ($action === 'toggle_active' && $id) {
    // Toggle for specific ID and its chain (if exists)
    $stmt = $db->prepare("
        UPDATE telegram_posts p1 
        JOIN (SELECT id, chain_id, is_active FROM telegram_posts WHERE id = :id) p2 
        ON (p1.id = p2.id OR (p1.chain_id IS NOT NULL AND p1.chain_id = p2.chain_id))
        SET p1.is_active = NOT p2.is_active
    ");
    $stmt->execute([':id' => $id]);
    header('Location: telegram.php');
    exit;
}

if ($action === 'send_now' && $id) {
    // Force schedule time to now, ensure it's active and reset sent status
    $stmt = $db->prepare("UPDATE telegram_posts SET 
        schedule_time = NOW(), 
        is_active = 1, 
        is_sent = 0,
        sent_at = NULL,
        sent_message_id = NULL,
        is_deleted = 0
        WHERE id = :id");
    $stmt->execute([':id' => $id]);
    header('Location: telegram.php?message=Post+will+be+sent+within+30+seconds');
    exit;
}

?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Telegram Planner - 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"><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 active"><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>Планировщик постов Telegram</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'): ?>
                <div style="display: flex; gap: 10px;">
                    <button id="btnRefreshGroups" class="btn btn-secondary"><i class="fas fa-sync"></i> Обновить группы</button>
                    <a href="telegram.php?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> Новый пост</a>
                </div>
            <?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 id="syncResult" class="card" style="display: none; margin-bottom: 20px; border-left: 4px solid var(--secondary-color);"></div>
            <div class="card">
                <h3>Запланированные посты</h3>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="text-align: left; border-bottom: 1px solid var(--border-color);">
                            <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 p1.* 
                            FROM telegram_posts p1
                            JOIN (
                                SELECT chain_id, 
                                       CASE 
                                           WHEN MIN(CASE WHEN is_sent = 0 THEN id END) IS NOT NULL 
                                           THEN MIN(CASE WHEN is_sent = 0 THEN id END)
                                           ELSE MAX(id)
                                       END as display_id
                                FROM telegram_posts 
                                GROUP BY chain_id
                            ) p2 ON p1.id = p2.display_id
                            ORDER BY p1.schedule_time DESC
                        ");
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)):
                            $typeMap = ['none' => 'Текст', 'image' => 'Картинка', 'video' => 'Видео', 'file' => 'Файл'];
                            $is_active = $row['is_active'];
                            $is_sent = $row['is_sent'];
                            
                            $status_color = 'var(--text-color)';
                            $status_text = 'Ожидает';
                            
                            if ($is_sent && !$row['is_recurring']) {
                                $status_text = 'Завершено';
                                $status_color = '#888';
                            } elseif ($is_sent && $row['is_recurring']) {
                                $status_text = $is_active ? 'В ротации' : 'Приостановлен';
                                $status_color = $is_active ? 'var(--secondary-color)' : 'var(--error-color)';
                            } elseif (!$is_active) {
                                $status_text = 'Отключен';
                                $status_color = 'var(--error-color)';
                            }
                        ?>
                        <tr style="border-bottom: 1px solid var(--border-color); <?php echo !$is_active ? 'opacity: 0.6;' : ''; ?>">
                            <td style="padding: 10px;"><?php echo $typeMap[$row['media_type']] ?? $row['media_type']; ?></td>
                            <td style="padding: 10px;"><?php echo $row['schedule_time']; ?></td>
                            <td style="padding: 10px;">
                                <span style="color: <?php echo $status_color; ?>"><?php echo $status_text; ?></span>
                                <?php if ($row['is_recurring']): ?>
                                    <i class="fas fa-redo" title="Повторяющийся (осталось: <?php echo (int)$row['repeat_count'] === 0 ? '∞' : $row['repeat_count']; ?>)" style="font-size: 0.8em; margin-left: 5px; color: var(--secondary-color);"></i>
                                <?php endif; ?>
                            </td>
                            <td style="padding: 10px;">
                                <a href="telegram.php?action=toggle_active&id=<?php echo $row['id']; ?>" style="color: <?php echo $is_active ? 'var(--secondary-color)' : 'var(--error-color)'; ?>; margin-right: 10px;" title="<?php echo $is_active ? 'Деактивировать' : 'Активировать'; ?>">
                                    <i class="fas <?php echo $is_active ? 'fa-toggle-on' : 'fa-toggle-off'; ?>"></i>
                                </a>
                                <a href="telegram.php?action=edit&id=<?php echo $row['id']; ?>" style="color: var(--text-color); margin-right: 10px;" title="Редактировать"><i class="fas fa-edit"></i></a>
                                <?php if (!$is_sent): ?>
                                    <a href="telegram.php?action=send_now&id=<?php echo $row['id']; ?>" style="color: var(--secondary-color); margin-right: 10px;" title="Отправить сейчас"><i class="fas fa-paper-plane"></i></a>
                                <?php else: ?>
                                    <a href="telegram.php?action=add&id=<?php echo $row['id']; ?>" style="color: #aaa; margin-right: 10px;" title="Использовать как шаблон"><i class="fas fa-copy"></i></a>
                                <?php endif; ?>
                                <a href="telegram.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'): ?>
            <div class="card">
                <h3><?php echo $action === 'edit' ? 'Редактировать пост' : 'Запланировать новый пост'; ?></h3>
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($edit_post): ?>
                        <input type="hidden" name="existing_media" value="<?php echo $edit_post['media_path']; ?>">
                    <?php endif; ?>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div class="form-group" style="grid-column: span 2;">
                            <label>Целевая группа</label>
                            <div style="display: flex; gap: 10px;">
                                <select name="group_id" required style="flex: 1;">
                                    <option value="">Выберите группу</option>
                                    <?php foreach ($groups as $g): ?>
                                        <option value="<?php echo $g['id']; ?>" <?php echo ($edit_post && $edit_post['group_id'] == $g['id']) ? 'selected' : ''; ?>>
                                            <?php echo $g['group_name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" id="btnRefreshAdd" class="btn btn-secondary" title="Обновить список"><i class="fas fa-sync"></i></button>
                            </div>
                        </div>
                        <div class="form-group" style="grid-column: span 2;">
                            <label>Контент поста (поддерживает HTML)</label>
                            <textarea name="content" rows="8" required><?php echo $edit_post ? htmlspecialchars($edit_post['content']) : ''; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label>Тип поста</label>
                            <select name="post_type">
                                <option value="text" <?php echo ($edit_post && $edit_post['media_type'] === 'none') ? 'selected' : ''; ?>>Только текст</option>
                                <option value="image" <?php echo ($edit_post && $edit_post['media_type'] === 'image') ? 'selected' : ''; ?>>Картинка</option>
                                <option value="video" <?php echo ($edit_post && $edit_post['media_type'] === 'video') ? 'selected' : ''; ?>>Видео/Анимация</option>
                                <option value="file" <?php echo ($edit_post && $edit_post['media_type'] === 'file') ? 'selected' : ''; ?>>Файл (Аудио, PDF)</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Медиафайл <?php echo ($edit_post && $edit_post['media_path']) ? '(уже загружен)' : ''; ?></label>
                            <input type="file" name="media">
                        </div>
                        <div class="form-group" style="grid-column: span 2;">
                            <label>или URL на медиафайл (воркер скачает его сам)</label>
                            <input type="text" name="media_url" value="<?php echo $edit_post ? htmlspecialchars($edit_post['media_url'] ?? '') : ''; ?>" placeholder="https://example.com/image.jpg">
                        </div>
                        <div class="form-group">
                            <label>Запланировать на</label>
                            <input type="datetime-local" name="scheduled_at" required value="<?php echo $edit_post ? date('Y-m-d\TH:i', strtotime($edit_post['schedule_time'])) : ''; ?>">
                        </div>
                        <div class="form-group" style="grid-column: span 2; display: flex; gap: 20px;">
                            <label style="display: flex; align-items: center; cursor: pointer; color: var(--secondary-color); font-weight: bold;">
                                <input type="checkbox" name="is_recurring" id="is_recurring" style="width: auto; margin-right: 10px;" <?php echo ($edit_post && $edit_post['is_recurring']) ? 'checked' : ''; ?>>
                                <i class="fas fa-redo" style="margin-right: 5px;"></i> Повторять этот пост
                            </label>
                            <label style="display: flex; align-items: center; cursor: pointer; color: var(--text-color); font-weight: bold;">
                                <input type="checkbox" name="is_active" style="width: auto; margin-right: 10px;" <?php echo (!$edit_post || $edit_post['is_active']) ? 'checked' : ''; ?>>
                                <i class="fas fa-power-off" style="margin-right: 5px;"></i> Активен
                            </label>
                        </div>

                        <div id="repeat_settings" style="display: <?php echo ($edit_post && $edit_post['is_recurring']) ? 'grid' : 'none'; ?>; grid-column: span 2; grid-template-columns: 1fr 1fr; gap: 20px; padding: 15px; background: rgba(255,255,255,0.05); border-radius: 8px; border: 1px dashed var(--border-color);">
                            <div class="form-group">
                                <label>Количество повторов (0 - бесконечно)</label>
                                <input type="number" name="repeat_count" value="<?php echo $edit_post ? $edit_post['repeat_count'] : '0'; ?>" min="0">
                            </div>
                            <div class="form-group">
                                <label>Интервал повтора</label>
                                <div style="display: flex; gap: 5px;">
                                    <input type="number" name="repeat_interval" value="<?php echo $edit_post ? $edit_post['repeat_interval'] : '1'; ?>" min="1" style="flex: 1;">
                                    <select name="repeat_unit" style="flex: 1;">
                                        <option value="minutes" <?php echo ($edit_post && $edit_post['repeat_unit'] === 'minutes') ? 'selected' : ''; ?>>Минуты</option>
                                        <option value="hours" <?php echo ($edit_post && $edit_post['repeat_unit'] === 'hours') ? 'selected' : ''; ?>>Часы</option>
                                        <option value="days" <?php echo (!$edit_post || $edit_post['repeat_unit'] === 'days') ? 'selected' : ''; ?>>Дни</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Авто-удаление через (минуты)</label>
                            <input type="number" name="delete_after" value="<?php echo $edit_post ? $edit_post['delete_after_minutes'] : '0'; ?>">
                        </div>
                    </div>
                    <div style="margin-top: 20px;">
                        <button type="submit" name="<?php echo $action === 'edit' ? 'edit_post' : 'add_post'; ?>" class="btn btn-primary">
                            <?php echo $action === 'edit' ? 'Сохранить изменения' : 'Запланировать пост'; ?>
                        </button>
                        <a href="telegram.php" class="btn btn-secondary">Отмена</a>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function syncGroups() {
            const btn = document.activeElement;
            const originalHtml = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Синхронизация...';

            fetch('api/telegram_sync.php')
                .then(response => response.json())
                .then(data => {
                    btn.disabled = false;
                    btn.innerHTML = originalHtml;
                    
                    const resultDiv = document.getElementById('syncResult');
                    if (data.success) {
                        if (resultDiv) {
                            resultDiv.style.display = 'block';
                            resultDiv.innerHTML = `Группы обновлены! Найдено новых групп: <strong>${data.new_groups}</strong>. Обновите страницу, если данные не появились.`;
                            resultDiv.style.borderColor = 'var(--secondary-color)';
                        } else {
                            location.reload();
                        }
                    } else {
                        alert('Ошибка: ' + data.error);
                    }
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.innerHTML = originalHtml;
                    alert('Ошибка сети при синхронизации.');
                });
        }

        if (document.getElementById('btnRefreshGroups')) {
            document.getElementById('btnRefreshGroups').addEventListener('click', syncGroups);
        }
        if (document.getElementById('btnRefreshAdd')) {
            document.getElementById('btnRefreshAdd').addEventListener('click', () => {
                syncGroups();
                setTimeout(() => location.reload(), 2000);
            });
        }

        if (document.getElementById('is_recurring')) {
            document.getElementById('is_recurring').addEventListener('change', function() {
                const settings = document.getElementById('repeat_settings');
                settings.style.display = this.checked ? 'grid' : 'none';
            });
        }
    </script>
</body>
</html>
