<?php
require_once 'db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$instansi_id = $_SESSION['instansi_id'];

// Ambil data instansi
$stmt_inst = $pdo->prepare("SELECT nama_instansi, logo_path FROM instansi WHERE id = ?");
$stmt_inst->execute([$instansi_id]);
$inst_data = $stmt_inst->fetch(PDO::FETCH_ASSOC);
$nama_instansi = $inst_data['nama_instansi'] ?? "Instansi ID $instansi_id";
$logo_path = !empty($inst_data['logo_path']) ? $inst_data['logo_path'] : '';

// Ambil data SKPD untuk dropdown filter
$stmt_skpd = $pdo->prepare("SELECT id, nama_skpd FROM skpd WHERE instansi_id = ? AND status = 'aktif' ORDER BY nama_skpd ASC");
$stmt_skpd->execute([$instansi_id]);
$skpd_list = $stmt_skpd->fetchAll(PDO::FETCH_ASSOC);

require_once 'layout_header.php';
?>

<!-- Loading Progress -->
<div id="page-loader" style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 60vh;">
    <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;" role="status"></div>
    <h4 class="mt-4 text-muted fw-bold">Memuat Analisis Tren...</h4>
</div>

<div id="page-content" style="display: none;">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-3">
        <div>
            <h4 class="fw-bold m-0 text-slate-800">Grafik Tren Sentimen</h4>
            <p class="text-muted small m-0">Pantau pergerakan opini publik dan sentimen dari waktu ke waktu</p>
        </div>
        <div>
            <span class="badge bg-primary rounded-pill px-3 py-2" style="font-size: 0.9rem;">
                <i class="fas fa-building me-1"></i> <?= htmlspecialchars($nama_instansi) ?>
            </span>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="card shadow-sm border-0 mb-4 animate-up delay-2">
        <div class="card-body">
            <form id="filterForm" class="row g-3 align-items-end">
                <div class="col-md-2">
                    <label class="form-label fw-bold text-muted small mb-1">Periode</label>
                    <select name="periode" id="filterPeriode" class="form-select border-0 bg-light">
                        <option value="harian" selected>Harian</option>
                        <option value="mingguan">Mingguan</option>
                        <option value="bulanan">Bulanan</option>
                        <option value="tahunan">Tahunan</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold text-muted small mb-1">Tanggal Mulai</label>
                    <input type="date" name="start_date" id="filterStart" class="form-control border-0 bg-light" value="<?= date('Y-m-d', strtotime('-30 days')) ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold text-muted small mb-1">Tanggal Akhir</label>
                    <input type="date" name="end_date" id="filterEnd" class="form-control border-0 bg-light" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label fw-bold text-muted small mb-1">Filter SKPD</label>
                    <select name="skpd_id" id="filterSkpd" class="form-select border-0 bg-light">
                        <option value="">Semua SKPD</option>
                        <?php foreach($skpd_list as $skpd): ?>
                            <option value="<?= $skpd['id'] ?>"><?= htmlspecialchars($skpd['nama_skpd']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary w-100 fw-bold shadow-sm" id="btnFilter">
                        <i class="fas fa-filter"></i>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Chart Container -->
    <div class="card shadow-sm border-0 animate-up delay-3">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap">
                <h5 class="card-title fw-bold m-0"><i class="fa-solid fa-chart-area text-info me-2"></i> Pergerakan Sentimen Opini Publik</h5>
                <span class="badge bg-light text-dark fw-bold rounded-pill px-3 py-2 border" id="chartPeriodLabel">
                    <i class="fa-solid fa-calendar-alt me-1"></i> 30 Hari Terakhir
                </span>
            </div>
            
            <div id="trendChartLoading" style="height: 400px; display: flex; justify-content: center; align-items: center;">
                <div class="spinner-grow text-info" role="status">
                  <span class="visually-hidden">Loading...</span>
                </div>
            </div>
            
            <div id="trendChartContainer" style="display: none;">
                <div id="trendChart" class="apex-charts" dir="ltr" style="height: 400px;"></div>
            </div>
        </div>
    </div>
</div>

<script>
    let trendChartInstance = null;

    $(document).ready(function() {
        $('#page-loader').hide();
        $('#page-content').fadeIn('slow');
        
        // Inisialisasi awal
        loadChartData();
        
        // Handle Submit Form
        $('#filterForm').on('submit', function(e) {
            e.preventDefault();
            loadChartData();
        });
        
        // Auto adjust date inputs based on period selection for better UX
        $('#filterPeriode').on('change', function() {
            let val = $(this).val();
            let startInput = $('#filterStart');
            let endInput = $('#filterEnd');
            
            let today = new Date();
            let endDateStr = today.toISOString().split('T')[0];
            
            let startDateStr = '';
            if(val === 'harian') {
                let lastMonth = new Date();
                lastMonth.setDate(today.getDate() - 30);
                startDateStr = lastMonth.toISOString().split('T')[0];
            } else if(val === 'mingguan') {
                let last3Months = new Date();
                last3Months.setMonth(today.getMonth() - 3);
                startDateStr = last3Months.toISOString().split('T')[0];
            } else if(val === 'bulanan') {
                let lastYear = new Date();
                lastYear.setFullYear(today.getFullYear() - 1);
                startDateStr = lastYear.toISOString().split('T')[0];
            } else if(val === 'tahunan') {
                let last5Years = new Date();
                last5Years.setFullYear(today.getFullYear() - 5);
                startDateStr = last5Years.toISOString().split('T')[0];
            }
            
            startInput.val(startDateStr);
            endInput.val(endDateStr);
            
            // Auto trigger load
            loadChartData();
        });
    });

    function loadChartData() {
        $('#trendChartContainer').hide();
        $('#trendChartLoading').show();
        $('#btnFilter').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
        
        let formData = {
            periode: $('#filterPeriode').val(),
            start_date: $('#filterStart').val(),
            end_date: $('#filterEnd').val(),
            skpd_id: $('#filterSkpd').val()
        };
        
        // Update Label
        $('#chartPeriodLabel').html(`<i class="fa-solid fa-calendar-alt me-1"></i> ${formData.start_date} s/d ${formData.end_date}`);

        $.ajax({
            url: 'ajax_trend_sentimen.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(res) {
                $('#btnFilter').prop('disabled', false).html('<i class="fas fa-filter"></i>');
                $('#trendChartLoading').hide();
                $('#trendChartContainer').show();
                
                if(res.status === 'success') {
                    renderChart(res.labels, res.series);
                } else {
                    $('#trendChartContainer').html(`<div class="alert alert-danger">Error: ${res.message}</div>`);
                }
            },
            error: function() {
                $('#btnFilter').prop('disabled', false).html('<i class="fas fa-filter"></i>');
                $('#trendChartLoading').hide();
                $('#trendChartContainer').show().html(`<div class="alert alert-danger">Gagal mengambil data dari server.</div>`);
            }
        });
    }

    function renderChart(labels, seriesData) {
        if (trendChartInstance !== null) {
            trendChartInstance.destroy();
        }

        var options = {
            chart: {
                height: 400,
                type: 'area', // Area chart (Time Series style)
                toolbar: {
                    show: true,
                    tools: {
                        download: true,
                        selection: true,
                        zoom: true,
                        zoomin: true,
                        zoomout: true,
                        pan: true
                    }
                },
                animations: {
                    enabled: true,
                    easing: 'easeinout',
                    speed: 800
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                curve: 'smooth',
                width: 3
            },
            series: seriesData, // [{name: 'Positif', data: []}, {name: 'Negatif', data: []}, {name: 'Netral', data: []}]
            colors: ['#10b981', '#ef4444', '#94a3b8'], // Positif (Hijau), Negatif (Merah), Netral (Abu)
            xaxis: {
                categories: labels,
                tickAmount: 10,
                labels: {
                    style: {
                        fontSize: '12px',
                        fontWeight: 500
                    },
                    rotate: -45,
                    rotateAlways: false
                }
            },
            yaxis: {
                title: {
                    text: 'Jumlah Berita',
                    style: {
                        fontWeight: 600
                    }
                },
                min: 0,
                forceNiceScale: true
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.4,
                    opacityTo: 0.05,
                    stops: [0, 90, 100]
                }
            },
            tooltip: {
                shared: true,
                intersect: false,
                y: {
                    formatter: function (y) {
                        if (typeof y !== "undefined") {
                            return y.toFixed(0) + " Berita";
                        }
                        return y;
                    }
                }
            },
            legend: {
                position: 'top',
                horizontalAlign: 'right',
                fontSize: '14px',
                fontWeight: 600,
                markers: {
                    radius: 12
                }
            }
        };

        trendChartInstance = new ApexCharts(document.querySelector("#trendChart"), options);
        trendChartInstance.render();
    }
</script>

<?php require_once 'layout_footer.php'; ?>
