<?php
/**
 * ================================================
 * ESTREKA KALENDRI PEALEHT - SAMM-SAMMULINE SÜNDMUSE LISAMINE
 * ================================================
 * 
 * FUNKTSIOONID:
 * - Samm-sammuline sündmuse lisamine (wizard)
 * - Sündmuste CRUD (loomine, muutmine, kustutamine)
 * - Kategooriate haldus
 * - Meeldetuletuste süsteem
 * - API integratsioon
 * - Responsiivne disain
 * - PARANDATUD: Täpse kellaaja tugi
 * 
 * ================================================
 */

// Põhiseadistused
require_once 'config/config.php';
require_once 'config/database.php';
require_once 'includes/functions.php';

session_start();

// Kontrolli sisselogimist
requireLogin();

$current_user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? ($_SESSION['firstName'] . ' ' . $_SESSION['lastName']);

// Debug mode check
$debug_mode = isset($_GET['debug']) ? true : false;

// ====================
// ANDMEBAASI TABELITE LOOMINE
// ====================
function ensureCalendarTables($pdo) {
    try {
        // Events tabel
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                title VARCHAR(255) NOT NULL,
                description TEXT,
                start_datetime TIMESTAMP NOT NULL,
                end_datetime TIMESTAMP,
                all_day BOOLEAN DEFAULT 0,
                location VARCHAR(255),
                category_id INTEGER,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
                FOREIGN KEY (category_id) REFERENCES event_categories(id) ON DELETE SET NULL
            )
        ");

        // Event categories tabel
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS event_categories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                name VARCHAR(255) NOT NULL,
                color VARCHAR(7) NOT NULL DEFAULT '#3B82F6',
                icon VARCHAR(10) NOT NULL DEFAULT '📅',
                default_reminder_minutes INTEGER DEFAULT 60,
                reminder_enabled BOOLEAN DEFAULT 1,
                custom_message_template TEXT,
                is_system BOOLEAN DEFAULT 0,
                is_active BOOLEAN DEFAULT 1,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            )
        ");

        // Event reminders tabel
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS event_reminders (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                event_id INTEGER NOT NULL,
                custom_message TEXT NOT NULL,
                reminder_datetime TIMESTAMP NOT NULL,
                minutes_before INTEGER NOT NULL DEFAULT 60,
                is_recurring BOOLEAN DEFAULT 0,
                recurring_type VARCHAR(20) DEFAULT NULL,
                recurring_interval INTEGER DEFAULT 1,
                recurring_end_date DATE DEFAULT NULL,
                is_enabled BOOLEAN DEFAULT 1,
                sent_at TIMESTAMP NULL,
                sent_count INTEGER DEFAULT 0,
                last_error TEXT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE
            )
        ");

        // Loo vaikimisi kategooriad kasutajale kui puuduvad
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM event_categories WHERE user_id = ?");
        $stmt->execute([$current_user_id]);
        $userCategoriesCount = $stmt->fetch()['count'];

        if ($userCategoriesCount == 0) {
            $defaultCategories = [
                [
                    'name' => 'Treening',
                    'color' => '#10B981',
                    'icon' => '🏃',
                    'template' => 'Treening "{title}" algab {time_until} pärast!'
                ],
                [
                    'name' => 'Võistlus',
                    'color' => '#F59E0B',
                    'icon' => '🏆',
                    'template' => 'Võistlus "{title}" algab {time_until} pärast! Sa oled valmis!'
                ]
            ];

            $stmt = $pdo->prepare("
                INSERT INTO event_categories (
                    user_id, name, color, icon, default_reminder_minutes, 
                    reminder_enabled, custom_message_template, is_system, 
                    is_active, created_at, updated_at
                ) VALUES (?, ?, ?, ?, 60, 1, ?, 0, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
            ");

            foreach ($defaultCategories as $category) {
                $stmt->execute([
                    $current_user_id,
                    $category['name'],
                    $category['color'],
                    $category['icon'],
                    $category['template']
                ]);
            }
        }

        return true;
    } catch (PDOException $e) {
        error_log('Calendar tables creation error: ' . $e->getMessage());
        return false;
    }
}

// ====================
// KATEGOORIATE LAADIMINE
// ====================
function getCategories($pdo, $user_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                id, user_id, name, color, icon, 
                default_reminder_minutes, reminder_enabled, 
                custom_message_template, is_system, is_active,
                (SELECT COUNT(*) FROM events WHERE category_id = ec.id AND user_id = ?) as event_count
            FROM event_categories ec
            WHERE user_id = ? AND is_active = 1
            ORDER BY name ASC
        ");
        $stmt->execute([$user_id, $user_id]);
        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($categories as &$category) {
            $category['can_edit'] = true;
            $category['can_delete'] = true;
        }
        
        return $categories;
    } catch (PDOException $e) {
        error_log('Categories load error: ' . $e->getMessage());
        return [];
    }
}

// ====================
// SÜNDMUSTE LAADIMINE
// ====================
function getEvents($pdo, $user_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                e.id,
                e.title,
                e.description,
                e.start_datetime,
                e.end_datetime,
                e.all_day,
                e.location,
                e.category_id,
                e.created_at,
                e.updated_at,
                COALESCE(c.name, 'Kategooriata') as category_name,
                COALESCE(c.color, '#4285F4') as category_color,
                COALESCE(c.icon, '📅') as category_icon
            FROM events e 
            LEFT JOIN event_categories c ON e.category_id = c.id 
            WHERE e.user_id = ?
            ORDER BY e.start_datetime ASC
        ");
        $stmt->execute([$user_id]);
        $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return $events;
    } catch (PDOException $e) {
        error_log('Events load error: ' . $e->getMessage());
        return [];
    }
}

