<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

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

checkAuth();
$conn = getConnection();

if (!function_exists('e')) {
    function e($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

$message = '';
$inserted = 0;
$updated = 0;
$skipped = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    if (!is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
        $message = 'File upload tidak valid.';
    } else {
        $tmp = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($tmp, 'r');

        if (!$handle) {
            $message = 'Gagal membuka file CSV.';
        } else {
            $header = fgetcsv($handle);

            if (!$header) {
                $message = 'Header CSV tidak ditemukan.';
            } else {
                $header = array_map(static fn($v) => trim((string)$v), $header);

                while (($row = fgetcsv($handle)) !== false) {
                    if (count(array_filter($row, fn($v) => trim((string)$v) !== '')) === 0) {
                        continue;
                    }

                    $data = array_combine($header, $row);
                    if (!$data) {
                        $skipped++;
                        continue;
                    }

                    $roomNumber    = trim((string)($data['Nomor Ruangan'] ?? ''));
                    $poliName      = trim((string)($data['Nama Poli/Ruangan'] ?? ''));
                    $wing          = trim((string)($data['Wing'] ?? ''));
                    $scheduleCode  = trim((string)($data['Schedule ID'] ?? ''));
                    $doctorName    = trim((string)($data['Nama Dokter'] ?? ''));
                    $practiceDays  = trim((string)($data['Hari Praktek'] ?? ''));
                    $practiceHours = trim((string)($data['Jam Praktek'] ?? ''));

                    if ($doctorName === '' || $poliName === '') {
                        $skipped++;
                        continue;
                    }

                    $check = $conn->prepare("
                        SELECT id
                        FROM polyclinic_doctors
                        WHERE doctor_name = ? AND poli_name = ?
                        LIMIT 1
                    ");
                    if (!$check) {
                        $skipped++;
                        continue;
                    }

                    $check->bind_param("ss", $doctorName, $poliName);
                    $check->execute();
                    $res = $check->get_result();

                    if ($res && $existing = $res->fetch_assoc()) {
                        $doctorId = (int)$existing['id'];

                        $up = $conn->prepare("
                            UPDATE polyclinic_doctors
                            SET room_number = ?, wing = ?, schedule_code = ?,
                                practice_days = ?, practice_hours = ?, is_active = 1
                            WHERE id = ?
                        ");
                        if ($up) {
                            $up->bind_param(
                                "sssssi",
                                $roomNumber,
                                $wing,
                                $scheduleCode,
                                $practiceDays,
                                $practiceHours,
                                $doctorId
                            );
                            $up->execute();
                            $up->close();
                            $updated++;
                        } else {
                            $skipped++;
                        }
                    } else {
                        $ins = $conn->prepare("
                            INSERT INTO polyclinic_doctors
                            (
                                room_number, poli_name, wing, schedule_code,
                                doctor_name, practice_days, practice_hours, is_active
                            )
                            VALUES (?, ?, ?, ?, ?, ?, ?, 1)
                        ");
                        if ($ins) {
                            $ins->bind_param(
                                "sssssss",
                                $roomNumber,
                                $poliName,
                                $wing,
                                $scheduleCode,
                                $doctorName,
                                $practiceDays,
                                $practiceHours
                            );
                            $ins->execute();
                            $ins->close();
                            $inserted++;
                        } else {
                            $skipped++;
                        }
                    }

                    $check->close();
                }

                fclose($handle);

                if (function_exists('logActivity')) {
                    @logActivity(
                        'import',
                        'laporan_harian_poliklinik',
                        0,
                        "Import master dokter poliklinik. Inserted: {$inserted}, Updated: {$updated}, Skipped: {$skipped}"
                    );
                }

                $message = "Import selesai. Inserted: {$inserted}, Updated: {$updated}, Skipped: {$skipped}";
            }
        }
    }
}
?>
<div class="max-w-2xl mx-auto p-4 md:p-6">
    <div class="bg-white rounded-2xl shadow p-6">
        <h1 class="text-2xl font-bold mb-4">Import Dokter Poliklinik</h1>
        <p class="text-slate-600 mb-4">
            Format kolom CSV:
            <b>Nomor Ruangan</b>, <b>Nama Poli/Ruangan</b>, <b>Wing</b>, <b>Schedule ID</b>,
            <b>Nama Dokter</b>, <b>Hari Praktek</b>, <b>Jam Praktek</b>.
        </p>

        <?php if ($message !== ''): ?>
            <div class="mb-4 p-3 rounded-xl bg-blue-50 text-blue-700 border border-blue-200">
                <?= e($message) ?>
            </div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data" class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">Upload CSV</label>
                <input type="file" name="csv_file" accept=".csv" required class="w-full border rounded-xl px-3 py-2">
            </div>

            <div class="flex gap-2">
                <button type="submit" class="px-4 py-2 rounded-xl bg-blue-600 text-white hover:bg-blue-700">
                    Import Sekarang
                </button>
                <a href="index.php?module=laporan_harian_poliklinik" class="px-4 py-2 rounded-xl border border-slate-300 hover:bg-slate-50">
                    Kembali ke Modul
                </a>
            </div>
        </form>
    </div>
</div>