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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'user') {
    header("Location: ../user_login.php");
    exit;
}

$templates = [];
try {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM sms_templates WHERE status = 'active' AND (owner_type = 'admin' OR (owner_type = 'user' AND owner_id = ?)) ORDER BY title");
    $stmt->execute([$_SESSION['user_id']]);
    $templates = $stmt->fetchAll() ?: [];
} catch (PDOException $e) {
    try {
        $stmt = $pdo->query("SELECT * FROM sms_templates WHERE status = 'active'");
        $templates = $stmt->fetchAll() ?: [];
    } catch (PDOException $e2) {
    }
}

$user_groups = get_active_contact_groups('user', $_SESSION['user_id']);

$metrics = ['total_sms' => 0, 'sms_sent' => 0, 'sms_failed' => 0, 'balance' => 0, 'total_contacts' => 0];
try {
    $statistics = get_user_sms_statistics($_SESSION['user_id']);
    $metrics['total_sms'] = $statistics['total_sms'];
    $metrics['sms_sent'] = $statistics['sms_sent'];
    $metrics['sms_failed'] = $statistics['sms_failed'];
    $stmt = $pdo->prepare("SELECT COUNT(DISTINCT recipient_number) FROM sms_logs WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $metrics['total_contacts'] = $stmt->fetchColumn();
    $metrics['balance'] = get_balance();
} catch (PDOException $e) {
}

$traffic_data = [];
try {
    $stmt = $pdo->prepare("SELECT DATE(sent_at) as date, COUNT(*) as count FROM sms_logs WHERE user_id = ? AND sent_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY DATE(sent_at) ORDER BY DATE(sent_at) ASC");
    $stmt->execute([$_SESSION['user_id']]);
    $traffic_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
}

$success_rate = $metrics['total_sms'] > 0 ? round(($metrics['sms_sent'] / $metrics['total_sms']) * 100, 1) : 0;

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

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

<!-- 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">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-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 $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-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="stat-label mb-1">Contacts</p>
                        <h3 class="stat-value mb-0"><?php echo $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-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>

<!-- Quick Actions -->
<div class="row">
    <div class="col-12 fade-in-up">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title mb-0">⚡ Quick Actions</h3>
            </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">View templates</small>
                            </div>
                        </a>
                    </div>
                    <div class="col-md-4">
                        <a href="monitor.php" style="text-decoration:none;">
                            <div class="card quick-action-card">
                                <div class="action-icon" style="background:linear-gradient(135deg,#F59E0B,#D97706);"><i
                                        class="fe fe-activity"></i></div>
                                <h6 class="mb-1">History</h6>
                                <small class="text-muted">View sent SMS</small>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Charts -->
<div class="row">
    <div class="col-xl-9 fade-in-up">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title mb-0">📈 My SMS Traffic (30 Days)</h3>
            </div>
            <div class="card-body">
                <canvas id="trafficChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-xl-3 fade-in-up">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title mb-0">📊 Delivery</h3>
            </div>
            <div class="card-body">
                <canvas id="statusChart" style="height: 220px;"></canvas>
                <div class="row mt-3 text-center">
                    <div class="col-6">
                        <h5 class="mb-0" style="color:var(--ui-emerald);"><?php echo $metrics['sms_sent']; ?></h5>
                        <small class="text-muted">Sent</small>
                    </div>
                    <div class="col-6">
                        <h5 class="mb-0" style="color:var(--ui-rose);"><?php echo $metrics['sms_failed']; ?></h5>
                        <small class="text-muted">Failed</small>
                    </div>
                </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</label>
                                <select class="form-control" name="contact_group[]" multiple>
                                    <?php foreach ($user_groups as $ug): ?>
                                        <option value="<?php echo $ug['id']; ?>">
                                            <?php echo htmlspecialchars($ug['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-4">
                            <label class="form-label">Info</label>
                            <div style="font-size:0.78rem;">
                                <span id="sms-encoding" class="fw-bold">GSM</span> |
                                <span id="sms-count" class="fw-bold">0</span> chars |
                                <span id="sms-parts" class="fw-bold">0</span> parts
                            </div>
                        </div>
                    </div>
                    <?php if (!empty($templates)): ?>
                        <div class="form-group mb-3">
                            <label class="form-label">Template</label>
                            <select class="form-select" id="templateSelect">
                                <option value="">-- Select --</option>
                                <?php foreach ($templates as $t): ?>
                                    <option value="<?php echo htmlspecialchars($t['message']); ?>">
                                        <?php echo htmlspecialchars($t['title']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                    <div class="form-group mb-3">
                        <label class="form-label">Message</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</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="<?php echo asset_url('assets/js/pages/sms_logic_v4.js'); ?>"></script>
<link href="<?php echo asset_url('assets/plugins/select2/css/select2.min.css'); ?>" rel="stylesheet" />
<script src="<?php echo asset_url('assets/plugins/select2/select2.full.min.js'); ?>"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.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: '<?php echo 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
            }
        });

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

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

        // Traffic Chart
        var trafficData = <?php echo json_encode($traffic_data); ?>;
        var labels = [], data = [];
        var today = new Date();
        for (var i = 29; i >= 0; i--) {
            var d = new Date(today); d.setDate(d.getDate() - i);
            var ds = d.toISOString().split('T')[0];
            labels.push(d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
            var f = trafficData.find(function (x) { return x.date === ds; });
            data.push(f ? parseInt(f.count) : 0);
        }

        new Chart(document.getElementById('trafficChart'), {
            type: 'line',
            data: {
                labels: labels, datasets: [{
                    label: 'SMS', data: data,
                    borderColor: '#4F46E5', backgroundColor: 'rgba(79,70,229,0.08)',
                    borderWidth: 2, fill: true, tension: 0.4, pointRadius: 2
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { y: { beginAtZero: true, ticks: { precision: 0 } }, x: { grid: { display: false } } }
            }
        });

        // Donut
        var sent = <?php echo (int) $metrics['sms_sent']; ?>, failed = <?php echo (int) $metrics['sms_failed']; ?>;
        new Chart(document.getElementById('statusChart'), {
            type: 'doughnut',
            data: {
                labels: (sent == 0 && failed == 0) ? ['No Data'] : ['Sent', 'Failed'],
                datasets: [{
                    data: (sent == 0 && failed == 0) ? [1] : [sent, failed],
                    backgroundColor: (sent == 0 && failed == 0) ? ['#E2E8F0'] : ['#10B981', '#F43F5E'], borderWidth: 0
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '72%',
                plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } }
            }
        });
    });
</script>

<?php require_once '../includes/footer.php'; ?>