<?php
// api/streaming_manual_save.php
require_once '../config/database.php';
require_once '../includes/functions.php';

session_start();
if (!isLoggedIn()) {
    die("Access Denied");
}

$action = $_POST['action'] ?? '';

try {
    if ($action === 'save_youtube') {
        $stream_id = (int)$_POST['stream_id'];
        $service_date = clean_input($_POST['service_date']);
        $logs = $_POST['logs'] ?? [];
        
        if (!$stream_id || !$service_date) die("Stream and Date required.");
        
        // AUTO-MIGRATION CHECK (Self-Healing)
        try {
            // Check descriptions (already exists but for safety)
            $check = $pdo->query("SHOW COLUMNS FROM youtube_manual_logs LIKE 'service_type'");
            if (!$check->fetch()) {
                $pdo->exec("ALTER TABLE youtube_manual_logs 
                    ADD COLUMN `service_type` VARCHAR(100) DEFAULT 'General' AFTER `service_date`,
                    ADD COLUMN `description` VARCHAR(255) DEFAULT NULL AFTER `service_type`
                ");
            }
            // Check physical_attendance
            $check2 = $pdo->query("SHOW COLUMNS FROM youtube_manual_logs LIKE 'physical_attendance'");
            if (!$check2->fetch()) {
                $pdo->exec("ALTER TABLE youtube_manual_logs ADD COLUMN `physical_attendance` INT DEFAULT 0 AFTER `peak_viewers`");
            }
        } catch (Exception $ignore) {}

        $count = 0;
        $stmt = $pdo->prepare("INSERT INTO youtube_manual_logs (stream_id, service_date, service_type, peak_viewers, physical_attendance, description) VALUES (?, ?, ?, ?, ?, ?)");
        
        foreach ($logs as $log) {
            $peak = (int)($log['peak'] ?? 0);
            $phy = (int)($log['physical_attendance'] ?? 0);
            
            if ($peak > 0 || $phy > 0) {
                // Save if either value exists
                $type = clean_input($log['type']);
                $desc = clean_input($log['desc'] ?? '');
                
                $stmt->execute([$stream_id, $service_date, $type, $peak, $phy, $desc]);
                $count++;
            }

        }
        
        logActivity($_SESSION['user_id'], 'CREATE', "Logged $count YouTube streaming entries");
        header("Location: ../index.php?page=streaming_input&msg=" . urlencode("$count entries log saved."));
        exit;
        
    } elseif ($action === 'update_youtube') {
        $id = (int)$_POST['id'];
        $stream_id = (int)$_POST['stream_id'];
        $service_date = clean_input($_POST['service_date']);
        $service_type = clean_input($_POST['service_type']);
        $peak = (int)$_POST['peak_viewers'];
        $phy = (int)$_POST['physical_attendance'];
        $desc = clean_input($_POST['description']);
        
        if ($id <= 0 || !$stream_id || !$service_date) die("Invalid Input");
        
        $stmt = $pdo->prepare("UPDATE youtube_manual_logs SET stream_id=?, service_date=?, service_type=?, peak_viewers=?, physical_attendance=?, description=? WHERE id=?");
        $stmt->execute([$stream_id, $service_date, $service_type, $peak, $phy, $desc, $id]);
        
        logActivity($_SESSION['user_id'], 'UPDATE', "Updated YouTube log ID: $id");
        header("Location: ../index.php?page=streaming_input&msg=" . urlencode("Entry updated successfully."));
        exit;

    } elseif ($action === 'save_radio') {
        // ... (existing save_radio logic is fine, let's just make sure we don't duplicate or cut it off incorrectly)
        $service_date = clean_input($_POST['service_date']);
        $service_type = clean_input($_POST['service_type'] ?? 'General');
        $listener_count = (int)$_POST['listener_count'];
        $notes = clean_input($_POST['notes']);
        
        // Auto-migration for radio schema
        try {
            $check = $pdo->query("SHOW COLUMNS FROM radio_manual_logs LIKE 'service_type'");
            if (!$check->fetch()) {
                $pdo->exec("ALTER TABLE radio_manual_logs ADD COLUMN `service_type` VARCHAR(100) DEFAULT 'General' AFTER `service_date`");
                // Also ensure ID exists
                try { $pdo->exec("ALTER TABLE radio_manual_logs ADD COLUMN `id` INT AUTO_INCREMENT PRIMARY KEY FIRST"); } catch(Exception $e){}
            }
        } catch (Exception $ignore) {}

        $stmt = $pdo->prepare("INSERT INTO radio_manual_logs (service_date, service_type, listener_count, notes) VALUES (?, ?, ?, ?)");
        $stmt->execute([$service_date, $service_type, $listener_count, $notes]);
        
        logActivity($_SESSION['user_id'], 'CREATE', "Logged Radio stats for $service_date ($listener_count listeners)");
        header("Location: ../index.php?page=streaming_input&msg=Radio log saved.");
        exit;

    } elseif ($action === 'update_radio') {
        $id = (int)$_POST['id'];
        $service_date = clean_input($_POST['service_date']);
        $service_type = clean_input($_POST['service_type']);
        $listener_count = (int)$_POST['listener_count'];
        $notes = clean_input($_POST['notes']);
        
        if ($id <= 0 || !$service_date) die("Invalid Input");

        $stmt = $pdo->prepare("UPDATE radio_manual_logs SET service_date=?, service_type=?, listener_count=?, notes=? WHERE id=?");
        $stmt->execute([$service_date, $service_type, $listener_count, $notes, $id]);
        
        logActivity($_SESSION['user_id'], 'UPDATE', "Updated Radio log ID: $id");
        header("Location: ../index.php?page=streaming_input&msg=" . urlencode("Radio entry updated."));
        exit;
    }
} catch (PDOException $e) {
    header("Location: ../index.php?page=streaming_input&error=" . urlencode("Error: " . $e->getMessage()));
    exit;
}
