<?php
// public/admin/dashboard.php — V2 Modern Redesign
require_once '../../functions.php';
check_admin_auth();

// Fetch Templates for Modal
$templates = [];
try {
    global $pdo;
    $stmt = $pdo->query("SELECT * FROM sms_templates WHERE status = 'active'");
    if ($stmt)
        $templates = $stmt->fetchAll() ?: [];
} catch (PDOException $e) {
}

$admin_groups = get_active_contact_groups('admin');
$delivery_stats = get_sms_delivery_stats();

// SSR Metrics
$metrics = ['total_contacts' => 0, 'total_sms' => 0, 'balance' => 0, 'sent' => 0, 'total_users' => 0, 'failed' => 0, 'total_templates' => 0];
try {
    $stmt = $pdo->query("SELECT COUNT(*) FROM users");
    $metrics['total_users'] = $stmt->fetchColumn();
    $stmt = $pdo->query("SELECT COUNT(DISTINCT recipient_number) FROM sms_logs");
    $metrics['total_contacts'] = $stmt->fetchColumn();
    $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs");
    $metrics['total_sms'] = $stmt->fetchColumn();
    $metrics['balance'] = get_balance();
    $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE status='sent'");
    $metrics['sent'] = $stmt->fetchColumn();
    $stmt = $pdo->query("SELECT COUNT(*) FROM sms_logs WHERE status='failed'");
    $metrics['failed'] = $stmt->fetchColumn();
    try {
        $stmt = $pdo->query("SELECT COUNT(*) FROM sms_templates");
        $metrics['total_templates'] = $stmt->fetchColumn();
    } catch (Exception $e) {
    }
} catch (PDOException $e) {
}

// User traffic data for chart
$nvd3_data = [];
try {
    $stmt = $pdo->prepare("SELECT u.username, COUNT(l.id) as sms_count FROM sms_logs l JOIN users u ON l.user_id = u.id WHERE l.sent_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY l.user_id ORDER BY sms_count DESC LIMIT 8");
    $stmt->execute();
    $db_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $labels_arr = [];
    $values_arr = [];
    if ($db_data) {
        foreach ($db_data as $row) {
            $labels_arr[] = $row['username'];
            $values_arr[] = (int) $row['sms_count'];
        }
    }
} catch (Exception $e) {
}

// Recent activity
$recent_logs = [];
try {
    $stmt = $pdo->query("SELECT l.*, u.username FROM sms_logs l LEFT JOIN users u ON l.user_id = u.id ORDER BY l.sent_at DESC LIMIT 8");
    $recent_logs = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Exception $e) {
}

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

$success_rate = $delivery_stats['total'] > 0 ? round(($delivery_stats['sent'] / $delivery_stats['total']) * 100, 1) : 0;

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
require_once '../includes/navbar.php';
?>

<!-- PAGE-HEADER -->
<div class="page-header">
    <h1 class="page-title">Dashboard</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="javascript:void(0)">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">Dashboard</li>
        </ol>
    </div>
</div>

<!-- ROW-1: Gradient Stat Cards -->
<div class="row">
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-1">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Total Balance</p>
                        <h3 class="stat-value mb-0">৳ <?php echo number_format((float) $metrics['balance'], 2); ?></h3>
                    </div>
                    <i class="fe fe-dollar-sign stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Total Contacts</p>
                        <h3 class="stat-value mb-0 count-up" data-target="<?php echo $metrics['total_contacts']; ?>">
                            <?php echo number_format($metrics['total_contacts']); ?></h3>
                    </div>
                    <i class="fe fe-users stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-3">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Total SMS</p>
                        <h3 class="stat-value mb-0 count-up" data-target="<?php echo $metrics['total_sms']; ?>">
                            <?php echo number_format($metrics['total_sms']); ?></h3>
                    </div>
                    <i class="fe fe-message-square stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">SMS Sent</p>
                        <h3 class="stat-value mb-0 count-up" data-target="<?php echo $metrics['sent']; ?>">
                            <?php echo number_format($metrics['sent']); ?></h3>
                    </div>
                    <i class="fe fe-check-circle stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ROW-2: Secondary Stats -->
<div class="row">
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-5">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Total Users</p>
                        <h3 class="stat-value mb-0"><?php echo number_format($metrics['total_users']); ?></h3>
                    </div>
                    <i class="fe fe-user stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-6">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Templates</p>
                        <h3 class="stat-value mb-0"><?php echo number_format($metrics['total_templates']); ?></h3>
                    </div>
                    <i class="fe fe-layers stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-7">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Failed SMS</p>
                        <h3 class="stat-value mb-0"><?php echo number_format($metrics['failed']); ?></h3>
                    </div>
                    <i class="fe fe-x-circle stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-sm-6 col-12 fade-in-up">
        <div class="card stat-card stat-gradient-8">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Success Rate</p>
                        <h3 class="stat-value mb-0"><?php echo $success_rate; ?>%</h3>
                    </div>
                    <i class="fe fe-trending-up stat-icon"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ROW-3: Quick Actions + Delivery Chart -->
