<?php
// pages/streaming_input.php
requireRole('any');

// Fetch Streams for dropdown
$streams = $pdo->query("SELECT id, name FROM youtube_streams ORDER BY name")->fetchAll(PDO::FETCH_KEY_PAIR);

// Service Types Configuration
$service_types = [
    'Sunday School Service',
    'Elementary Sunday School',
    'Devotional Service',
    'Evening Service / YPS / Evangelistic',
    'Bible Study'
];

// Fetch Recent Logs
$recent_yt_logs = $pdo->query("SELECT yml.*, ys.name as stream_name FROM youtube_manual_logs yml JOIN youtube_streams ys ON yml.stream_id = ys.id ORDER BY created_at DESC LIMIT 10")->fetchAll();
$recent_radio_logs = $pdo->query("SELECT * FROM radio_manual_logs ORDER BY service_date DESC LIMIT 5")->fetchAll();

$msg = isset($_GET['msg']) ? htmlspecialchars($_GET['msg']) : '';
$error = isset($_GET['error']) ? htmlspecialchars($_GET['error']) : '';
?>

<h1>Manual Streaming Entry</h1>

<?php if ($msg): ?>
<div class="alert alert-success"><?php echo $msg; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger"><?php echo $error; ?></div>
<?php endif; ?>

<?php
// ... Previous Fetches ...
$edit_mode = false;
$edit_data = [];
$edit_type = '';

if (isset($_GET['edit_id']) && isset($_GET['type'])) {
    $edit_id = (int)$_GET['edit_id'];
    $edit_type = $_GET['type'];
    
    if ($edit_type === 'youtube') {
        $stmt = $pdo->prepare("SELECT * FROM youtube_manual_logs WHERE id = ?");
        $stmt->execute([$edit_id]);
        $edit_data = $stmt->fetch();
        if ($edit_data) $edit_mode = true;
    } elseif ($edit_type === 'radio') {
        $stmt = $pdo->prepare("SELECT * FROM radio_manual_logs WHERE id = ?");
        $stmt->execute([$edit_id]);
        $edit_data = $stmt->fetch();
        if ($edit_data) $edit_mode = true;
    }
}
?>

