<?php
require_once '../../config.php';
require_once '../../functions.php';

check_admin_auth();

// Fetch users for filter
$users_list = [];
try {
    $stmt = $pdo->query("SELECT id, username FROM users ORDER BY username");
    $users_list = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (PDOException $e) {
}

// Today stats
$today = ['total' => 0, 'sent' => 0, 'failed' => 0];
try {
    $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE DATE(sent_at) = CURDATE()");
    $today['total'] = $stmt->fetchColumn();
    $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE DATE(sent_at) = CURDATE() AND status='sent'");
    $today['sent'] = $stmt->fetchColumn();
    $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE DATE(sent_at) = CURDATE() AND status='failed'");
    $today['failed'] = $stmt->fetchColumn();
} catch (Exception $e) {
}
$rate = $today['total'] > 0 ? round(($today['sent'] / $today['total']) * 100, 1) : 0;

$pageTitle = "SMS Monitor - Admin";
include '../includes/header.php';
include '../includes/sidebar.php';
include '../includes/navbar.php';
?>

<div class="page-header">
    <h1 class="page-title">📡 SMS Monitor</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
            <li class="breadcrumb-item active">SMS Monitor</li>
        </ol>
    </div>
</div>

<!-- Summary Stats -->
<div class="stats-summary-bar fade-in-up">
    <div class="stats-summary-item">
        <div class="ss-value text-primary"><?php echo $today['total']; ?></div>
        <div class="ss-label">Today Total</div>
    </div>
    <div class="stats-summary-item">
        <div class="ss-value" style="color:var(--ui-emerald);"><?php echo $today['sent']; ?></div>
        <div class="ss-label">Today Sent</div>
    </div>
    <div class="stats-summary-item">
        <div class="ss-value" style="color:var(--ui-rose);"><?php echo $today['failed']; ?></div>
        <div class="ss-label">Today Failed</div>
    </div>
    <div class="stats-summary-item">
        <div class="ss-value" style="color:var(--ui-primary);"><?php echo $rate; ?>%</div>
        <div class="ss-label">Success Rate</div>
    </div>
</div>

<div class="row">
    <div class="col-12 fade-in-up">
        <div class="card mb-4">
            <div class="card-header d-flex align-items-center flex-wrap gap-2">
                <h3 class="card-title mb-0">SMS History — All Users</h3>
                <div class="ms-auto d-flex gap-2 align-items-center">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="autoRefreshToggle">
                        <label class="form-check-label" for="autoRefreshToggle"
                            style="font-size:0.8rem;">Auto-refresh</label>
                    </div>
                    <button class="btn btn-sm btn-outline-primary" id="manualRefresh"><i
                            class="fe fe-refresh-cw"></i></button>
                </div>
            </div>
            <div class="card-body">
                <!-- Filters -->
                <div class="filter-bar">
                    <div class="form-group">
                        <label class="form-label" style="font-size:0.75rem;">User</label>
                        <select class="form-select form-select-sm" id="filterUser" style="min-width:140px;">
                            <option value="">All Users</option>
                            <?php foreach ($users_list as $u): ?>
                                <option value="<?php echo $u['id']; ?>"><?php echo htmlspecialchars($u['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label" style="font-size:0.75rem;">Status</label>
                        <select class="form-select form-select-sm" id="filterStatus" style="min-width:100px;">
                            <option value="">All</option>
                            <option value="sent">Sent</option>
                            <option value="failed">Failed</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label" style="font-size:0.75rem;">From</label>
                        <input type="date" class="form-control form-control-sm" id="filterDateFrom">
                    </div>
                    <div class="form-group">
                        <label class="form-label" style="font-size:0.75rem;">To</label>
                        <input type="date" class="form-control form-control-sm" id="filterDateTo">
                    </div>
                    <div class="form-group" style="align-self:flex-end;">
                        <button class="btn btn-sm btn-modern-primary" id="applyFilters"><i
                                class="fe fe-filter me-1"></i>Filter</button>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="sms-monitor-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User / Status</th>
                                <th>Mobile / Actions</th>
                                <th>Message</th>
                                <th>Time</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
    <link href="' . asset_url('assets/plugins/datatable/css/dataTables.bootstrap5.css') . '" rel="stylesheet" />
    <link href="' . asset_url('assets/plugins/datatable/css/buttons.bootstrap5.min.css') . '" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <script src="' . asset_url('assets/plugins/datatable/js/jquery.dataTables.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/dataTables.bootstrap5.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/dataTables.buttons.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/buttons.bootstrap5.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/jszip.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/pdfmake/pdfmake.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/pdfmake/vfs_fonts.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/buttons.html5.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/buttons.print.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/js/buttons.colVis.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/dataTables.responsive.min.js') . '"></script>
    <script src="' . asset_url('assets/plugins/datatable/responsive.bootstrap5.min.js') . '"></script>

    <script>
    $(document).ready(function() {
        var autoRefreshInterval = null;
        
        var table = $("#sms-monitor-table").DataTable({
            processing: true, serverSide: true,
            ajax: {
                url: "' . base_url('public/api/get_monitor_logs.php') . '",
                type: "GET",
                data: function(d) {
                    d.user_filter = $("#filterUser").val();
                    d.status_filter = $("#filterStatus").val();
                    d.date_from = $("#filterDateFrom").val();
                    d.date_to = $("#filterDateTo").val();
                }
            },
            columns: [
                { data: 0, responsivePriority: 1 },
                { data: 1, responsivePriority: 2 },
                { data: 2, responsivePriority: 3 },
                { data: 3, orderable: false, responsivePriority: 4 },
                { data: 4, responsivePriority: 5 }
            ],
            order: [[0, "desc"]], pageLength: 25,
            lengthMenu: [[10,25,50,100,-1],[10,25,50,100,"All"]],
            language: {
                searchPlaceholder: "Search...", search: "",
                processing: "<div class=\"spinner-modern\" style=\"margin:20px auto;\"></div>"
            },
            dom: "Blfrtip",
            buttons: [
                { extend: "copy", className: "btn btn-sm btn-outline-primary" },
                { extend: "csv", className: "btn btn-sm btn-outline-primary" },
                { extend: "excel", className: "btn btn-sm btn-outline-primary" },
                { extend: "pdf", className: "btn btn-sm btn-outline-primary" },
                { extend: "print", className: "btn btn-sm btn-outline-primary" }
            ]
        });

        // Filter
        $("#applyFilters").click(function() { table.ajax.reload(); });
        
        // Manual refresh
        $("#manualRefresh").click(function() {
            table.ajax.reload(null, false);
            $(this).find("i").addClass("spin");
            setTimeout(function() { $("#manualRefresh i").removeClass("spin"); }, 1000);
        });

        // Auto-refresh
        $("#autoRefreshToggle").change(function() {
            if (this.checked) {
                autoRefreshInterval = setInterval(function() { table.ajax.reload(null, false); }, 15000);
            } else {
                clearInterval(autoRefreshInterval);
            }
        });
    });
    </script>
    <style>.spin{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}</style>
';
include '../includes/footer.php';
?>