<div class="row">
    <div class="col-xl-8 fade-in-up">
        <div class="card">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">⚡ Quick Actions</h3>
                <div class="ms-auto">
                    <span
                        class="health-indicator <?php echo (float) $metrics['balance'] > 10 ? 'health-good' : 'health-warn'; ?>">
                        ● API <?php echo (float) $metrics['balance'] > 0 ? 'Connected' : 'Check Balance'; ?>
                    </span>
                </div>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <div class="card quick-action-card" data-bs-toggle="modal" data-bs-target="#sendSmsModal">
                            <div class="action-icon" style="background:linear-gradient(135deg,#4F46E5,#7C3AED);">
                                <i class="fe fe-send"></i>
                            </div>
                            <h6 class="mb-1">Send SMS</h6>
                            <small class="text-muted">Quick message</small>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <a href="templates.php" style="text-decoration:none;">
                            <div class="card quick-action-card">
                                <div class="action-icon" style="background:linear-gradient(135deg,#10B981,#059669);">
                                    <i class="fe fe-layers"></i>
                                </div>
                                <h6 class="mb-1">Templates</h6>
                                <small class="text-muted">Manage templates</small>
                            </div>
                        </a>
                    </div>
                    <div class="col-md-4">
                        <a href="ai_settings.php" style="text-decoration:none;">
                            <div class="card quick-action-card">
                                <div class="action-icon" style="background:linear-gradient(135deg,#7C3AED,#EC4899);">
                                    <i class="fe fe-cpu"></i>
                                </div>
                                <h6 class="mb-1">AI Generator</h6>
                                <small class="text-muted">AI templates</small>
                            </div>
                        </a>
                    </div>
                </div>

                <!-- Today's Summary -->
                <div class="stats-summary-bar mt-4">
                    <div class="stats-summary-item">
                        <div class="ss-value text-primary"><?php echo $today_stats['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_stats['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_stats['failed']; ?></div>
                        <div class="ss-label">Today Failed</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Delivery Rate -->
    <div class="col-xl-4 fade-in-up">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title mb-0">📊 Delivery Rate</h3>
            </div>
            <div class="card-body">
                <div class="chartjs-wrapper-demo">
                    <canvas id="statusChart" style="height: 220px;"></canvas>
                </div>
                <div class="row mt-3 text-center">
                    <div class="col-6">
                        <h5 class="mb-0 number-font" style="color:var(--ui-emerald);">
                            <?php echo number_format($delivery_stats['sent']); ?></h5>
                        <span class="text-muted fs-12">Sent</span>
                    </div>
                    <div class="col-6">
                        <h5 class="mb-0 number-font" style="color:var(--ui-rose);">
                            <?php echo number_format($delivery_stats['failed']); ?></h5>
                        <span class="text-muted fs-12">Failed</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ROW-4: Traffic Chart + Live Activity -->
<div class="row">
    <div class="col-xl-8 fade-in-up">
        <div class="card">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">📈 User SMS Traffic (Last 30 Days)</h3>
            </div>
            <div class="card-body">
                <canvas id="trafficChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-xl-4 fade-in-up">
        <div class="card">
            <div class="card-header d-flex align-items-center">
                <h3 class="card-title mb-0">🔴 Live Activity</h3>
                <span class="health-indicator health-good ms-auto" id="live-indicator">● Live</span>
            </div>
            <div class="card-body">
                <div class="activity-feed" id="activity-feed">
                    <?php if (empty($recent_logs)): ?>
                        <p class="text-muted text-center">No recent activity</p>
                    <?php else: ?>
                        <?php foreach ($recent_logs as $log): ?>
                            <div class="activity-item">
                                <div class="activity-dot <?php echo $log['status']; ?>"></div>
                                <div style="flex:1;min-width:0;">
                                    <div class="d-flex justify-content-between">
                                        <strong
                                            style="font-size:0.85rem;"><?php echo htmlspecialchars($log['username'] ?? 'System'); ?></strong>
                                        <small
                                            class="text-muted"><?php echo date('h:i A', strtotime($log['sent_at'])); ?></small>
                                    </div>
                                    <div style="font-size:0.8rem;color:#64748B;">
                                        → <?php echo htmlspecialchars($log['recipient_number']); ?>
                                    </div>
                                    <div
                                        style="font-size:0.75rem;color:#94A3B8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                                        <?php echo htmlspecialchars(substr($log['message_body'], 0, 50)); ?>...
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SEND SMS MODAL -->
<div class="modal fade" id="sendSmsModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header" style="background:linear-gradient(135deg,#4F46E5,#7C3AED);color:#fff;">
                <h5 class="modal-title"><i class="fe fe-send me-2"></i>Send SMS</h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="sendSmsForm" method="POST" action="<?php echo base_url('public/api/send_sms.php'); ?>">
                    <div class="form-group mb-3">
                        <label class="form-label">Mobile Numbers</label>
                        <select class="form-control select2-show-search" name="mobile_number[]"
                            multiple="multiple"></select>
                    </div>
                    <div class="row">
                        <div class="col-8">
                            <div class="form-group mb-3">
                                <label class="form-label">Contact Group (Optional)</label>
                                <select class="form-control" name="contact_group[]" multiple>
                                    <?php if (empty($admin_groups)): ?>
                                        <option disabled>No Active Groups</option>
                                    <?php else: ?>
                                        <?php foreach ($admin_groups as $ag): ?>
                                            <option value="<?php echo $ag['id']; ?>">
                                                <?php echo htmlspecialchars($ag['name']); ?></option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="form-group">
                                <label class="form-label">Message Info</label>
                                <p class="mb-0" style="font-size:0.8rem;">
                                    Encoding: <span id="sms-encoding" class="fw-bold">GSM_7BIT</span><br>
                                    Chars: <span id="sms-count" class="fw-bold">0</span> |
                                    Parts: <span id="sms-parts" class="fw-bold">0</span><br>
                                    Remaining: <span id="sms-remaining" class="fw-bold">160</span>
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="form-group mb-3">
                        <label class="form-label">Template (Optional)</label>
                        <select class="form-control form-select" id="templateSelect">
                            <option value="">-- Select Template --</option>
                            <?php foreach ($templates as $t): ?>
                                <option value="<?php echo htmlspecialchars($t['message']); ?>">
                                    <?php echo htmlspecialchars($t['title']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <label class="form-label">Message Body</label>
                        <textarea name="message" id="msgBody" class="form-control" rows="5" required></textarea>
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-modern-primary flex-grow-1">
                            <i class="fe fe-send me-2"></i>Send Message
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
    <script src="' . asset_url('assets/js/pages/sms_logic_v4.js') . '"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <link href="' . asset_url('assets/plugins/select2/css/select2.min.css') . '" rel="stylesheet" />
    <script src="' . asset_url('assets/plugins/select2/select2.full.min.js') . '"></script>
    <script>
    $(document).ready(function() {
        // Select2
        $(".select2-show-search").select2({
            tags: true, tokenSeparators: [",", " "], width: "100%",
            placeholder: "Enter mobile numbers...", minimumInputLength: 1,
            ajax: { url: "' . base_url("public/api/search_contacts.php") . '", dataType: "json", delay: 250,
                data: function(p) { return { term: p.term }; },
                processResults: function(d) { return { results: d.results }; }, cache: true
            }
        });

        // Template Select
        $("#templateSelect").change(function() { var m=$(this).val(); if(m) { $("#msgBody").val(m); $("#msgBody")[0].dispatchEvent(new Event("input")); } });

        // Animated Counters
        $(".count-up").each(function() {
            var target = parseInt($(this).data("target")) || 0;
            if (target > 0 && typeof animateCounter === "function") animateCounter(this, target);
        });

        // Delivery Rate Donut
        var dSent = ' . $delivery_stats['sent'] . ', dFailed = ' . $delivery_stats['failed'] . ';
        if (document.getElementById("statusChart")) {
            new Chart(document.getElementById("statusChart"), {
                type: "doughnut",
                data: {
                    labels: (dSent==0 && dFailed==0) ? ["No Data"] : ["Sent","Failed"],
                    datasets: [{ data: (dSent==0 && dFailed==0) ? [1] : [dSent, dFailed],
                        backgroundColor: (dSent==0 && dFailed==0) ? ["#E2E8F0"] : ["#10B981","#F43F5E"], borderWidth: 0 }]
                },
                options: { responsive: true, maintainAspectRatio: false, cutout: "72%",
                    plugins: { legend: { display: true, position: "bottom", labels: { padding: 15, font: { size: 12, family: "Inter" } } } } }
            });
        }

        // Traffic Bar Chart
        var tLabels = ' . json_encode($labels_arr) . ';
        var tValues = ' . json_encode($values_arr) . ';
        if (document.getElementById("trafficChart") && tLabels.length > 0) {
            new Chart(document.getElementById("trafficChart"), {
                type: "bar",
                data: { labels: tLabels, datasets: [{
                    label: "SMS Count", data: tValues,
                    backgroundColor: function(ctx) {
                        var g = ctx.chart.ctx.createLinearGradient(0,0,0,300);
                        g.addColorStop(0,"rgba(79,70,229,0.8)"); g.addColorStop(1,"rgba(139,92,246,0.3)");
                        return g;
                    },
                    borderRadius: 8, borderSkipped: false
                }]},
                options: { responsive: true, maintainAspectRatio: false,
                    plugins: { legend: { display: false } },
                    scales: { y: { beginAtZero: true, ticks: { precision: 0 }, grid: { color: "rgba(0,0,0,0.04)" } },
                        x: { grid: { display: false } } }
                }
            });
        }
    });
    </script>';
require_once '../includes/footer.php';
?>