<?php require_once __DIR__ . '/layout.php'; ?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; flex-wrap: wrap; gap: 1rem;">
    <div>
        <h3 style="margin: 0 0 0.5rem; color: white;">Global System Settings</h3>
        <p style="color: var(--text-muted); margin: 0;">Configure background automation, start/stop the scheduler agent, and monitor execution logs.</p>
    </div>
    <div>
        <a href="/superadmin/settings" class="btn-outline-gold" style="display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.6rem 1.2rem; text-decoration: none; border-radius: 8px; font-weight: 600;">
            <i class="ph ph-arrows-counter-clockwise" style="font-size: 1.2rem;"></i>
            <span>Refresh Data</span>
        </a>
    </div>
</div>

<!-- Grid for Status and Controls -->
<div class="two-col-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem; align-items: stretch;">
    <!-- Scheduler Engine Card -->
    <div class="card" style="padding: 2rem; background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: 16px; backdrop-filter: blur(10px);">
        <h3 style="margin-top: 0; color: white; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem;">
            <i class="ph ph-cpu" style="color: #fbbf24; font-size: 1.5rem;"></i>
            Scheduler Engine Status
        </h3>
        <div style="margin: 1.5rem 0; display: flex; align-items: center; gap: 1.5rem;">
            <!-- Engine Run State -->
            <div>
                <span style="color: var(--text-muted); font-size: 0.85rem; display: block; margin-bottom: 0.25rem;">Control Status</span>
                <?php if ($schedulerActive === '1'): ?>
                    <span style="display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(16, 185, 129, 0.15); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.3); padding: 0.35rem 0.75rem; border-radius: 9999px; font-weight: 600; font-size: 0.9rem;">
                        <span style="width: 8px; height: 8px; background: #10b981; border-radius: 50%; display: inline-block; animation: pulse 1.5s infinite;"></span>
                        Active / Started
                    </span>
                <?php else: ?>
                    <span style="display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(239, 68, 68, 0.15); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.3); padding: 0.35rem 0.75rem; border-radius: 9999px; font-weight: 600; font-size: 0.9rem;">
                        <span style="width: 8px; height: 8px; background: #ef4444; border-radius: 50%; display: inline-block;"></span>
                        Inactive / Stopped
                    </span>
                <?php endif; ?>
            </div>

            <!-- Heartbeat State -->
            <div>
                <span style="color: var(--text-muted); font-size: 0.85rem; display: block; margin-bottom: 0.25rem;">Engine Heartbeat</span>
                <?php if ($heartbeatActive): ?>
                    <span style="display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(16, 185, 129, 0.15); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.3); padding: 0.35rem 0.75rem; border-radius: 9999px; font-weight: 600; font-size: 0.9rem;">
                        <i class="ph ph-heartbeat" style="font-size: 1.1rem;"></i>
                        Connected
                    </span>
                <?php else: ?>
                    <span style="display: inline-flex; align-items: center; gap: 0.5rem; background: rgba(245, 158, 11, 0.15); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.3); padding: 0.35rem 0.75rem; border-radius: 9999px; font-weight: 600; font-size: 0.9rem;">
                        <i class="ph ph-warning-circle" style="font-size: 1.1rem;"></i>
                        Disconnected
                    </span>
                <?php endif; ?>
            </div>
        </div>

        <p style="color: var(--text-light); font-size: 0.9rem; line-height: 1.5; margin: 0;">
            <?php if ($heartbeatActive): ?>
                The background engine was last seen at <strong style="color: white;"><?php echo htmlspecialchars($lastHeartbeat); ?></strong>. It is communicating normally.
            <?php else: ?>
                The background engine hasn't checked in recently. Please ensure that the daemon task is running on localhost, or setup the Cron job command: <code style="background: rgba(15,23,42,0.6); padding: 0.2rem 0.4rem; border-radius: 4px; color: #f59e0b; font-size: 0.8rem; font-family: monospace;">php bin/expiry_scheduler.php</code>
            <?php endif; ?>
        </p>

        <div style="margin-top: 1.5rem; display: flex; gap: 1rem;">
            <?php if ($schedulerActive === '1'): ?>
                <a href="/superadmin/stopScheduler" class="btn-gold" style="background: #ef4444; color: white;">
                    <i class="ph ph-stop-circle" style="font-size: 1.25rem;"></i> Stop Scheduler
                </a>
            <?php else: ?>
                <a href="/superadmin/startScheduler" class="btn-gold" style="background: #10b981; color: white;">
                    <i class="ph ph-play-circle" style="font-size: 1.25rem;"></i> Start Scheduler
                </a>
            <?php endif; ?>
        </div>
        
        <form action="/superadmin/updateSettings" method="POST" style="margin-top: 1.5rem; border-top: 1px solid var(--glass-border); padding-top: 1.5rem;">
            <div class="input-group" style="margin-bottom: 0;">
                <label for="scheduler_downtime_emails" style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 0.5rem; display: block;">Scheduler Downtime Alert (Comma separated emails)</label>
                <div style="display: flex; gap: 1rem; align-items: flex-start;">
                    <input type="text" id="scheduler_downtime_emails" name="scheduler_downtime_emails" value="<?php echo htmlspecialchars($downtimeEmails ?? ''); ?>" placeholder="admin@example.com, it@example.com" style="flex: 1; padding: 0.75rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; font-size: 0.95rem;">
                    <button type="submit" class="btn-gold" style="height: 46px; white-space: nowrap;">
                        <i class="ph ph-floppy-disk" style="font-size: 1.25rem;"></i> Save
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Configure Daily Run Time -->
    <div class="card" style="padding: 2rem; background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: 16px; backdrop-filter: blur(10px);">
        <h3 style="margin-top: 0; color: white; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.75rem;">
            <i class="ph ph-sliders" style="vertical-align: middle; color: #fbbf24; margin-right: 0.5rem; font-size: 1.5rem;"></i>
            Run Time Settings
        </h3>
        <form action="/superadmin/updateSettings" method="POST" style="margin-top: 1.5rem;">
            <div style="display: flex; align-items: flex-end; gap: 1rem; flex-wrap: wrap;">
                
                <div class="input-group" style="margin-bottom: 0; width: 120px;">
                    <label for="run_hour" style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 0.5rem; display: block;">Hour</label>
                    <select id="run_hour" name="run_hour" required style="width: 100%; padding: 0.75rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; font-size: 0.95rem;">
                        <?php for ($h = 1; $h <= 12; $h++): ?>
                            <?php $hVal = sprintf("%02d", $h); ?>
                            <option value="<?php echo $hVal; ?>" <?php echo $runHour === $hVal ? 'selected' : ''; ?> style="background: var(--bg-dark); color: white;"><?php echo $hVal; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="input-group" style="margin-bottom: 0; width: 120px;">
                    <label for="run_minute" style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 0.5rem; display: block;">Minute</label>
                    <select id="run_minute" name="run_minute" required style="width: 100%; padding: 0.75rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; font-size: 0.95rem;">
                        <?php for ($m = 0; $m < 60; $m += 5): ?>
                            <?php $mVal = sprintf("%02d", $m); ?>
                            <option value="<?php echo $mVal; ?>" <?php echo $runMinute === $mVal ? 'selected' : ''; ?> style="background: var(--bg-dark); color: white;"><?php echo $mVal; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="input-group" style="margin-bottom: 0; width: 100px;">
                    <label for="run_period" style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 0.5rem; display: block;">Period</label>
                    <select id="run_period" name="run_period" required style="width: 100%; padding: 0.75rem; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(15,23,42,0.6); color: white; outline: none; font-size: 0.95rem;">
                        <option value="AM" <?php echo $runPeriod === 'AM' ? 'selected' : ''; ?> style="background: var(--bg-dark); color: white;">AM</option>
                        <option value="PM" <?php echo $runPeriod === 'PM' ? 'selected' : ''; ?> style="background: var(--bg-dark); color: white;">PM</option>
                    </select>
                </div>
                
                <button type="submit" class="btn-gold" style="height: 46px;">
                    <i class="ph ph-floppy-disk" style="font-size: 1.25rem;"></i> Save
                </button>
            </div>
            <small style="color: var(--text-muted); display: block; margin-top: 1rem;">
                This controls the daily run time of the NotifyAgent automation background checks (e.g. 08:00 AM).
            </small>
        </form>
    </div>