// Loo tabelid kui puuduvad
ensureCalendarTables($pdo);

// Lae andmed
$categories = getCategories($pdo, $current_user_id);
$events = getEvents($pdo, $current_user_id);

// Include header
include 'includes/header.php';
?>

<!-- KALENDER -->
<div class="calendar-wrapper">
    <div class="calendar-container">
        <!-- Header -->
        <div class="calendar-header">
            <div class="header-left">
                <h1>
                    <span>📅</span>
                    Minu kalender
                </h1>
                <p style="margin: 0; color: var(--gray-600);">
                    Tere, <?php echo htmlspecialchars($user_name); ?>!
                    <?php if ($debug_mode): ?>
                        <span style="background: #ff0; color: #000; padding: 2px 6px; border-radius: 4px; font-size: 12px;">DEBUG MODE</span>
                    <?php endif; ?>
                </p>
            </div>
            
            <div class="header-actions">
                <div style="display: flex; gap: 2px; background: var(--gray-100); padding: 2px; border-radius: var(--radius-lg);">
                    <button class="btn btn-outline active" onclick="safeChangeView('month')">Kuu</button>
                    <button class="btn btn-outline" onclick="safeChangeView('week')">Nädal</button>
                    <button class="btn btn-outline" onclick="safeChangeView('day')">Päev</button>
                </div>
                <button class="btn btn-primary" onclick="safeOpenEventWizard()">
                    + Lisa sündmus
                </button>
            </div>
        </div>

        <!-- Content -->
        <div class="calendar-content">
            <!-- Sidebar -->
            <div class="calendar-sidebar">
                <!-- Täna -->
                <div class="sidebar-card">
                    <h3>Täna (<?php echo date('d.m.Y'); ?>)</h3>
                    <div id="today-events">
                        <p style="color: var(--gray-600); font-size: var(--font-size-sm);">Laadin...</p>
                    </div>
                </div>

                <!-- Kategooriad -->
                <div class="sidebar-card">
                    <h3>Kategooriad</h3>
                    <div id="category-list">
                        <?php foreach ($categories as $category): ?>
                        <div class="category-item" data-category-id="<?php echo $category['id']; ?>">
                            <div class="category-color" style="background-color: <?php echo htmlspecialchars($category['color']); ?>"></div>
                            <span style="font-size: var(--font-size-sm);"><?php echo htmlspecialchars($category['icon']); ?></span>
                            <span class="category-name"><?php echo htmlspecialchars($category['name']); ?></span>
                            <span class="category-count"><?php echo $category['event_count']; ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <button class="btn btn-secondary" onclick="safeOpenCategoryManager()" style="margin-top: var(--space-4); width: 100%;">
                        Halda kategooriaid
                    </button>
                </div>

                <!-- Statistika -->
                <div class="sidebar-card">
                    <h3>Statistika</h3>
                    <p style="margin: 0; font-size: var(--font-size-sm); color: var(--gray-600);">
                        Sündmusi kokku: <strong id="total-events"><?php echo count($events); ?></strong><br>
                        Kategooriaid: <strong><?php echo count($categories); ?></strong><br>
                        <?php if ($debug_mode): ?>
                        <br><strong>Debug info:</strong><br>
                        API URL: <code><?php echo BASE_URL; ?>/calendar/api/</code><br>
                        User ID: <?php echo $current_user_id; ?><br>
                        JS Status: <span id="js-status" style="color: #f44336;">Loading...</span>
                        <?php endif; ?>
                    </p>
                </div>
            </div>

            <!-- Calendar Main -->
            <div class="calendar-main">
                <!-- Nav -->
                <div class="calendar-nav">
                    <div>
                        <button class="nav-btn" onclick="safePreviousMonth()">Eelmine</button>
                        <button class="nav-btn" onclick="safeGoToToday()">Täna</button>
                        <button class="nav-btn" onclick="safeNextMonth()">Järgmine</button>
                    </div>
                    <h2 class="calendar-title" id="calendar-title">Laadin...</h2>
                </div>
                
                <!-- Grid -->
                <div class="calendar-grid" id="calendar-grid">
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: var(--gray-600);">
                        Kalender laadib...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Event Wizard Modal - PARANDATUD CUSTOM REMINDER FIELD -->
