<?php

require_once __DIR__ . '/../config/db.php';

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.\n");
}

echo "Starting migration...\n";

// 1. Migrate CDN Links
$cdnJson = file_get_contents('/var/www/oldsite/cdn.json');
$cdnData = json_decode($cdnJson, true);

if ($cdnData) {
    echo "Migrating CDN links...\n";
    $stmt = $db->prepare("INSERT INTO cdn_links (name, url) VALUES (:name, :url)");
    foreach ($cdnData as $cdn) {
        // Check if exists
        $check = $db->prepare("SELECT id FROM cdn_links WHERE name = :name");
        $check->execute([':name' => $cdn['name']]);
        if ($check->rowCount() == 0) {
            $stmt->execute([':name' => $cdn['name'], ':url' => $cdn['server']]); // Using 'server' as url based on json
        }
    }
    echo "CDN links migrated.\n";
}

// 2. Migrate Schedule
$scheduleJson = file_get_contents('/var/www/oldsite/schedule.json');
$scheduleData = json_decode($scheduleJson, true);

if ($scheduleData) {
    echo "Migrating Schedule...\n";
    $stmt = $db->prepare("INSERT INTO schedule (title, start_time, end_time, cdn_id, is_active) VALUES (:title, :start_time, :end_time, :cdn_id, :is_active)");
    
    // Get default CDN ID (assuming first one is default)
    $cdnId = 1; 
    $cdnStmt = $db->query("SELECT id FROM cdn_links LIMIT 1");
    if ($row = $cdnStmt->fetch(PDO::FETCH_ASSOC)) {
        $cdnId = $row['id'];
    }

    // Days mapping for next occurrence
    $daysOfWeek = [
        "Monday" => "next Monday",
        "Tuesday" => "next Tuesday",
        "Wednesday" => "next Wednesday",
        "Thursday" => "next Thursday",
        "Friday" => "next Friday",
        "Saturday" => "next Saturday",
        "Sunday" => "next Sunday"
    ];

    foreach ($scheduleData as $day => $events) {
        foreach ($events as $event) {
            // Calculate next occurrence date
            $dateString = $daysOfWeek[$day];
            // If today is the day, we might want "this Monday" or just date('Y-m-d') if time hasn't passed?
            // For simplicity, let's just use "next Day" logic or current date if it matches.
            if (date('l') == $day) {
                $dateString = "today";
            }
            
            $baseDate = date('Y-m-d', strtotime($dateString));
            $startTime = $baseDate . ' ' . $event['time'];
            $duration = isset($event['duration']) ? (int)$event['duration'] : 50;
            $endTime = date('Y-m-d H:i:s', strtotime($startTime) + ($duration * 60));

            // Determine CDN based on video path (simplified logic)
            // In oldsite, video path was relative. We might need to store the relative path or full URL.
            // The task says "video files from CDN".
            // Let's store the video path in description or a new column? 
            // Wait, the `schedule` table I designed doesn't have `video_path`! I missed that.
            // I need to alter the table or add it.
            // Checking init.sql: 
            // CREATE TABLE IF NOT EXISTS schedule ( ... cdn_id INT ... );
            // It seems I forgot `video_path` or `video_url`.
            // I should add `video_path` to the schedule table.
            
            // Let's add it now via SQL execution or just update init.sql and recreate.
            // Since I haven't put data in yet, I can update init.sql and re-run it (or just ALTER TABLE here).
            // I will ALTER TABLE in this script to be safe.
            
            try {
                $db->exec("ALTER TABLE schedule ADD COLUMN video_path VARCHAR(255)");
            } catch (PDOException $e) {
                // Ignore if exists
            }

            $stmtWithVideo = $db->prepare("INSERT INTO schedule (title, start_time, end_time, cdn_id, is_active, video_path) VALUES (:title, :start_time, :end_time, :cdn_id, :is_active, :video_path)");
            
            $stmtWithVideo->execute([
                ':title' => $event['title'],
                ':start_time' => $startTime,
                ':end_time' => $endTime,
                ':cdn_id' => $cdnId,
                ':is_active' => isset($event['active']) ? $event['active'] : 1,
                ':video_path' => $event['video']
            ]);
        }
    }
    echo "Schedule migrated.\n";
}