</div>



<!-- Logs Section -->
<div class="card" style="padding: 2rem; background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: 16px; backdrop-filter: blur(10px); margin-top: 2rem;">
    <h3 style="margin-top: 0; color: white; border-bottom: 1px solid var(--glass-border); padding-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem;">
        <i class="ph ph-list-bullets" style="color: #fbbf24; font-size: 1.5rem;"></i>
        Scheduler Execution Logs
    </h3>
    <div class="responsive-table-container" style="overflow-x: auto; margin-top: 1.5rem; border: none;">
        <table class="data-table" style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr>
                    <th style="color: var(--text-muted);">Date & Time</th>
                    <th style="color: var(--text-muted);">Tenant</th>
                    <th style="color: var(--text-muted); text-align: center;">Trigger</th>
                    <th style="color: var(--text-muted); text-align: center;">Channel</th>
                    <th style="color: var(--text-muted);">Recipients</th>
                    <th style="color: var(--text-muted); text-align: center;">Items</th>
                    <th style="color: var(--text-muted);">Status</th>
                    <th style="color: var(--text-muted);">Failure Reason / Notes</th>
                    <th style="color: var(--text-muted); text-align: center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($logs)): ?>
                    <tr>
                        <td colspan="9" style="text-align: center; color: var(--text-muted); padding: 2rem;">No execution logs found.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                        <tr>
                            <td style="color: white; white-space: nowrap; font-weight: 500;">
                                <?php echo htmlspecialchars($log['created_at']); ?>
                            </td>
                            <td style="color: var(--text-light);">
                                <?php echo htmlspecialchars($log['tenant_name'] ?? 'System / Global'); ?>
                            </td>
                            <td style="text-align: center;">
                                <?php if (($log['alert_type'] ?? '') === 'manual'): ?>
                                    <span style="background: rgba(245, 158, 11, 0.1); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.2); padding: 0.25rem 0.5rem; border-radius: 4px; font-weight: 600; font-size: 0.8rem; display: inline-flex; align-items: center; gap: 0.25rem;">
                                        <i class="ph ph-user" style="font-size: 0.95rem;"></i> Manual
                                    </span>
                                <?php else: ?>
                                    <span style="background: rgba(139, 92, 246, 0.1); color: #a78bfa; border: 1px solid rgba(139, 92, 246, 0.2); padding: 0.25rem 0.5rem; border-radius: 4px; font-weight: 600; font-size: 0.8rem; display: inline-flex; align-items: center; gap: 0.25rem;">
                                        <i class="ph ph-clock" style="font-size: 0.95rem;"></i> Scheduler
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td style="text-align: center;">
                                <?php if (($log['channel'] ?? 'Email') === 'WhatsApp'): ?>
                                    <span style="color: #22c55e; font-weight: 600; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 0.25rem;">
                                        <i class="ph ph-whatsapp-logo" style="font-size: 1rem;"></i> WhatsApp
                                    </span>
                                <?php else: ?>
                                    <span style="color: #38bdf8; font-weight: 600; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 0.25rem;">
                                        <i class="ph ph-envelope-simple" style="font-size: 1rem;"></i> Email
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td style="color: var(--text-light); font-size: 0.85rem;" title="<?php echo htmlspecialchars($log['recipients'] ?? ''); ?>">
                                <?php 
                                    $rec = htmlspecialchars($log['recipients'] ?? '');
                                    echo strlen($rec) > 30 ? substr($rec, 0, 30) . '...' : $rec; 
                                ?>
                            </td>
                            <td style="color: #fbbf24; font-weight: bold; text-align: center;">
                                <?php echo intval($log['items_count']); ?>
                            </td>
                            <td>
                                <?php if ($log['status'] === 'success'): ?>
                                    <span style="background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.2); padding: 0.25rem 0.5rem; border-radius: 4px; font-weight: 600; font-size: 0.8rem;">
                                        SUCCESS
                                    </span>
                                <?php else: ?>
                                    <span style="background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); padding: 0.25rem 0.5rem; border-radius: 4px; font-weight: 600; font-size: 0.8rem;">
                                        FAILURE
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td style="color: #94a3b8; font-size: 0.85rem;">
                                <?php echo htmlspecialchars($log['failure_reason'] ?? 'N/A'); ?>
                            </td>
                            <td style="text-align: center; white-space: nowrap;">
                                <a href="/superadmin/logEdit/<?php echo $log['id']; ?>" class="action-icon edit" title="Edit Log">
                                    <i class="ph ph-pencil-simple"></i>
                                </a>
                                <a href="/superadmin/logDelete/<?php echo $log['id']; ?>" class="action-icon delete" title="Delete Log" onclick="return confirm('Are you sure you want to delete this log entry?');">
                                    <i class="ph ph-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<style>
@keyframes pulse {
    0% { transform: scale(0.9); opacity: 0.6; }
    50% { transform: scale(1.1); opacity: 1; }
    100% { transform: scale(0.9); opacity: 0.6; }
}
</style>

</div> <!-- main-content -->
</div> <!-- dashboard-layout -->

<script>
function updateClock() {
    const clockDateEl = document.getElementById('clockDate');
    const clockTimeEl = document.getElementById('clockTime');
    if (!clockDateEl || !clockTimeEl) return;

    const now = new Date();
    const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
    const dateStr = now.toLocaleDateString('en-US', options);
    
    let hours = now.getHours();
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    const hoursStr = String(hours).padStart(2, '0');
    
    clockDateEl.textContent = dateStr;
    clockTimeEl.textContent = `${hoursStr}:${minutes}:${seconds} ${ampm}`;
}
updateClock();
setInterval(updateClock, 1000);
</script>
</body>
</html>
