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

// Load header configuration
include_once('../includes/header.php'); 

// Authorization Guard: Only Schedulers can access this control desk
if ($_SESSION['role'] !== 'Scheduler') {
    echo "<script>window.location.href='../login.php';</script>";
    exit;
}

$status_msg = "";

// --- HANDLING CAMPAIGN DELETION ROUTE ---
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    
    // Deleting from schedules will automatically clear matching details and assets due to foreign key cascades
    $delete_query = "DELETE FROM schedules WHERE id = $delete_id";
    if (mysqli_query($conn, $delete_query)) {
        $status_msg = "<div class='alert alert-success border-0 shadow-sm'>🗑️ Campaign Schedule deleted successfully.</div>";
    } else {
        $status_msg = "<div class='alert alert-danger border-0 shadow-sm'>Failed to remove schedule entry.</div>";
    }
}
?>

<div class="main-card shadow-sm border-0 mb-5">
    <div class="card-header-dark p-4 d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0 fw-bold text-white text-uppercase">Scheduler Management</h5>
            <small class="text-secondary opacity-75">Full Campaign Oversight & Control Console</small>
        </div>
        <a href="create.php" class="btn btn-sm btn-success rounded-pill px-3 fw-bold">
            <i class="bi bi-plus-circle me-1"></i> New Campaign
        </a>
    </div>

    <div class="p-4 bg-white rounded-bottom border border-top-0">
        <?php echo $status_msg; ?>

        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="bg-light">
                    <tr>
                        <th class="py-3 border-0 ps-3">CAMPAIGN DETAILS</th>
                        <th class="py-3 border-0">DURATION</th>
                        <th class="py-3 border-0">MODE</th>
                        <th class="py-3 border-0">TARGET PLATFORMS</th>
                        <th class="py-3 border-0 text-center">GLOBAL STATUS</th>
                        <th class="py-3 border-0 text-end pe-3">ACTIONS</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // Fetch every deployed schedule row
                    $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'];
                            
                            // Map state styling attributes
                            $dbStatus = trim($row['status'] ?? 'Pending');
                            $bgClass = "bg-warning text-dark"; 
                            if (strcasecmp($dbStatus, 'In Progress') == 0) $bgClass = "bg-info text-white";
                            if (strcasecmp($dbStatus, 'Completed') == 0) $bgClass = "bg-success text-white";

                            // Query active distribution target channels
                            $details_sql = "SELECT platform FROM schedule_details WHERE schedule_id = $s_id";
                            $details_res = mysqli_query($conn, $details_sql);
                            $plat_list = [];
                            while($d = mysqli_fetch_assoc($details_res)) { 
                                $plat_list[] = $d['platform']; 
                            }
                    ?>
                    <tr>
                        <td class="py-4 ps-3">
                            <div class="fw-bold text-dark h6 mb-1"><?php echo htmlspecialchars($row['title']); ?></div>
                            <small class="text-muted text-uppercase fw-bold" style="font-size: 10px; letter-spacing: 0.5px;">
                                <i class="bi bi-hash"></i> SH-0<?php echo $s_id; ?>
                            </small>
                        </td>

                        <td>
                            <div class="small fw-bold text-secondary">
                                <?php echo htmlspecialchars($row['start_date']); ?> 
                                <span class="mx-1 text-muted opacity-50">→</span> 
                                <?php echo htmlspecialchars($row['end_date']); ?>
                            </div>
                        </td>

                        <td>
                            <span class="badge bg-dark text-uppercase font-monospace" style="font-size: 10px;">
                                <?php echo htmlspecialchars($row['mode']); ?>
                            </span>
                        </td>

                        <td>
                            <?php if(!empty($plat_list)): ?>
                                <?php foreach($plat_list as $plt): ?>
                                    <span class="badge bg-light text-dark border rounded-pill px-2 py-1 small fw-normal me-1" style="font-size: 10px;">
                                        <?php echo htmlspecialchars($plt); ?>
                                    </span>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <small class="text-muted italic">No platforms assigned</small>
                            <?php endif; ?>
                        </td>

                        <td class="text-center">
                            <span class="badge <?php echo $bgClass; ?> px-3 py-2 shadow-sm fw-bold" style="min-width: 110px; font-size: 11px;">
                                <?php echo strtoupper($dbStatus); ?>
                            </span>
                        </td>

                        <td class="text-end pe-3">
                            <div class="d-inline-flex gap-2">
                                <a href="edit.php?id=<?php echo $s_id; ?>" class="btn btn-sm btn-outline-primary rounded-pill px-3 fw-bold">
                                    <i class="bi bi-pencil-square"></i> Edit
                                </a>
                                <a href="dashboard.php?delete_id=<?php echo $s_id; ?>" 
                                   class="btn btn-sm btn-outline-danger rounded-pill px-3 fw-bold"
                                   onclick="return confirm('Are you sure you want to completely erase this campaign schedule along with all its attached files?')">
                                    <i class="bi bi-trash3"></i> Delete
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php 
                        } 
                    } else {
                        echo "<tr><td colspan='6' class='text-center py-5 text-muted small italic'>
                                <i class='bi bi-folder-x d-block h1 opacity-25'></i>
                                No active campaign entries deployed on system storage.
                              </td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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