<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/functions.php';

$vendorAutoload = dirname(__DIR__, 2) . '/vendor/autoload.php';
if (file_exists($vendorAutoload)) {
    require_once $vendorAutoload;
}

if (function_exists('checkAuth')) {
    checkAuth();
}

if (!function_exists('ak_redirect')) {
    function ak_redirect(string $url): void
    {
        echo '<script>window.location.href=' . json_encode($url) . ';</script>';
        echo '<noscript><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '"></noscript>';
        exit;
    }
}

$conn = getConnection();

$analysisYear = (int)($_GET['year'] ?? date('Y'));
$view         = $_GET['view'] ?? 'dashboard';

ak_seed_monthly_rows($conn, $analysisYear);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['save_nurse_setting'])) {
        $unitIds      = $_POST['unit_id'] ?? [];
        $nurseCounts  = $_POST['nurse_count'] ?? [];
        $createdBy    = (int)($_SESSION['user_id'] ?? ($_SESSION['user']['id'] ?? 0));

        $stmt = $conn->prepare("
            INSERT INTO visit_analysis_nurse_settings
            (analysis_year, unit_id, nurse_count, created_by)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                nurse_count = VALUES(nurse_count),
                created_by  = VALUES(created_by)
        ");

        if ($stmt) {
            foreach ($unitIds as $index => $unitId) {
                $analysisYearParam = (int)$analysisYear;
                $unitIdParam       = (int)$unitId;
                $nurseCountParam   = (int)($nurseCounts[$index] ?? 0);
                $createdByParam    = (int)$createdBy;

                $stmt->bind_param("iiii", $analysisYearParam, $unitIdParam, $nurseCountParam, $createdByParam);
                $stmt->execute();
            }
            $stmt->close();
        }

        ak_redirect("?module=analisis_kunjungan&view=settings&year=" . $analysisYear . "&success=1");
    }

    if (isset($_POST['save_manual_visits'])) {
        $unitId      = (int)($_POST['unit_id'] ?? 0);
        $monthNums   = $_POST['month_num'] ?? [];
        $visitTotals = $_POST['visit_total'] ?? [];

        $stmt = $conn->prepare("
            UPDATE visit_analysis_monthly
            SET visit_total = ?, data_source = 'manual'
            WHERE analysis_year = ? AND unit_id = ? AND month_num = ?
        ");

        if ($stmt) {
            foreach ($monthNums as $i => $monthNum) {
                $visitTotalParam   = (int)($visitTotals[$i] ?? 0);
                $analysisYearParam = (int)$analysisYear;
                $unitIdParam       = (int)$unitId;
                $monthNumParam     = (int)$monthNum;

                $stmt->bind_param("iiii", $visitTotalParam, $analysisYearParam, $unitIdParam, $monthNumParam);
                $stmt->execute();
            }
            $stmt->close();
        }

        ak_redirect("?module=analisis_kunjungan&view=input&year=" . $analysisYear . "&unit_id=" . $unitId . "&success=1");
    }
}

$units                   = ak_get_units($conn);
$selectedUnitId          = (int)($_GET['unit_id'] ?? ($units[0]['id'] ?? 0));
$nurseSettings           = ak_get_nurse_settings($conn, $analysisYear);
$dashboardRows           = ak_get_dashboard_rows($conn, $analysisYear);
$chartData               = ak_get_monthly_chart_data($conn, $analysisYear, $selectedUnitId);
$manualRows              = ak_get_manual_rows($conn, $analysisYear, $selectedUnitId);
$selectedUnitNurseCount  = ak_get_unit_nurse_count($conn, $analysisYear, $selectedUnitId);
$unitMonthlyDetail       = ak_get_unit_monthly_detail($conn, $analysisYear, $selectedUnitId);

$selectedUnitName = '-';
foreach ($units as $unit) {
    if ((int)$unit['id'] === $selectedUnitId) {
        $selectedUnitName = $unit['name'];
        break;
    }
}

$grandTotalVisits = 0;
$grandTotalNurses = 0;
$highestUnit      = '-';
$highestVisits    = -1;

foreach ($dashboardRows as $row) {
    $grandTotalVisits += (int)$row['total_visits'];
    $grandTotalNurses += (int)$row['nurse_count'];

    if ((int)$row['total_visits'] > $highestVisits) {
        $highestVisits = (int)$row['total_visits'];
        $highestUnit   = $row['unit_name'];
    }
}

$grandRatio = $grandTotalNurses > 0 ? round($grandTotalVisits / $grandTotalNurses, 2) : 0;
?>

<div class="space-y-6">
    <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
                <h1 class="text-2xl font-bold text-slate-800">Analisis Kunjungan Pasien Keperawatan</h1>
                <p class="text-slate-500 mt-1">
                    Periode otomatis: Desember tahun sebelumnya sampai November tahun aktif
                </p>
            </div>

            <div class="flex flex-wrap gap-2">
                <form method="get" class="flex flex-wrap items-center gap-3">
                    <input type="hidden" name="module" value="analisis_kunjungan">
                    <input type="hidden" name="view" value="<?= ak_e($view) ?>">

                    <label class="text-sm font-medium text-slate-700">Tahun Analisis</label>
                    <input
                        type="number"
                        name="year"
                        value="<?= $analysisYear ?>"
                        class="border border-slate-300 rounded-xl px-4 py-2 w-32 focus:outline-none focus:ring-2 focus:ring-teal-500"
                    >
                    <button class="bg-teal-700 hover:bg-teal-800 text-white px-4 py-2 rounded-xl font-semibold">
                        Tampilkan
                    </button>
                </form>

                <a href="?module=analisis_kunjungan&action=export_docx&year=<?= $analysisYear ?>"
                   class="bg-blue-700 hover:bg-blue-800 text-white px-4 py-2 rounded-xl font-semibold">
                    Export DOCX
                </a>
            </div>
        </div>
    </div>

    <div class="flex flex-wrap gap-2">
        <a href="?module=analisis_kunjungan&view=dashboard&year=<?= $analysisYear ?>"
           class="px-4 py-2 rounded-xl font-semibold <?= $view === 'dashboard' ? 'bg-teal-700 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
            Dashboard
        </a>

        <a href="?module=analisis_kunjungan&view=settings&year=<?= $analysisYear ?>"
           class="px-4 py-2 rounded-xl font-semibold <?= $view === 'settings' ? 'bg-teal-700 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
            Setting Jumlah Perawat
        </a>

        <a href="?module=analisis_kunjungan&view=input&year=<?= $analysisYear ?>"
           class="px-4 py-2 rounded-xl font-semibold <?= $view === 'input' ? 'bg-teal-700 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
            Input Manual
        </a>
    </div>

    <?php if ($view === 'dashboard'): ?>
        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <div class="text-slate-500 text-sm">Total Kunjungan</div>
                <div class="text-3xl font-bold text-slate-800 mt-2"><?= number_format($grandTotalVisits, 0, ',', '.') ?></div>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <div class="text-slate-500 text-sm">Total Perawat</div>
                <div class="text-3xl font-bold text-slate-800 mt-2"><?= number_format($grandTotalNurses, 0, ',', '.') ?></div>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <div class="text-slate-500 text-sm">Rata-rata Kunjungan / Perawat</div>
                <div class="text-3xl font-bold text-slate-800 mt-2"><?= number_format($grandRatio, 2, ',', '.') ?></div>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <div class="text-slate-500 text-sm">Unit Tertinggi</div>
                <div class="text-2xl font-bold text-slate-800 mt-2"><?= ak_e($highestUnit) ?></div>
            </div>
        </div>

        <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
                    <h2 class="text-lg font-bold text-slate-800">Grafik Kunjungan Bulanan</h2>

                    <form method="get" class="flex items-center gap-3">
                        <input type="hidden" name="module" value="analisis_kunjungan">
                        <input type="hidden" name="view" value="dashboard">
                        <input type="hidden" name="year" value="<?= $analysisYear ?>">

                        <select name="unit_id" class="border border-slate-300 rounded-xl px-4 py-2" onchange="this.form.submit()">
                            <?php foreach ($units as $unit): ?>
                                <option value="<?= (int)$unit['id'] ?>" <?= $selectedUnitId === (int)$unit['id'] ? 'selected' : '' ?>>
                                    <?= ak_e($unit['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </div>

                <div class="relative w-full overflow-x-auto">
                    <canvas id="visitChart" height="95"></canvas>
                </div>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <div class="flex items-center justify-between mb-4">
                    <h2 class="text-lg font-bold text-slate-800">Grafik Rasio Pasien : Perawat</h2>
                    <div class="text-sm text-slate-500"><?= ak_e($selectedUnitName) ?></div>
                </div>

                <div class="relative w-full overflow-x-auto">
                    <canvas id="ratioChart" height="95"></canvas>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 overflow-x-auto">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-lg font-bold text-slate-800">Dashboard Bulanan Unit - <?= ak_e($selectedUnitName) ?></h2>
                <div class="text-sm text-slate-500">Rasio = Kunjungan / Jumlah Perawat</div>
            </div>

            <table class="min-w-full text-sm">
                <thead>
                    <tr class="bg-slate-100 text-slate-700">
                        <th class="px-4 py-3 text-left">No</th>
                        <th class="px-4 py-3 text-left">Periode</th>
                        <th class="px-4 py-3 text-right">Kunjungan</th>
                        <th class="px-4 py-3 text-right">Jumlah Perawat</th>
                        <th class="px-4 py-3 text-right">Rasio Pasien : Perawat</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($unitMonthlyDetail as $i => $row): ?>
                        <tr class="border-b border-slate-100 hover:bg-slate-50">
                            <td class="px-4 py-3"><?= $i + 1 ?></td>
                            <td class="px-4 py-3 font-medium"><?= ak_e($row['period_label']) ?></td>
                            <td class="px-4 py-3 text-right"><?= number_format((int)$row['visit_total'], 0, ',', '.') ?></td>
                            <td class="px-4 py-3 text-right"><?= number_format((int)$row['nurse_count'], 0, ',', '.') ?></td>
                            <td class="px-4 py-3 text-right font-semibold text-teal-700">
                                <?= number_format((float)$row['ratio'], 2, ',', '.') ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 overflow-x-auto">
            <h2 class="text-lg font-bold text-slate-800 mb-4">Rekap Unit</h2>

            <table class="min-w-full text-sm">
                <thead>
                    <tr class="bg-slate-100 text-slate-700">
                        <th class="px-4 py-3 text-left">No</th>
                        <th class="px-4 py-3 text-left">Unit</th>
                        <th class="px-4 py-3 text-right">Total Kunjungan</th>
                        <th class="px-4 py-3 text-right">Jumlah Perawat</th>
                        <th class="px-4 py-3 text-right">Rata-rata Kunjungan / Perawat</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($dashboardRows as $i => $row): ?>
                        <tr class="border-b border-slate-100 hover:bg-slate-50">
                            <td class="px-4 py-3"><?= $i + 1 ?></td>
                            <td class="px-4 py-3 font-medium"><?= ak_e($row['unit_name']) ?></td>
                            <td class="px-4 py-3 text-right"><?= number_format((int)$row['total_visits'], 0, ',', '.') ?></td>
                            <td class="px-4 py-3 text-right"><?= number_format((int)$row['nurse_count'], 0, ',', '.') ?></td>
                            <td class="px-4 py-3 text-right"><?= number_format((float)$row['ratio'], 2, ',', '.') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script>
            const visitCtx = document.getElementById('visitChart');
            if (visitCtx) {
                new Chart(visitCtx, {
                    type: 'line',
                    data: {
                        labels: <?= json_encode(array_column($unitMonthlyDetail, 'period_label')) ?>,
                        datasets: [{
                            label: 'Kunjungan <?= ak_e($selectedUnitName) ?>',
                            data: <?= json_encode(array_column($unitMonthlyDetail, 'visit_total')) ?>,
                            borderWidth: 3,
                            tension: 0.3,
                            fill: false
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: true } },
                        scales: { y: { beginAtZero: true } }
                    }
                });
            }

            const ratioCtx = document.getElementById('ratioChart');
            if (ratioCtx) {
                new Chart(ratioCtx, {
                    type: 'bar',
                    data: {
                        labels: <?= json_encode(array_column($unitMonthlyDetail, 'period_label')) ?>,
                        datasets: [{
                            label: 'Rasio Pasien : Perawat <?= ak_e($selectedUnitName) ?>',
                            data: <?= json_encode(array_column($unitMonthlyDetail, 'ratio')) ?>,
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: true } },
                        scales: { y: { beginAtZero: true } }
                    }
                });
            }
        </script>
    <?php endif; ?>

    <?php if ($view === 'settings'): ?>
        <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
                <h2 class="text-lg font-bold text-slate-800">Setting Jumlah Perawat Tahun <?= $analysisYear ?></h2>

                <?php if (isset($_GET['success'])): ?>
                    <div class="text-green-700 bg-green-100 px-4 py-2 rounded-xl text-sm font-medium">
                        Data jumlah perawat berhasil disimpan
                    </div>
                <?php endif; ?>
            </div>

            <form method="post">
                <div class="overflow-x-auto">
                    <table class="min-w-full text-sm">
                        <thead>
                            <tr class="bg-slate-100 text-slate-700">
                                <th class="px-4 py-3 text-left">No</th>
                                <th class="px-4 py-3 text-left">Unit</th>
                                <th class="px-4 py-3 text-left">Jumlah Perawat</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($units as $i => $unit): ?>
                                <tr class="border-b border-slate-100">
                                    <td class="px-4 py-3"><?= $i + 1 ?></td>
                                    <td class="px-4 py-3 font-medium">
                                        <?= ak_e($unit['name']) ?>
                                        <input type="hidden" name="unit_id[]" value="<?= (int)$unit['id'] ?>">
                                    </td>
                                    <td class="px-4 py-3">
                                        <input
                                            type="number"
                                            name="nurse_count[]"
                                            min="0"
                                            value="<?= (int)($nurseSettings[$unit['id']] ?? 0) ?>"
                                            class="border border-slate-300 rounded-xl px-4 py-2 w-40 focus:outline-none focus:ring-2 focus:ring-teal-500"
                                        >
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-5">
                    <button type="submit" name="save_nurse_setting" value="1"
                            class="bg-teal-700 hover:bg-teal-800 text-white px-5 py-3 rounded-xl font-semibold">
                        Simpan Setting
                    </button>
                </div>
            </form>
        </div>
    <?php endif; ?>

    <?php if ($view === 'input'): ?>
        <div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5">
                <h2 class="text-lg font-bold text-slate-800 mb-4">Pilih Unit</h2>

                <div class="space-y-2">
                    <?php foreach ($units as $unit): ?>
                        <a href="?module=analisis_kunjungan&view=input&year=<?= $analysisYear ?>&unit_id=<?= (int)$unit['id'] ?>"
                           class="block px-4 py-3 rounded-xl font-medium <?= $selectedUnitId === (int)$unit['id'] ? 'bg-teal-700 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?>">
                            <?= ak_e($unit['name']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="bg-white rounded-2xl shadow-sm border border-slate-200 p-5 xl:col-span-2">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3 mb-4">
                    <h2 class="text-lg font-bold text-slate-800">
                        Input Manual Kunjungan - <?= ak_e($selectedUnitName) ?>
                    </h2>

                    <?php if (isset($_GET['success'])): ?>
                        <div class="text-green-700 bg-green-100 px-4 py-2 rounded-xl text-sm font-medium">
                            Data kunjungan berhasil disimpan
                        </div>
                    <?php endif; ?>
                </div>

                <?php if ($selectedUnitNurseCount <= 0): ?>
                    <div class="mb-4 bg-yellow-100 text-yellow-800 border border-yellow-200 rounded-xl p-4">
                        Jumlah perawat untuk unit ini belum diisi. Silakan isi dulu di tab <strong>Setting Jumlah Perawat</strong>.
                    </div>
                <?php endif; ?>

                <form method="post">
                    <input type="hidden" name="unit_id" value="<?= $selectedUnitId ?>">

                    <div class="overflow-x-auto">
                        <table class="min-w-full text-sm">
                            <thead>
                                <tr class="bg-slate-100 text-slate-700">
                                    <th class="px-4 py-3 text-left">Periode</th>
                                    <th class="px-4 py-3 text-left">Total Kunjungan</th>
                                    <th class="px-4 py-3 text-right">Jumlah Perawat</th>
                                    <th class="px-4 py-3 text-right">Rasio Pasien : Perawat</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($manualRows as $row): ?>
                                    <?php
                                        $visitTotal = (int)$row['visit_total'];
                                        $ratioMonthly = $selectedUnitNurseCount > 0 ? round($visitTotal / $selectedUnitNurseCount, 2) : 0;
                                    ?>
                                    <tr class="border-b border-slate-100">
                                        <td class="px-4 py-3 font-medium">
                                            <?= ak_e($row['period_label']) ?>
                                            <input type="hidden" name="month_num[]" value="<?= (int)$row['month_num'] ?>">
                                        </td>
                                        <td class="px-4 py-3">
                                            <input
                                                type="number"
                                                name="visit_total[]"
                                                min="0"
                                                value="<?= $visitTotal ?>"
                                                class="border border-slate-300 rounded-xl px-4 py-2 w-48 focus:outline-none focus:ring-2 focus:ring-teal-500"
                                            >
                                        </td>
                                        <td class="px-4 py-3 text-right">
                                            <?= number_format($selectedUnitNurseCount, 0, ',', '.') ?>
                                        </td>
                                        <td class="px-4 py-3 text-right font-semibold text-teal-700">
                                            <?= number_format($ratioMonthly, 2, ',', '.') ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-5">
                        <button type="submit" name="save_manual_visits" value="1"
                                class="bg-teal-700 hover:bg-teal-800 text-white px-5 py-3 rounded-xl font-semibold">
                            Simpan Kunjungan
                        </button>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>