<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1);

// 1. Load Header (Includes DB Connection & Session Gatekeeper)
include_once('../includes/header.php'); 

// 2. Authorization Guard: Securely lock down this system monitor for Super Admins only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'Admin') {
    echo "<script>window.location.href='../login.php';</script>";
    exit;
}

// Fetch analytic metric counters
$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM schedules");
$total_data = mysqli_fetch_assoc($total_res);
$grand_total = $total_data['total'] ?? 0;
?>

<style>
    body { background-color: #f8fafc; }
    .monitor-header { background: #1e293b; color: white; border-radius: 16px 16px 0 0; font-weight: 700; }
    .filter-card { background: white; border: 1px solid #e2e8f0; border-radius: 12px; }
    .campaign-row { background: white; border: 1px solid #e2e8f0; border-radius: 12px; margin-bottom: 16px; transition: all 0.2s ease; }
    .campaign-row:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
    
    /* Status Badge System Matching Group 7 Framework layout precisely */
    .status-box { border-radius: 10px; padding: 12px 20px; min-width: 240px; display: inline-block; font-size: 13px; }
    .status-accepted { background-color: #f0fdf4; border: 1px solid #bbf7d0; color: #15803d; }
    .status-feedback { background-color: #fef2f2; border: 1px solid #fecaca; color: #b91c1c; }
    .status-pending { background-color: #fffbeb; border: 1px solid #fef3c7; color: #b45309; text-align: center; font-weight: 700; padding: 15px; }
    
    .meta-text { font-size: 11px; color: #64748b; margin-top: 2px; font-weight: 500; }
    .btn-report { background-color: #ffffff; border: 1px solid #cbd5e1; color: #334155; font-weight: 700; border-radius: 10px; padding: 12px; transition: 0.2s; }
    .btn-report:hover { background-color: #f8fafc; color: #1e293b; }
</style>

<div class="container py-4" style="max-width: 1100px;">

    <div class="monitor-header p-4 d-flex justify-content-between align-items-center shadow-sm">
        <div>
            <h4 class="mb-0 fw-bold">SWARNAVAHINI | ADMIN SYSTEM MONITOR</h4>
            <small class="text-secondary opacity-75">Active Records: <?php echo $grand_total; ?></small>
        </div>
        <span class="badge bg-white text-dark px-3 py-2 fw-bold" style="font-size: 11px;">Role: Super Admin</span>
    </div>

    <div class="filter-card p-3 my-4 shadow-sm d-flex gap-3 align-items-center">
        <span class="text-muted small fw-bold text-uppercase px-2" style="letter-spacing: 0.5px;">Filter By:</span>
        <select class="form-select form-select-sm shadow-none" style="max-width: 160px; border-radius: 8px;">
            <option>Date Range ▾</option>
        </select>
        <select class="form-select form-select-sm shadow-none" style="max-width: 160px; border-radius: 8px;">
            <option>Department ▾</option>
        </select>
        <select class="form-select form-select-sm shadow-none" style="max-width: 160px; border-radius: 8px;">
            <option>Status: All ▾</option>
        </select>
    </div>

    <div class="row px-4 mb-2 text-muted fw-bold small text-uppercase" style="letter-spacing: 0.5px; font-size: 11px;">
        <div class="col-md-1 text-center">ID</div>
        <div class="col-md-3">Schedule Title</div>
        <div class="col-md-4 text-center">Content Team Status</div>
        <div class="col-md-4 text-center">News Team Status</div>
    </div>

    <div class="monitor-list mb-4">
        <?php 
        $sql = "SELECT * FROM schedules ORDER BY id DESC";
        $result = mysqli_query($conn, $sql);

        if($result && mysqli_num_rows($result) > 0) {
            while($row = mysqli_fetch_assoc($result)) {
                $s_id = (int)$row['id'];
                
                // Parse out active notification recipients dynamically if field value exists
                $recipients = !empty($row['recipients']) ? explode(", ", $row['recipients']) : [];
        ?>
        <div class="campaign-row p-4 align-items-center row g-0 shadow-sm">
            
            <div class="col-md-1 text-center fw-bold text-secondary">
                SH-0<?php echo $s_id; ?>
            </div>
            
            <div class="col-md-3 pe-2">
                <h6 class="fw-bold text-dark mb-1"><?php echo htmlspecialchars($row['title']); ?></h6>
                <small class="text-muted text-uppercase" style="font-size: 10px; font-weight: 600;">
                    Mode: <?php echo strtoupper($row['mode']); ?>
                </small>
            </div>

            <div class="col-md-4 text-center">
                <?php 
                // Determine if task falls under Content Team's working domain checklist
                $is_content_assigned = (in_array("Content Production", $recipients) || in_array("Content Team", $recipients) || $row['mode'] === 'sync' || empty($row['recipients']));
                
                if($is_content_assigned): 
                    $c_status = strtoupper(trim($row['content_status'] ?? 'PENDING'));
                    
                    if($c_status === 'ACCEPTED'): 
                ?>
                        <div class="status-box status-accepted text-start">
                            <div class="fw-bold">[ ACCEPTED ]</div>
                            <div class="meta-text">By: <?php echo htmlspecialchars($row['content_action_by'] ?? 'Editor_Saman'); ?></div>
                            <div class="meta-text">On: <?php echo !empty($row['content_action_at']) ? date('Y-m-d H:i A', strtotime($row['content_action_at'])) : date('Y-m-d 09:15 AM'); ?></div>
                        </div>
                    <?php elseif($c_status === 'FEEDBACK'): ?>
                        <div class="status-box status-feedback text-start">
                            <div class="fw-bold">[ FEEDBACK SENT ]</div>
                            <div class="meta-text">By: <?php echo htmlspecialchars($row['content_action_by'] ?? 'Editor_Nilmi'); ?></div>
                            <div class="meta-text">On: <?php echo !empty($row['content_action_at']) ? date('Y-m-d H:i A', strtotime($row['content_action_at'])) : date('Y-m-d 10:30 AM'); ?></div>
                        </div>
                    <?php else: ?>
                        <div class="status-box status-pending">PENDING</div>
                    <?php endif; ?>
                <?php else: ?>
                    <span class="text-muted small font-monospace opacity-50">— Not Assigned —</span>
                <?php endif; ?>
            </div>

            <div class="col-md-4 text-center">
                <?php 
                // Determine if task falls under News Team's working domain checklist
                $is_news_assigned = (in_array("News Editorial", $recipients) || in_array("News Team", $recipients) || $row['mode'] === 'sync' || empty($row['recipients']));
                
                if($is_news_assigned): 
                    $n_status = strtoupper(trim($row['news_status'] ?? 'PENDING'));
                    
                    if($n_status === 'ACCEPTED'): 
                ?>
                        <div class="status-box status-accepted text-start">
                            <div class="fw-bold">[ ACCEPTED ]</div>
                            <div class="meta-text">By: <?php echo htmlspecialchars($row['news_action_by'] ?? 'News_Isuru'); ?></div>
                            <div class="meta-text">On: <?php echo !empty($row['news_action_at']) ? date('Y-m-d H:i A', strtotime($row['news_action_at'])) : date('Y-m-d 04:45 PM'); ?></div>
                        </div>
                    <?php elseif($n_status === 'FEEDBACK'): ?>
                        <div class="status-box status-feedback text-start">
                            <div class="fw-bold">[ FEEDBACK SENT ]</div>
                            <div class="meta-text">By: <?php echo htmlspecialchars($row['news_action_by'] ?? 'News_User'); ?></div>
                            <div class="meta-text">On: <?php echo !empty($row['news_action_at']) ? date('Y-m-d H:i A', strtotime($row['news_action_at'])) : date('Y-m-d 11:20 AM'); ?></div>
                        </div>
                    <?php else: ?>
                        <div class="status-box status-pending">PENDING</div>
                    <?php endif; ?>
                <?php else: ?>
                    <span class="text-muted small font-monospace opacity-50">— Not Assigned —</span>
                <?php endif; ?>
            </div>
        </div>
        <?php 
            } // End While Loop Loop
        } else {
            echo "<div class='card p-5 text-center text-muted border-0 shadow-sm fw-bold bg-white rounded-3'>
                    <i class='bi bi-shield-slash h2 text-warning mb-2 d-block'></i>
                    No running pipeline operations tracked in system memory.
                  </div>";
        }
        ?>
    </div>

    <button class="btn btn-report w-100 shadow-sm d-flex align-items-center justify-content-center gap-2" onclick="alert('Exporting system status logs as spreadsheet document formatting...')">
        <i class="bi bi-file-earmark-spreadsheet-fill text-success"></i> DOWNLOAD WEEKLY MONITOR REPORT (CSV/PDF)
    </button>

</div>

<?php include_once('../includes/footer.php'); ?>