// 3. Migrate Info Blocks
$infoJson = file_get_contents('/var/www/oldsite/info_blocks.json');
$infoData = json_decode($infoJson, true);

if ($infoData) {
    echo "Migrating Info Blocks (Index/iOS)...\n";
    $stmt = $db->prepare("INSERT INTO info_blocks (page_name, title, content) VALUES (:page_name, :title, :content)");
    
    foreach ($infoData as $block) {
        // For Index
        $stmt->execute([
            ':page_name' => 'index',
            ':title' => $block['title'],
            ':content' => $block['description']
        ]);
        // For iOS (assuming same content)
        $stmt->execute([
            ':page_name' => 'i',
            ':title' => $block['title'],
            ':content' => $block['description']
        ]);
    }
    echo "Info Blocks (Index/iOS) migrated.\n";
}

// 4. Migrate Sacral Info Blocks (Hardcoded)
echo "Migrating Info Blocks (Sacral)...\n";
$sacralBlocks = [
    [
        'title' => 'Мириадоника',
        'content' => '<p>Что такое Мириадоника?
<br><br>
Это исцеление потоками космического происхождения, передаваемыми оператором всем, кто слушает прямую трансляцию.<br>
<br>
Как и какими потоками идет работа а так же, узнать подробнее о методике <a class="highlighted-link" href="https://t.me/c/1177994457/14075/"><b>здесь</b></a><br>
<br>
Работа ведется только в живую!</p>'
    ],
    [
        'title' => 'Донейшн',
        'content' => '<p>
❣️ Ваш отзыв о сеансе важен, описывайте пожалуйста все что увидите, ощутите по этой <a class="highlighted-link" href="https://t.me/c/1177994457/14082/17322" target="_blank"><b>ссылке</b></a><br>
<br>
🌟 После сеанса, Вы можете отблагодарить мастера и поддержать наш проект по сердцу за каждый сеанс<br>
<br>
В описании перевода ничего не указывайте ❗️<br>
<br>
Из-за границы <br>
PayPal: m.sokalsky@yandex.com<br>
(выбрать перевод для семьи/друзей)<br>
<br>
Из России: на карту<br>
Сбербанк 2202202353475027 <br>
Maria Sokalsky <br><br>
на Сбербанк по номеру  телефона +79956207299<br>
<br>
После перевода обязательно выслать скриншот выписки со счёта мастеру Меатару в личку:<br>
<a class="highlighted-link" href="https://t.me/lenattro"><b>@lenattro</b></a>
</p>'
    ]
];

$stmt = $db->prepare("INSERT INTO info_blocks (page_name, title, content) VALUES (:page_name, :title, :content)");
foreach ($sacralBlocks as $block) {
    $stmt->execute([
        ':page_name' => 'sacral',
        ':title' => $block['title'],
        ':content' => $block['content']
    ]);
     $stmt->execute([
        ':page_name' => 'sacrali',
        ':title' => $block['title'],
        ':content' => $block['content']
    ]);
}
echo "Info Blocks (Sacral) migrated.\n";

// 5. Visitor Table Handling
echo "Preparing Visitor Table...\n";
try {
    $db->exec("CREATE TABLE IF NOT EXISTS visitors (
        id INT AUTO_INCREMENT PRIMARY KEY,
        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        ip_address VARCHAR(45) NOT NULL,
        user_agent TEXT,
        page_viewed VARCHAR(255),
        broadcast_id INT
    )");
    
    // Ensure page_viewed column exists for existing tables
    try {
        $db->exec("ALTER TABLE visitors ADD COLUMN page_viewed VARCHAR(255) AFTER user_agent");
    } catch (PDOException $e) { /* Ignore if exists */ }

    // Ensure timestamp column exists (might be named visit_time from previous build)
    try {
        $db->exec("ALTER TABLE visitors CHANGE COLUMN visit_time timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
    } catch (PDOException $e) {
        try {
            $db->exec("ALTER TABLE visitors ADD COLUMN timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
        } catch (PDOException $e2) { /* Ignore if exists */ }
    }

    echo "Visitor table ready.\n";
} catch (PDOException $e) {
    echo "Error creating visitor table: " . $e->getMessage() . "\n";
}

echo "Migration completed successfully.\n";
echo "NOTE: If you have an existing SQL dump of 'online_visitors', please import it directly via phpMyAdmin or MySQL CLI.\n";