<div class="dashboard-grid">
    <!-- YouTube Manual Entry -->
    <div class="card" style="grid-column: span 2;">
        <?php if ($edit_mode && $edit_type === 'youtube'): ?>
            <div style="background: #fff3cd; color: #856404; padding: 10px; margin-bottom: 20px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center;">
                <strong><i class="fas fa-edit"></i> Editing YouTube Entry #<?php echo $edit_data['id']; ?></strong>
                <a href="index.php?page=streaming_input" class="btn" style="background: #666; padding: 2px 8px; font-size: 0.8rem;">Cancel</a>
            </div>
            
            <form action="api/streaming_manual_save.php" method="POST">
                <input type="hidden" name="action" value="update_youtube">
                <input type="hidden" name="id" value="<?php echo $edit_data['id']; ?>">
                
                <div class="dashboard-grid" style="grid-template-columns: 1fr 1fr; margin-bottom: 20px;">
                    <div class="form-group">
                        <label>Stream</label>
                        <select name="stream_id" class="form-control" required>
                            <?php foreach ($streams as $id => $name): ?>
                                <option value="<?php echo $id; ?>" <?php echo $edit_data['stream_id'] == $id ? 'selected' : ''; ?>><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Service Date</label>
                        <input type="date" name="service_date" class="form-control" value="<?php echo $edit_data['service_date']; ?>" required>
                    </div>
                </div>

                <div class="form-group">
                    <label>Service Type</label>
                    <select name="service_type" class="form-control">
                         <?php foreach ($service_types as $st): ?>
                            <option value="<?php echo htmlspecialchars($st); ?>" <?php echo $edit_data['service_type'] === $st ? 'selected' : ''; ?>><?php echo htmlspecialchars($st); ?></option>
                         <?php endforeach; ?>
                         <option value="Other Services" <?php echo $edit_data['service_type'] === 'Other Services' ? 'selected' : ''; ?>>Other Services</option>
                    </select>
                </div>

                <div class="dashboard-grid" style="grid-template-columns: 1fr 1fr 1fr;">
                    <div class="form-group">
                        <label>Peak Viewers</label>
                        <input type="number" name="peak_viewers" class="form-control" value="<?php echo $edit_data['peak_viewers']; ?>">
                    </div>
                    <div class="form-group">
                        <label>Physical Attendance</label>
                        <input type="number" name="physical_attendance" class="form-control" value="<?php echo $edit_data['physical_attendance']; ?>">
                    </div>
                    <div class="form-group">
                        <label>Description (Optional)</label>
                        <input type="text" name="description" class="form-control" value="<?php echo htmlspecialchars($edit_data['description'] ?? ''); ?>">
                    </div>
                </div>

                <button type="submit" class="btn" style="width: auto;">Update Entry</button>
            </form>

        <?php else: ?>
            <!-- Normal Add Form -->
            <h3><i class="fab fa-youtube" style="color: red;"></i> YouTube Service Logs</h3>
            <form action="api/streaming_manual_save.php" method="POST">
                <input type="hidden" name="action" value="save_youtube">
                
                <div class="dashboard-grid" style="grid-template-columns: 1fr 1fr; margin-bottom: 20px;">
                    <div class="form-group">
                        <label>Select Channel / Stream</label>
                        <select name="stream_id" class="form-control" required>
                            <option value="">-- Select Stream --</option>
                            <?php foreach ($streams as $id => $name): ?>
                                <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Service Date</label>
                        <input type="date" name="service_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                </div>

                <table class="table" style="width: 100%;">
                    <thead>
                        <tr>
                            <th style="text-align: left;">Service Type</th>
                            <th style="width: 150px;">Peak Viewers</th>
                            <th style="width: 150px;">Physical Attd.</th>
                            <th>Description (Optional)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($service_types as $index => $type): ?>
                        <tr>
                            <td style="padding: 10px;">
                                <?php echo $type; ?>
                                <input type="hidden" name="logs[<?php echo $index; ?>][type]" value="<?php echo htmlspecialchars($type); ?>">
                            </td>
                            <td>
                                <input type="number" name="logs[<?php echo $index; ?>][peak]" class="form-control" min="0" placeholder="0">
                            </td>
                            <td>
                                <input type="number" name="logs[<?php echo $index; ?>][physical_attendance]" class="form-control" min="0" placeholder="0">
                            </td>
                            <td>
                                <input type="hidden" name="logs[<?php echo $index; ?>][desc]" value="">
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <!-- Other Services -->
                        <tr>
                            <td style="padding: 10px;">
                                <strong>Other Services</strong>
                                <input type="hidden" name="logs[99][type]" value="Other Services">
                            </td>
                            <td>
                                <input type="number" name="logs[99][peak]" class="form-control" min="0" placeholder="0">
                            </td>
                            <td>
                                <input type="number" name="logs[99][physical_attendance]" class="form-control" min="0" placeholder="0">
                            </td>
                            <td>
                                <input type="text" name="logs[99][desc]" class="form-control" placeholder="Describe event...">
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div style="margin-top: 20px; text-align: right;">
                    <button type="submit" class="btn" style="width: auto; padding: 10px 40px;">Log All Entries</button>
                </div>
            </form>
        <?php endif; ?>

        <h4 style="margin-top: 30px;">Recent Entries</h4>
        <div style="overflow-x: auto;">
            <table class="table" style="width: 100%; font-size: 0.9rem;">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Channel</th>
                        <th>Service</th>
                        <th>Peak Viewers</th>
                        <th>Physical</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_yt_logs as $log): ?>
                    <tr style="<?php echo ($edit_mode && $edit_type == 'youtube' && $edit_data['id'] == $log['id']) ? 'background: #333;' : ''; ?>">
                        <td><?php echo $log['service_date']; ?></td>
                        <td><?php echo htmlspecialchars($log['stream_name']); ?></td>
                        <td>
                            <?php echo htmlspecialchars($log['service_type'] ?? 'General'); ?>
                            <?php if(!empty($log['description'])) echo " <small class='text-muted'>(" . htmlspecialchars($log['description']) . ")</small>"; ?>
                        </td>
                        <td style="font-weight: bold;"><?php echo $log['peak_viewers']; ?></td>
                        <td><?php echo isset($log['physical_attendance']) ? $log['physical_attendance'] : '-'; ?></td>
                        <td>
                            <a href="index.php?page=streaming_input&edit_id=<?php echo $log['id']; ?>&type=youtube" 
                               class="btn" style="background: var(--primary-color); padding: 5px 10px; font-size: 0.8rem; margin-right: 5px;">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="api/streaming_manual_delete.php?type=youtube&id=<?php echo $log['id']; ?>" 
                               class="btn" style="background: var(--danger-color); padding: 5px 10px; font-size: 0.8rem;"
                               onclick="return confirm('Are you sure you want to delete this YouTube entry?');">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Radio Manual Entry -->
    <div class="card">
        <?php if ($edit_mode && $edit_type === 'radio'): ?>
            <div style="background: #e3f2fd; color: #0d47a1; padding: 10px; margin-bottom: 20px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center;">
                <strong><i class="fas fa-edit"></i> Editing Radio Entry #<?php echo $edit_data['id']; ?></strong>
                <a href="index.php?page=streaming_input" style="color: #666; font-size: 0.8rem;">Cancel</a>
            </div>

            <form action="api/streaming_manual_save.php" method="POST">
                <input type="hidden" name="action" value="update_radio">
                <input type="hidden" name="id" value="<?php echo $edit_data['id']; ?>">
                
                <div class="form-group">
                    <label>Service Date</label>
                    <input type="date" name="service_date" class="form-control" value="<?php echo $edit_data['service_date']; ?>" required>
                </div>
                <div class="form-group">
                    <label>Service Type</label>
                    <select name="service_type" class="form-control" required>
                        <?php foreach ($service_types as $st): ?>
                        <option value="<?php echo htmlspecialchars($st); ?>" <?php echo $edit_data['service_type'] === $st ? 'selected' : ''; ?>><?php echo htmlspecialchars($st); ?></option>
                        <?php endforeach; ?>
                        <option value="Other Services" <?php echo $edit_data['service_type'] === 'Other Services' ? 'selected' : ''; ?>>Other Services</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Listener Count</label>
                    <input type="number" name="listener_count" class="form-control" value="<?php echo $edit_data['listener_count']; ?>" required min="0">
                </div>
                <div class="form-group">
                    <label>Notes (Optional)</label>
                    <input type="text" name="notes" class="form-control" value="<?php echo htmlspecialchars($edit_data['notes'] ?? ''); ?>">
                </div>
                <button type="submit" class="btn btn-block" style="background-color: var(--accent-color);">Update Radio Log</button>
            </form>
        <?php else: ?>
            <h3><i class="fas fa-broadcast-tower" style="color: var(--accent-color);"></i> Web Radio Log</h3>
            <form action="api/streaming_manual_save.php" method="POST">
                <input type="hidden" name="action" value="save_radio">
                <div class="form-group">
                    <label>Service Date</label>
                    <input type="date" name="service_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                </div>
                <div class="form-group">
                    <label>Service Type</label>
                    <select name="service_type" class="form-control" required>
                        <?php foreach ($service_types as $st): ?>
                        <option value="<?php echo htmlspecialchars($st); ?>"><?php echo htmlspecialchars($st); ?></option>
                        <?php endforeach; ?>
                        <option value="Other Services">Other Services</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Listener Count</label>
                    <input type="number" name="listener_count" class="form-control" required min="0">
                </div>
                <div class="form-group">
                    <label>Notes (Optional)</label>
                    <input type="text" name="notes" class="form-control" placeholder="e.g. Special Revival Service">
                </div>
                <button type="submit" class="btn btn-block" style="background-color: var(--accent-color);">Log Radio Stats</button>
            </form>
        <?php endif; ?>

        <h4 style="margin-top: 20px;">Recent Entries</h4>
        <ul style="list-style: none; padding: 0; font-size: 0.9rem; color: #aaa;">
            <?php foreach ($recent_radio_logs as $log): ?>
                <li style="border-bottom: 1px solid #333; padding: 5px 0; display: flex; justify-content: space-between; align-items: center; <?php echo ($edit_mode && $edit_type == 'radio' && $edit_data['id'] == $log['id']) ? 'background: #222;' : ''; ?>">
                    <div>
                        <span><?php echo $log['service_date']; ?></span>
                        <strong style="color: #fff; margin-left: 10px;"><?php echo $log['listener_count']; ?></strong>
                        <br>
                        <small><?php echo htmlspecialchars($log['service_type'] ?? 'General'); ?></small>
                    </div>
                    <div>
                        <a href="index.php?page=streaming_input&edit_id=<?php echo $log['id']; ?>&type=radio" 
                           style="color: var(--primary-color); margin-right: 10px;">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="api/streaming_manual_delete.php?type=radio&id=<?php echo $log['id']; ?>" 
                           style="color: var(--danger-color);"
                           onclick="return confirm('Delete this radio log?');">
                            <i class="fas fa-trash"></i>
                        </a>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>
</div>