<div class="modal-overlay" id="eventWizardModal" style="display: none;">
    <div class="modal-content wizard-modal">
        <!-- Wizard Header -->
        <div class="modal-header">
            <h3 class="modal-title">Lisa uus sündmus</h3>
            <button class="modal-close" onclick="safeCloseEventWizard()">×</button>
        </div>
        
        <!-- Wizard Progress -->
        <div class="wizard-progress">
            <div class="progress-step active" id="progress-step-1">
                <div class="step-number">1</div>
                <div class="step-label">Sündmus</div>
            </div>
            <div class="progress-step" id="progress-step-2">
                <div class="step-number">2</div>
                <div class="step-label">Aeg</div>
            </div>
            <div class="progress-step" id="progress-step-3">
                <div class="step-number">3</div>
                <div class="step-label">Meeldetuletus</div>
            </div>
        </div>
        
        <!-- Wizard Content -->
        <form id="event-wizard-form" onsubmit="safeSaveEventFromWizard(event)">
            <input type="hidden" id="wizard-event-id" name="event_id">
            
            <!-- Step 1: Sündmuse andmed -->
            <div class="wizard-step active" id="wizard-step-1">
                <div class="wizard-step-content">
                    <h4>Mis sündmus on?</h4>
                    <p>Sisesta sündmuse nimi ja täiendav info</p>
                    
                    <div class="form-group">
                        <label class="form-label" for="wizard-title">Sündmuse nimi</label>
                        <input type="text" id="wizard-title" name="title" class="form-control" required placeholder="nt. Treening, Koosolek, Võistlus" autofocus>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="wizard-description">Kirjeldus (valikuline)</label>
                        <textarea id="wizard-description" name="description" class="form-control" rows="2" placeholder="Täiendav info sündmuse kohta..."></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="wizard-location">Asukoht (valikuline)</label>
                        <input type="text" id="wizard-location" name="location" class="form-control" placeholder="Kus toimub?">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label" for="wizard-category">Kategooria (valikuline)</label>
                        <select id="wizard-category" name="category" class="form-control">
                            <option value="">Vali kategooria</option>
                            <?php foreach ($categories as $category): ?>
                            <option value="<?php echo $category['id']; ?>">
                                <?php echo htmlspecialchars($category['icon'] . ' ' . $category['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="wizard-actions">
                    <button type="button" class="btn btn-secondary" onclick="safeCloseEventWizard()">Tühista</button>
                    <button type="button" class="btn btn-danger" onclick="safeDeleteEventFromWizard()" id="wizard-delete-btn-step1" style="display: none;">🗑️ Kustuta sündmus</button>
                    <button type="button" class="btn btn-primary" onclick="wizardNextStep()">Järgmine</button>
                </div>
            </div>
            
            <!-- Step 2: Aeg -->
            <div class="wizard-step" id="wizard-step-2">
                <div class="wizard-step-content">
                    <h4>Millal toimub?</h4>
                    <p>Vali sündmuse algus- ja lõpuaeg</p>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <label class="form-label" for="wizard-start">Algusaeg</label>
                            <input type="datetime-local" id="wizard-start" name="start" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="wizard-end">Lõpuaeg (valikuline)</label>
                            <input type="datetime-local" id="wizard-end" name="end" class="form-control">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                            <input type="checkbox" id="wizard-all-day" name="all_day" style="transform: scale(1.2);">
                            Kogu päeva sündmus
                        </label>
                    </div>
                    
                    <!-- Kiired ajavalikud -->
                    <div class="quick-time-options">
                        <p style="margin-bottom: 8px; font-weight: 500;">Kiired valikud:</p>
                        <div class="quick-time-buttons">
                            <button type="button" class="btn btn-outline btn-sm" onclick="setQuickTime('today-morning')">Täna hommik</button>
                            <button type="button" class="btn btn-outline btn-sm" onclick="setQuickTime('today-afternoon')">Täna pärastlõuna</button>
                            <button type="button" class="btn btn-outline btn-sm" onclick="setQuickTime('today-evening')">Täna õhtu</button>
                            <button type="button" class="btn btn-outline btn-sm" onclick="setQuickTime('tomorrow-morning')">Homme hommik</button>
                            <button type="button" class="btn btn-outline btn-sm" onclick="setQuickTime('next-week')">Järgmine nädal</button>
                        </div>
                    </div>
                </div>
                
                <div class="wizard-actions">
                    <button type="button" class="btn btn-secondary" onclick="wizardPrevStep()">Tagasi</button>
                    <button type="button" class="btn btn-secondary" onclick="wizardSkipReminder()">Lõpeta ilma meeldetuletuseta</button>
                    <button type="button" class="btn btn-primary" onclick="wizardNextStep()">Lisa meeldetuletus</button>
                </div>
            </div>
            
            <!-- Step 3: Meeldetuletus - PARANDATUD! -->
            <div class="wizard-step" id="wizard-step-3">
                <div class="wizard-step-content">
                    <h4>Kas soovid meeldetuletust?</h4>
                    <p>Vali, millal sulle meeldetuletus saata</p>
                    
                    <div class="reminder-options">
                        <div class="reminder-option" onclick="selectReminderOption('60')">
                            <input type="radio" name="reminder_option" value="60" id="reminder-60">
                            <label for="reminder-60">
                                <div class="option-title">1 tund enne</div>
                                <div class="option-description">Saad meeldetuletuse 1 tund enne sündmust</div>
                            </label>
                        </div>
                        
                        <div class="reminder-option" onclick="selectReminderOption('120')">
                            <input type="radio" name="reminder_option" value="120" id="reminder-120">
                            <label for="reminder-120">
                                <div class="option-title">2 tundi enne</div>
                                <div class="option-description">Saad meeldetuletuse 2 tundi enne sündmust</div>
                            </label>
                        </div>
                        
                        <div class="reminder-option" onclick="selectReminderOption('1440')">
                            <input type="radio" name="reminder_option" value="1440" id="reminder-1440">
                            <label for="reminder-1440">
                                <div class="option-title">1 päev enne</div>
                                <div class="option-description">Saad meeldetuletuse 1 päev enne sündmust</div>
                            </label>
                        </div>
                        
                        <div class="reminder-option" onclick="selectReminderOption('custom')">
                            <input type="radio" name="reminder_option" value="custom" id="reminder-custom">
                            <label for="reminder-custom">
                                <div class="option-title">Täpne kellaaeg</div>
                                <div class="option-description">Vali täpne aeg millal meeldetuletus saata</div>
                            </label>
                        </div>
                        
                        <div class="reminder-option" onclick="selectReminderOption('none')">
                            <input type="radio" name="reminder_option" value="none" id="reminder-none">
                            <label for="reminder-none">
                                <div class="option-title">Ei soovi meeldetuletust</div>
                                <div class="option-description">Sündmus lisatakse ilma meeldetuletuseta</div>
                            </label>
                        </div>
                    </div>
                    
                    <!-- PARANDATUD: Täpse kellaaja valik -->
                    <div id="custom-reminder-time" style="display: none; margin-top: 16px;">
                        <div class="form-group">
                            <label class="form-label" for="wizard-reminder-datetime">
                                🎯 Täpne meeldetuletuse kellaaeg
                            </label>
                            <input type="datetime-local" id="wizard-reminder-datetime" name="reminder_datetime" class="form-control">
                            <small style="color: var(--gray-600); font-size: 12px;">
                                ⚠️ Vali täpne kuupäev ja kellaaeg, millal soovid meeldetuletust saada
                            </small>
                        </div>
                    </div>
                    
                    <!-- Meeldetuletuse tekst -->
                    <div id="reminder-message-section" style="display: none; margin-top: 16px;">
                        <div class="form-group">
                            <label class="form-label" for="wizard-reminder-message">Meeldetuletuse tekst (valikuline)</label>
                            <input type="text" id="wizard-reminder-message" name="reminder_message" class="form-control" placeholder="Kohandatud meeldetuletuse tekst...">
                            <small style="color: var(--gray-600);">Kui jätad tühjaks, kasutame automaatset teksti</small>
                        </div>
                    </div>
                </div>
                
                <div class="wizard-actions">
                    <button type="button" class="btn btn-secondary" onclick="wizardPrevStep()">Tagasi</button>
                    <button type="button" class="btn btn-danger" onclick="safeDeleteEventFromWizard()" id="wizard-delete-btn" style="display: none;">Kustuta sündmus</button>
                    <button type="submit" class="btn btn-primary">Salvesta sündmus</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Olemasolev Event Modal (muutmiseks) -->
<div class="modal-overlay" id="eventModal">
    <div class="modal-content" style="max-width: 700px;">
        <div class="modal-header">
            <h3 class="modal-title" id="modal-title">Muuda sündmust</h3>
            <button class="modal-close" onclick="safeCloseEventModal()">×</button>
        </div>
        
        <form id="event-form" onsubmit="safeSaveEvent(event)">
            <input type="hidden" id="event-id" name="event_id">
            <div class="modal-body">
                
                <!-- Sündmuse põhiandmed -->
                <div class="form-section">
                    <h4 style="margin: 0 0 16px 0; color: var(--gray-800); font-size: 18px;">Sündmuse andmed</h4>
                    
                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label class="form-label" for="event-title">Sündmuse nimi</label>
                            <input type="text" id="event-title" name="title" class="form-control" required placeholder="Sisesta sündmuse nimi">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="event-start">Algusaeg</label>
                            <input type="datetime-local" id="event-start" name="start" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="event-end">Lõpuaeg</label>
                            <input type="datetime-local" id="event-end" name="end" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="event-category">Kategooria</label>
                            <select id="event-category" name="category" class="form-control">
                                <option value="">Vali kategooria</option>
                                <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>">
                                    <?php echo htmlspecialchars($category['icon'] . ' ' . $category['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label" for="event-location">Asukoht</label>
                            <input type="text" id="event-location" name="location" class="form-control" placeholder="Kus toimub?">
                        </div>
                        
                        <div class="form-group full-width">
                            <label class="form-label" for="event-description">Kirjeldus</label>
                            <textarea id="event-description" name="description" class="form-control" rows="3" placeholder="Täiendav info..."></textarea>
                        </div>
                    </div>
                </div>

                <!-- Meeldetuletuste sektsiooni -->
                <div class="form-section" style="border-top: 1px solid var(--gray-200); padding-top: 24px; margin-top: 24px;">
                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
                        <h4 style="margin: 0; color: var(--gray-800); font-size: 18px;">Meeldetuletused</h4>
                        <button type="button" class="btn btn-primary btn-sm" onclick="safeAddReminder()">
                            Lisa meeldetuletus
                        </button>
                    </div>
                    
                    <!-- Meeldetuletuste loend -->
                    <div id="reminders-list" style="margin-bottom: 16px;">
                        <div class="empty-reminders">
                            <div style="font-size: 32px; margin-bottom: 8px;">🔔</div>
                            <div>Meeldetuletusi pole veel lisatud</div>
                            <small style="color: var(--gray-500);">Lisa meeldetuletus üleval oleva nupuga</small>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="safeCloseEventModal()">Tühista</button>
                <button type="button" class="btn btn-outline" onclick="openWizardForEdit()" style="margin-right: auto;">🪄 Ava wizard</button>
                <button type="button" class="btn btn-danger" onclick="safeDeleteEvent()" id="delete-btn" style="display: none;">
                    Kustuta
                </button>
                <button type="submit" class="btn btn-primary">Salvesta</button>
            </div>
        </form>
    </div>
</div>

<!-- Detailne meeldetuletuse modal -->
<div class="modal-overlay" id="reminderModal" style="display: none;">
    <div class="modal-content" style="max-width: 500px;">
        <div class="modal-header">
            <h3 class="modal-title" id="reminder-modal-title">Lisa meeldetuletus</h3>
            <button class="modal-close" onclick="safeCloseReminderModal()">×</button>
        </div>
        
        <form id="reminder-form" onsubmit="safeSaveReminder(event)">
            <input type="hidden" id="reminder-id" name="reminder_id">
            <input type="hidden" id="reminder-event-id" name="event_id">
            
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label" for="reminder-message">Meeldetuletuse tekst</label>
                    <textarea id="reminder-message" name="custom_message" class="form-control" rows="3" required placeholder="Kirjuta oma meeldetuletuse tekst..."></textarea>
                    <small style="color: var(--gray-600); font-size: 12px;">Näiteks: "Kobi trenni laiskvorst"</small>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Millal meeldetuletus saata?</label>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
                        <div>
                            <label style="font-size: 12px; color: var(--gray-600);">Mitu minutit enne sündmust</label>
                            <select id="reminder-minutes" name="minutes_before" class="form-control">
                                <option value="5">5 minutit</option>
                                <option value="15">15 minutit</option>
                                <option value="30">30 minutit</option>
                                <option value="60" selected>1 tund</option>
                                <option value="120">2 tundi</option>
                                <option value="360">6 tundi</option>
                                <option value="720">12 tundi</option>
                                <option value="1440">1 päev</option>
                                <option value="2880">2 päeva</option>
                                <option value="10080">1 nädal</option>
                            </select>
                        </div>
                        <div>
                            <label style="font-size: 12px; color: var(--gray-600);">VÕI täpne kellaaeg</label>
                            <input type="datetime-local" id="reminder-exact-time" name="exact_time" class="form-control">
                        </div>
                    </div>
                    <small style="color: var(--gray-600); font-size: 12px;">Vali kas enne-aeg või täpne kellaaeg</small>
                </div>
                
                <div class="form-group">
                    <div style="background: var(--gray-50); padding: 16px; border-radius: 8px;">
                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 500;">
                            <input type="checkbox" id="reminder-recurring" name="is_recurring" style="transform: scale(1.2);">
                            Korduv meeldetuletus
                        </label>
                        
                        <!-- Korduvuse seaded -->
                        <div id="recurring-settings" style="display: none; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--gray-200);">
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 12px;">
                                <div>
                                    <label style="font-size: 12px; color: var(--gray-600);">Korduvuse tüüp</label>
                                    <select id="recurring-type" name="recurring_type" class="form-control">
                                        <option value="daily">Iga päev</option>
                                        <option value="weekly">Iga nädal</option>
                                        <option value="monthly">Iga kuu</option>
                                    </select>
                                </div>
                                <div>
                                    <label style="font-size: 12px; color: var(--gray-600);">Intervalь</label>
                                    <select id="recurring-interval" name="recurring_interval" class="form-control">
                                        <option value="1">Iga 1</option>
                                        <option value="2">Iga 2</option>
                                        <option value="3">Iga 3</option>
                                        <option value="4">Iga 4</option>
                                        <option value="5">Iga 5</option>
                                    </select>
                                </div>
                            </div>
                            <div>
                                <label style="font-size: 12px; color: var(--gray-600);">Korduvuse lõpp (valikuline)</label>
                                <input type="date" id="recurring-end" name="recurring_end_date" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="safeCloseReminderModal()">Tühista</button>
                <button type="button" class="btn btn-danger" onclick="safeDeleteReminder()" id="delete-reminder-btn" style="display: none;">
                    Kustuta
                </button>
                <button type="submit" class="btn btn-primary">Salvesta meeldetuletus</button>
            </div>
        </form>
    </div>
</div>

<!-- Category Manager Modal -->
<div class="modal-overlay" id="categoryManagerModal" style="display: none;">
    <div class="modal-content" style="max-width: 800px;">
        <div class="modal-header">
            <h3 class="modal-title">Kategooriate haldus</h3>
            <button class="modal-close" onclick="safeCloseCategoryManager()">×</button>
        </div>
        <div class="modal-body">
            <div id="category-manager-inner">
                <div style="text-align: center; padding: 40px;">
                    <h3>Kategooriahaldus laadib...</h3>
                    <p>Palun oodake, kategooriahalduse moodul laadib...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Debug info -->
<?php if ($debug_mode): ?>
<div class="debug-info">
    <div>DEBUG INFO</div>
    <div>Events: <?php echo count($events); ?></div>
    <div>Categories: <?php echo count($categories); ?></div>
    <div>User: <?php echo $current_user_id; ?></div>
    <div>API: <?php echo BASE_URL; ?>/calendar/api/</div>
    <div>JS: <span id="debug-js-status">Loading</span></div>
    <div>Process: <span id="debug-process-status">Waiting</span></div>
</div>
<?php endif; ?>

<!-- Include CSS -->
<link rel="stylesheet" href="<?php echo BASE_URL; ?>/calendar/css/calendar.css">

<!-- GLOBAALSED ANDMED JAVASCRIPT JAOKS -->
<script>
window.calendarConfig = {
    apiBaseUrl: '<?php echo BASE_URL; ?>/calendar/api/',
    debugMode: <?php echo $debug_mode ? 'true' : 'false'; ?>,
    currentUserId: <?php echo $current_user_id; ?>,
    baseUrl: '<?php echo BASE_URL; ?>'
};

window.calendarData = {
    categories: <?php echo json_encode($categories); ?>,
    events: <?php echo json_encode($events); ?>
};

function updateDebugStatus(component, status, message = '') {
    if (!window.calendarConfig.debugMode) return;
    
    const element = document.getElementById('debug-' + component + '-status');
    if (element) {
        element.innerHTML = status + (message ? ' ' + message : '');
    }
}

let jsLoadStatus = {
    core: false,
    reminders: false,
    categories: false
};

function checkAllJSLoaded() {
    const allLoaded = Object.values(jsLoadStatus).every(status => status);
    
    if (allLoaded) {
        updateDebugStatus('js', 'Loaded');
        
        const jsStatus = document.getElementById('js-status');
        if (jsStatus) jsStatus.innerHTML = 'Ready';
        
        console.log('All calendar JavaScript modules loaded successfully!');
        
        if (typeof initCalendarSafely === 'function') {
            initCalendarSafely();
        }
    } else {
        updateDebugStatus('js', 'Loading...');
        console.log('Still loading JS modules:', jsLoadStatus);
    }
}

window.addEventListener('error', function(e) {
    if (e.filename && e.filename.includes('calendar')) {
        console.error('Calendar JavaScript error:', e);
        updateDebugStatus('js', 'Error: ' + e.message);
        
        const jsStatus = document.getElementById('js-status');
        if (jsStatus) jsStatus.innerHTML = 'Error';
    }
});
</script>

<!-- TURVALINE JAVASCRIPT INIT -->
<script>
function safeGetElement(id) {
    try {
        const element = document.getElementById(id);
        if (!element) {
            console.warn('Element not found: ' + id);
            return null;
        }
        return element;
    } catch (error) {
        console.warn('Error getting element ' + id + ':', error);
        return null;
    }
}

function safeCalendarInit() {
    const calendarGrid = safeGetElement('calendar-grid');
    if (!calendarGrid) {
        console.log('Calendar grid not found - skipping calendar initialization');
        return false;
    }
    
    console.log('Calendar container found - proceeding with initialization');
    return true;
}

// UUED WIZARD FUNKTSIOONID
function safeOpenEventWizard(date = null) {
    try {
        if (typeof window.openEventWizard === 'function') {
            window.openEventWizard(date);
        } else {
            const modal = safeGetElement('eventWizardModal');
            if (modal) {
                modal.style.display = 'flex';
                console.warn('Using fallback wizard opening');
            }
        }
    } catch (error) {
        console.error('Error in safeOpenEventWizard:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga sündmuse wizardi avamisel', 'error');
        }
    }
}

function safeCloseEventWizard() {
    try {
        if (typeof window.closeEventWizard === 'function') {
            window.closeEventWizard();
        } else {
            const modal = safeGetElement('eventWizardModal');
            if (modal) {
                modal.style.display = 'none';
            }
        }
    } catch (error) {
        console.error('Error in safeCloseEventWizard:', error);
    }
}

function safeSaveEventFromWizard(event) {
    try {
        if (typeof window.saveEventFromWizard === 'function') {
            window.saveEventFromWizard(event);
        } else {
            console.error('saveEventFromWizard function not found');
            event.preventDefault();
            if (typeof window.showNotification === 'function') {
                window.showNotification('Sündmuse salvestamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeSaveEventFromWizard:', error);
        event.preventDefault();
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga sündmuse salvestamisel', 'error');
        }
    }
}

// UUENDATUD WIZARD KUSTUTAMISE FUNKTSIOON
function safeDeleteEventFromWizard() {
    try {
        if (typeof window.deleteEventFromWizard === 'function') {
            window.deleteEventFromWizard();
        } else {
            console.error('deleteEventFromWizard function not found');
            if (typeof window.showNotification === 'function') {
                window.showNotification('Sündmuse kustutamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeDeleteEventFromWizard:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga sündmuse kustutamisel', 'error');
        }
    }
}

// OLEMASOLEVAD FUNKTSIOONID
function safeOpenAddEventModal(date = null) {
    try {
        const modal = safeGetElement('eventModal');
        if (!modal) {
            console.error('Event modal not available');
            return false;
        }
        
        if (typeof window.openAddEventModal === 'function') {
            window.openAddEventModal(date);
        } else if (typeof window.openEventModal === 'function') {
            window.openEventModal(null);
        } else {
            modal.style.display = 'flex';
            console.warn('Using fallback modal opening');
        }
    } catch (error) {
        console.error('Error in safeOpenAddEventModal:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga sündmuse modali avamisel', 'error');
        }
    }
}

function safeCloseEventModal() {
    try {
        const modal = safeGetElement('eventModal');
        if (modal) {
            modal.style.display = 'none';
        }
        
        if (typeof window.closeEventModal === 'function') {
            window.closeEventModal();
        }
    } catch (error) {
        console.error('Error in safeCloseEventModal:', error);
    }
}

function safeSaveEvent(event) {
    try {
        if (typeof window.saveEvent === 'function') {
            window.saveEvent(event);
        } else {
            console.error('saveEvent function not found');
            event.preventDefault();
            if (typeof window.showNotification === 'function') {
                window.showNotification('Sündmuse salvestamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeSaveEvent:', error);
        event.preventDefault();
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga sündmuse salvestamisel', 'error');
        }
    }
}

function safeDeleteEvent() {
    try {
        if (typeof window.deleteEvent === 'function') {
            window.deleteEvent();
        } else {
            console.error('deleteEvent function not found');
            if (typeof window.showNotification === 'function') {
                window.showNotification('Sündmuse kustutamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeDeleteEvent:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga sündmuse kustutamisel', 'error');
        }
    }
}

function safeAddReminder() {
    try {
        if (typeof window.addReminder === 'function') {
            window.addReminder();
        } else {
            console.error('addReminder function not found');
            if (typeof window.showNotification === 'function') {
                window.showNotification('Meeldetuletuse lisamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeAddReminder:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga meeldetuletuse lisamisel', 'error');
        }
    }
}

function safeCloseReminderModal() {
    try {
        if (typeof window.closeReminderModal === 'function') {
            window.closeReminderModal();
        } else {
            const modal = safeGetElement('reminderModal');
            if (modal) {
                modal.style.display = 'none';
            }
        }
    } catch (error) {
        console.error('Error in safeCloseReminderModal:', error);
    }
}

function safeSaveReminder(event) {
    try {
        if (typeof window.saveReminder === 'function') {
            window.saveReminder(event);
        } else {
            console.error('saveReminder function not found');
            event.preventDefault();
            if (typeof window.showNotification === 'function') {
                window.showNotification('Meeldetuletuse salvestamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeSaveReminder:', error);
        event.preventDefault();
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga meeldetuletuse salvestamisel', 'error');
        }
    }
}

function safeDeleteReminder() {
    try {
        if (typeof window.deleteReminder === 'function') {
            window.deleteReminder();
        } else {
            console.error('deleteReminder function not found');
            if (typeof window.showNotification === 'function') {
                window.showNotification('Meeldetuletuse kustutamise funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeDeleteReminder:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga meeldetuletuse kustutamisel', 'error');
        }
    }
}

function safeOpenCategoryManager() {
    try {
        if (typeof window.openCategoryManager === 'function') {
            window.openCategoryManager();
        } else {
            console.error('openCategoryManager function not found');
            if (typeof window.showNotification === 'function') {
                window.showNotification('Kategooriahalduse funktsioon ei ole saadaval', 'error');
            }
        }
    } catch (error) {
        console.error('Error in safeOpenCategoryManager:', error);
        if (typeof window.showNotification === 'function') {
            window.showNotification('Viga kategooriahalduse avamisel', 'error');
        }
    }
}

function safeCloseCategoryManager() {
    try {
        if (typeof window.closeCategoryManager === 'function') {
            window.closeCategoryManager();
        } else {
            const modal = safeGetElement('categoryManagerModal');
            if (modal) {
                modal.style.display = 'none';
            }
        }
    } catch (error) {
        console.error('Error in safeCloseCategoryManager:', error);
    }
}

function safePreviousMonth() {
    try {
        if (typeof window.previousMonth === 'function') {
            window.previousMonth();
        } else {
            console.error('previousMonth function not found');
        }
    } catch (error) {
        console.error('Error in safePreviousMonth:', error);
    }
}

function safeNextMonth() {
    try {
        if (typeof window.nextMonth === 'function') {
            window.nextMonth();
        } else {
            console.error('nextMonth function not found');
        }
    } catch (error) {
        console.error('Error in safeNextMonth:', error);
    }
}

function safeGoToToday() {
    try {
        if (typeof window.goToToday === 'function') {
            window.goToToday();
        } else {
            console.error('goToToday function not found');
        }
    } catch (error) {
        console.error('Error in safeGoToToday:', error);
    }
}

function safeChangeView(view) {
    try {
        if (typeof window.changeView === 'function') {
            window.changeView(view);
        } else {
            console.error('changeView function not found');
        }
    } catch (error) {
        console.error('Error in safeChangeView:', error);
    }
}

function waitForDOM(callback) {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', callback);
    } else {
        callback();
    }
}

function initCalendarSafely() {
    waitForDOM(function() {
        setTimeout(function() {
            console.log('Starting safe calendar initialization...');
            
            if (safeCalendarInit()) {
                console.log('Calendar initialization ready');
            }
        }, 100);
    });
}

console.log('Calendar safe initialization script ready!');
</script>

<!-- AUTOMAATNE MEELDETULETUSTE KONTROLL -->
<script>
console.log('Käivitan automaatse meeldetuletuste kontrollimise...');

function checkReminders() {
    const url = '<?php echo BASE_URL; ?>/calendar/process_reminders.php?action=process&web=1&cron=1';
    
    console.log('Kontrollin meeldetuletusi:', url);
    updateDebugStatus('process', 'Checking...');
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status + ': ' + response.statusText);
            }
            return response.text();
        })
        .then(data => {
            console.log('Meeldetuletuste kontroll lõpetatud:', data.substring(0, 100) + '...');
            updateDebugStatus('process', 'OK');
            
            const sentMatch = data.match(/sent_successfully['":\s]*(\d+)/);
            if (sentMatch) {
                updateDebugStatus('process', 'Sent: ' + sentMatch[1]);
            }
            
            if (<?php echo $debug_mode ? 'true' : 'false'; ?>) {
                let debugDiv = document.getElementById('reminder-debug');
                if (!debugDiv) {
                    debugDiv = document.createElement('div');
                    debugDiv.id = 'reminder-debug';
                    debugDiv.style.cssText = 'position:fixed;bottom:60px;right:10px;background:#2a2a2a;color:#fff;padding:10px;border-radius:5px;font-family:monospace;font-size:12px;max-width:300px;z-index:9999;border:1px solid #4CAF50;';
                    document.body.appendChild(debugDiv);
                }
                debugDiv.innerHTML = 'Meeldetuletuste kontroll<br>' + new Date().toLocaleTimeString() + '<br>Status: OK<br>Vastus: ' + data.substring(0, 50) + '...';
            }
        })
        .catch(error => {
            console.error('Meeldetuletuste kontroll ebaõnnestus:', error);
            updateDebugStatus('process', 'Error');
            
            if (<?php echo $debug_mode ? 'true' : 'false'; ?>) {
                let debugDiv = document.getElementById('reminder-debug');
                if (!debugDiv) {
                    debugDiv = document.createElement('div');
                    debugDiv.id = 'reminder-debug';
                    debugDiv.style.cssText = 'position:fixed;bottom:60px;right:10px;background:#4a1a1a;color:#fff;padding:10px;border-radius:5px;font-family:monospace;font-size:12px;max-width:300px;z-index:9999;border:1px solid #f44336;';
                    document.body.appendChild(debugDiv);
                }
                debugDiv.innerHTML = 'Meeldetuletuste viga<br>' + new Date().toLocaleTimeString() + '<br>ERROR: ' + error.message + '<br>Kontrolli process_reminders.php';
            }
        });
}

setTimeout(checkReminders, 5000);
const reminderInterval = setInterval(checkReminders, 120000);

console.log('Automaatne meeldetuletuste kontroll seadistatud (iga 2 minutit)');

window.addEventListener('beforeunload', function() {
    if (reminderInterval) {
        clearInterval(reminderInterval);
        console.log('Meeldetuletuste timer peatatud');
    }
});

window.manualReminderCheck = function() {
    console.log('Manuaalne meeldetuletuste kontroll...');
    checkReminders();
};

<?php if ($debug_mode): ?>
document.addEventListener('DOMContentLoaded', function() {
    const debugButton = document.createElement('button');
    debugButton.innerHTML = 'Test Meeldetuletusi';
    debugButton.style.cssText = 'position:fixed;top:10px;right:10px;background:#4CAF50;color:white;border:none;padding:10px;border-radius:5px;cursor:pointer;z-index:9999;font-weight:bold;';
    debugButton.onclick = window.manualReminderCheck;
    document.body.appendChild(debugButton);
    
    console.log('DEBUG: Lisasin manuaalse test nupu (paremas ülanurgas)');
});
<?php endif; ?>
</script>

<!-- JAVASCRIPT FAILIDE LAADIMINE -->
<script src="<?php echo BASE_URL; ?>/calendar/js/calendar-core.js" defer onload="jsLoadStatus.core = true; checkAllJSLoaded();" onerror="console.error('Failed to load calendar-core.js'); updateDebugStatus('js', 'Core failed');"></script>
<script src="<?php echo BASE_URL; ?>/calendar/js/reminders.js" defer onload="jsLoadStatus.reminders = true; checkAllJSLoaded();" onerror="console.error('Failed to load reminders.js'); updateDebugStatus('js', 'Reminders failed');"></script>
<script src="<?php echo BASE_URL; ?>/calendar/js/categories.js" defer onload="jsLoadStatus.categories = true; checkAllJSLoaded();" onerror="console.error('Failed to load categories.js'); updateDebugStatus('js', 'Categories failed');"></script>

<script>
console.log('Loading calendar JavaScript modules...');

setTimeout(function() {
    const allLoaded = Object.values(jsLoadStatus).every(status => status);
    if (!allLoaded) {
        console.error('Some JavaScript modules failed to load:', jsLoadStatus);
        updateDebugStatus('js', 'Some modules failed');
        
        const jsStatus = document.getElementById('js-status');
        if (jsStatus) jsStatus.innerHTML = 'Failed';
        
        if (typeof window.showNotification === 'function') {
            window.showNotification('Mõned kalendri funktsioonid ei pruugi töötada. Palun värskenda lehte.', 'warning');
        }
    }
}, 10000);
</script>

<?php if ($debug_mode): ?>
<div style="position: fixed; bottom: 10px; left: 10px; background: #2a2a2a; color: #fff; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 12px; z-index: 9999; border: 1px solid #2196F3;">
    CALENDAR DEBUG<br>
    API: <?php echo BASE_URL; ?>/calendar/<br>
    User: <?php echo $current_user_id; ?><br>
    <?php echo date('H:i:s'); ?><br>
    Auto reminders: ON<br>
    JS: <span id="debug-js-mini">Loading...</span>
</div>

<script>
function updateMiniDebug() {
    const element = document.getElementById('debug-js-mini');
    if (element) {
        const allLoaded = Object.values(jsLoadStatus).every(status => status);
        element.innerHTML = allLoaded ? 'Ready' : 'Loading';
    }
}

let updateCounter = 0;
const miniDebugInterval = setInterval(function() {
    updateMiniDebug();
    updateCounter++;
    if (updateCounter > 30) {
        clearInterval(miniDebugInterval);
    }
}, 1000);
</script>
<?php endif; ?>

<?php include 'includes/footer.php'; ?>