<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/notifications.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/../config/database.php';
}

require_admin();

$act = $_POST['action'] ?? '';
if ($act === 'process') { 
    ensure_csrf(); 
    $res = process_email_queue($pdo, 20); 
    set_flash('success','Email queue processed: '.json_encode($res)); 
    redirect('/admin/notifications.php?tab=emails'); 
}

$activeTab = $_GET['tab'] ?? 'emails';

$emails = $pdo->query("SELECT * FROM email_queue ORDER BY created_at DESC LIMIT 100")->fetchAll();
$notifs = $pdo->query("SELECT n.*, u.full_name FROM notifications n JOIN users u ON u.id=n.user_id ORDER BY n.created_at DESC LIMIT 100")->fetchAll();

// Stats for emails
$emailStats = $pdo->query("SELECT status, COUNT(*) as count FROM email_queue GROUP BY status")->fetchAll(PDO::FETCH_KEY_PAIR);
$totalEmails = array_sum($emailStats);

include __DIR__ . '/../includes/header.php';
?>
<style>
.tabs-wrapper { border-bottom: 1px solid var(--border); margin-bottom: 24px; display: flex; gap: 8px; }
.tab-link { display: inline-flex; align-items: center; gap: 8px; padding: 12px 16px; color: var(--muted); font-weight: 600; border-bottom: 2px solid transparent; text-decoration: none; transition: all 0.2s; }
.tab-link:hover { color: var(--text); background: #f8fafc; }
.tab-link.active { color: var(--primary); border-bottom-color: var(--primary); }

.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.stat-card { background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 16px; display: flex; align-items: center; gap: 12px; }
.stat-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
.stat-val { font-size: 24px; font-weight: 700; color: var(--text); display: block; }
.stat-label { font-size: 13px; color: var(--muted); font-weight: 500; }

.status-sent { background: #ecfdf5; color: #065f46; border: 1px solid #bbf7d0; }
.status-queued { background: #fefce8; color: #854d0e; border: 1px solid #fef08a; }
.status-failed { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
.status-retry { background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; }

.notif-unread { border-left: 4px solid var(--primary); }
.notif-read { border-left: 4px solid transparent; opacity: 0.8; }

.data-preview { font-size: 11px; font-family: monospace; color: var(--muted); background: #f8fafc; padding: 4px 8px; border-radius: 4px; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
</style>

<div style="display:flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h2 style="margin:0">Notifications & Messaging</h2>
    <div style="display:flex; gap:10px">
        <a href="/admin/notifications.php" class="btn"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" stroke-linecap="round" stroke-linejoin="round"/></svg> Refresh</a>
        <?php if ($activeTab === 'emails'): ?>
        <form method="post" style="margin:0">
            <?=csrf_field()?>
            <input type="hidden" name="action" value="process">
            <button class="btn primary" type="submit">Process Queue Now</button>
        </form>
        <?php endif; ?>
    </div>
</div>

<div class="tabs-wrapper">
    <a href="?tab=emails" class="tab-link <?=$activeTab==='emails'?'active':''?>"><?=ui_icon('faq', 18)?> Email Queue</a>
    <a href="?tab=inapp" class="tab-link <?=$activeTab==='inapp'?'active':''?>"><?=ui_icon('users', 18)?> In-App Notifications</a>
</div>

<?php if ($activeTab === 'emails'): ?>
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#f1f5f9; color:#475569"><?=ui_icon('services', 20)?></div>
            <div>
                <span class="stat-val"><?=number_format((float)$totalEmails)?></span>
                <span class="stat-label">Total Emails</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon status-queued"><?=ui_icon('processing', 20)?></div>
            <div>
                <span class="stat-val"><?=number_format((float)($emailStats['queued'] ?? 0))?></span>
                <span class="stat-label">Queued</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon status-sent"><?=ui_icon('approved', 20)?></div>
            <div>
                <span class="stat-val"><?=number_format((float)($emailStats['sent'] ?? 0))?></span>
                <span class="stat-label">Successfully Sent</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon status-failed"><?=ui_icon('logout', 20)?></div>
            <div>
                <span class="stat-val"><?=number_format((float)($emailStats['failed'] ?? 0))?></span>
                <span class="stat-label">Failed Delivery</span>
            </div>
        </div>
    </div>

    <div class="card" style="padding:0; overflow:hidden;">
        <div style="padding:16px 20px; border-bottom:1px solid var(--border); background:#f8fafc">
            <h3 style="margin:0; font-size:16px">Outgoing Email Logs</h3>
        </div>
        <div style="overflow-x:auto">
            <table class="striped">
                <thead>
                    <tr>
                        <th>Recipient</th>
                        <th>Subject</th>
                        <th>Template</th>
                        <th>Status</th>
                        <th>Attempts</th>
                        <th>Timestamp</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($emails)): ?>
                        <tr><td colspan="6" style="text-align:center; padding:40px; color:var(--muted)">No emails in the queue yet.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($emails as $m): 
                        $statusCls = 'status-' . ($m['status'] ?? 'queued');
                    ?>
                        <tr>
                            <td>
                                <div style="font-weight:600; color:var(--text)"><?=e($m['to_email'] ?? '')?></div>
                            </td>
                            <td><div style="max-width:240px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap"><?=e($m['subject'] ?? '')?></div></td>
                            <td><span class="badge" style="font-size:11px"><?=e($m['template'] ?? '')?></span></td>
                            <td><span class="chip <?=$statusCls?>"><?=ucfirst($m['status'] ?? 'queued')?></span></td>
                            <td style="text-align:center"><?=e((string)($m['attempts'] ?? 0))?>/3</td>
                            <td style="font-size:12px; color:var(--muted)">
                                <?php 
                                    $ts = strtotime($m['created_at'] ?? '');
                                    echo $ts ? date('M j, H:i', $ts) : 'N/A';
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

<?php else: ?>
    <div class="card" style="padding:0; overflow:hidden;">
        <div style="padding:16px 20px; border-bottom:1px solid var(--border); background:#f8fafc">
            <h3 style="margin:0; font-size:16px">In-App Notification History</h3>
        </div>
        <div style="overflow-x:auto">
            <table class="striped">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Category</th>
                        <th>Content</th>
                        <th>Status</th>
                        <th>Data</th>
                        <th>Sent At</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($notifs)): ?>
                        <tr><td colspan="6" style="text-align:center; padding:40px; color:var(--muted)">No notifications have been sent yet.</td></tr>
                    <?php endif; ?>
                    <?php foreach ($notifs as $n): 
                        $isRead = ($n['status'] ?? 'unread') === 'read';
                    ?>
                        <tr class="<?=$isRead?'notif-read':'notif-unread'?>">
                            <td><div style="font-weight:600"><?=e($n['full_name'] ?? 'Unknown')?></div></td>
                            <td><span class="badge" style="font-size:11px"><?=e($n['type'] ?? 'general')?></span></td>
                            <td>
                                <div style="font-weight:600; font-size:13px"><?=e($n['title'] ?? '')?></div>
                                <div style="font-size:12px; color:var(--muted); max-width:300px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis"><?=e($n['body'] ?? '')?></div>
                            </td>
                            <td>
                                <span class="chip <?=$isRead?'chip-draft':'chip-processing'?>">
                                    <?=$isRead?'Read':'Unread'?>
                                </span>
                            </td>
                            <td>
                                <?php if (!empty($n['data_json']) && $n['data_json'] !== '[]'): ?>
                                    <div class="data-preview"><?=e($n['data_json'])?></div>
                                <?php else: ?>
                                    <span class="muted" style="font-size:11px">None</span>
                                <?php endif; ?>
                            </td>
                            <td style="font-size:12px; color:var(--muted)">
                                <?php 
                                    $ts = strtotime($n['created_at'] ?? '');
                                    echo $ts ? date('M j, H:i', $ts) : 'N/A';
                                ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<?php include __DIR__ . '/../includes/footer.php'; ?>
