<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pendaftaran Pasien - RS Poltekkes Kemenkes Semarang</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- FontAwesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <!-- AOS CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.css" rel="stylesheet">
    <!-- Select2 CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-5-theme/1.3.0/select2-bootstrap-5-theme.min.css" rel="stylesheet">
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">

    <style>
        html {
            scroll-behavior: smooth;
        }

        body {
            background-color: #f8fcff;
            font-family: 'Segoe UI', sans-serif;
            padding-top: 80px;
        }

        section[id] {
            scroll-margin-top: 90px;
        }

        .navbar {
            background-color: #0097B2;
        }

        .navbar-brand,
        .nav-link {
            color: #fff !important;
            font-weight: 600;
        }

        .navbar .navbar-toggler {
            border-color: rgba(255, 255, 255, .5);
        }

        .navbar .navbar-toggler-icon {
            background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(255,255,255,0.9)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
        }

        .hero {
            background: linear-gradient(rgba(0, 151, 178, .8), rgba(0, 151, 178, .8)),
                url('https://klinik-pratama.poltekkes-smg.id/storage/general/01K0S3X64EM9N1M5FGZKFDZTZD.jpg') center/cover no-repeat;
            color: #fff;
            min-height: 80vh;
            display: flex;
            align-items: center;
            text-align: center;
        }

        .hero h1 {
            font-size: 2.8rem;
            font-weight: 700;
        }

        .form-card {
            background: #fff;
            border-radius: 16px;
            padding: 30px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, .1);
        }

        .section-title {
            color: #0097B2;
            font-weight: 700;
        }

        .icon-box {
            background: #72E8D2;
            color: #0097B2;
            font-size: 2rem;
            border-radius: 12px;
            padding: 20px;
            display: inline-block;
            margin-bottom: 15px;
        }

        .mode-selector {
            margin-bottom: 30px;
        }

        .mode-btn {
            padding: 15px 30px;
            font-size: 1.1rem;
        }

        .pasien-form {
            display: none;
        }

        .pasien-form.active {
            display: block;
        }

        .kartu-antrian {
            background: linear-gradient(135deg, #0097B2, #72E8D2);
            color: white;
            border-radius: 15px;
            padding: 30px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            max-width: 400px;
            margin: 0 auto;
        }

        .nomor-antrian {
            font-size: 2rem;
            font-weight: 600;
            margin: 20px 0;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }

        .form-group {
            margin-bottom: 1.2rem;
        }

        .select2-container--bootstrap-5 .select2-selection {
            height: calc(1.5em + 1rem + 2px);
        }

        .info-reservasi {
            background: rgba(255, 255, 255, 0.2) !important;
            border: 1px solid rgba(255, 255, 255, 0.3) !important;
            backdrop-filter: blur(10px);
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            display: none;
        }

        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
    </style>
</head>

<body>

    <!-- Loading Overlay -->
    <div class="loading-overlay">
        <div class="spinner-border text-light" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg fixed-top">
        <div class="container">
            <a class="navbar-brand" href="#"><i class="fa-solid fa-hospital"></i> RS Poltekkes Kemenkes Semarang</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navmenu">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navmenu">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a href="#daftar" class="nav-link">Pendaftaran</a></li>
                    <li class="nav-item"><a href="#layanan" class="nav-link">Layanan</a></li>
                    <li class="nav-item"><a href="#kontak" class="nav-link">Kontak</a></li>
                    <li class="nav-item"><a href="#" class="nav-link" data-bs-toggle="modal" data-bs-target="#loginPetugasModal"><i class="fa-solid fa-user-shield"></i> Masuk</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Modal Login Petugas -->
    <div class="modal fade" id="loginPetugasModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-4 shadow">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fa-solid fa-user-shield"></i> Masuk</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-4">
                    <form id="formLoginPetugas" action="<?= base_url('auth/login_petugas_ajax'); ?>" method="post" novalidate>
                        <?php if ($this->config->item('csrf_protection')): ?>
                            <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="form-label"><i class="fa-solid fa-id-badge"></i> Username</label>
                            <input type="text" name="username" class="form-control" placeholder="Masukkan username" required>
                            <div class="invalid-feedback" data-error="username"></div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><i class="fa-solid fa-lock"></i> Password</label>
                            <input type="password" name="password" class="form-control" placeholder="Masukkan password" required>
                            <div class="invalid-feedback" data-error="password"></div>
                        </div>

                        <button type="submit" class="btn btn-primary w-100">
                            <span class="btn-text">Masuk</span>
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Hero -->
    <section class="hero">
        <div class="container" data-aos="fade-up">
            <h1>Selamat Datang </h1>
            <h1>Rumah Sakit Poltekkes Kemenkes Semarang</h1>
            <p class="lead">Pendaftaran pasien online dengan mudah, cepat, dan aman</p>
            <a href="#daftar" class="btn btn-light btn-lg mt-3"><i class="fa-solid fa-user-plus"></i> Daftar Sekarang</a>
        </div>
    </section>

    <!-- Form Pendaftaran Online -->
    <section id="daftar" class="py-5">
        <div class="container">
            <h2 class="section-title text-center mb-4" data-aos="zoom-in">Pendaftaran Online</h2>

            <!-- Mode Selection -->
            <div class="row justify-content-center mb-4">
                <div class="col-md-8 text-center">
                    <div class="mode-selector">
                        <h4 class="mb-3">Pilih Jenis Pendaftaran</h4>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-primary mode-btn active" data-mode="baru">
                                <i class="fa-solid fa-user-plus me-2"></i>Pasien Baru
                            </button>
                            <button type="button" class="btn btn-outline-primary mode-btn" data-mode="lama">
                                <i class="fa-solid fa-user-check me-2"></i>Pasien Lama
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Form Pasien Baru -->
            <div class="row justify-content-center">
                <div class="col-lg-10">
                    <div class="form-card pasien-form active" id="form-pasien-baru">
                        <h4 class="mb-4 text-center"><i class="fa-solid fa-user-plus me-2"></i>Formulir Pasien Baru</h4>

                        <form id="formDaftarBaru" method="post" action="<?= site_url('pendaftaran_online/simpan_pasien_baru') ?>">
                            <div class="row">
                                <!-- Data Diri -->
                                <div class="col-md-6">
                                    <h5 class="mb-3 border-bottom pb-2">Data Diri</h5>

                                    <div class="form-group">
                                        <label class="form-label">NIK <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="nik" maxlength="16" required 
                                               placeholder="16 digit NIK">
                                        <div class="invalid-feedback" data-error="nik"></div>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" name="nama_lengkap" required 
                                               placeholder="Nama lengkap sesuai KTP">
                                        <div class="invalid-feedback" data-error="nama_lengkap"></div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Tempat Lahir</label>
                                                <input type="text" class="form-control" name="tempat_lahir" 
                                                       placeholder="Kota tempat lahir">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Tanggal Lahir</label>
                                                <input type="date" class="form-control" name="tanggal_lahir">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Jenis Kelamin <span class="text-danger">*</span></label>
                                                <select class="form-control" name="jenis_kelamin" required>
                                                    <option value="">-- Pilih --</option>
                                                    <option value="L">Laki-laki</option>
                                                    <option value="P">Perempuan</option>
                                                </select>
                                                <div class="invalid-feedback" data-error="jenis_kelamin"></div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Golongan Darah</label>
                                                <select class="form-control" name="golongan_darah">
                                                    <option value="">-- Pilih --</option>
                                                    <option value="A">A</option>
                                                    <option value="B">B</option>
                                                    <option value="AB">AB</option>
                                                    <option value="O">O</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Alamat Lengkap</label>
                                        <textarea class="form-control" name="alamat" rows="2" 
                                                  placeholder="Alamat lengkap tempat tinggal"></textarea>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">No. Telepon/HP</label>
                                                <input type="text" class="form-control" name="no_telp" 
                                                       placeholder="08xxxxxxxxxx">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="form-label">Email</label>
                                                <input type="email" class="form-control" name="email" 
                                                       placeholder="email@example.com">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Pekerjaan</label>
                                        <input type="text" class="form-control" name="pekerjaan" 
                                               placeholder="Pekerjaan saat ini">
                                    </div>
                                </div>

                                <!-- Data Pendaftaran -->
                                <div class="col-md-6">
                                    <h5 class="mb-3 border-bottom pb-2">Data Pendaftaran</h5>

                                    <div class="form-group">
                                        <label class="form-label">Poli Tujuan <span class="text-danger">*</span></label>
                                        <select class="form-select select2-poli" name="id_poli" required>
                                            <option value="">-- Pilih Poli --</option>
                                            <?php foreach ($list_poli ?? [] as $p): ?>
                                                <option value="<?= $p->poli_id ?>"><?= $p->nama_poli ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="invalid-feedback" data-error="id_poli"></div>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Dokter</label>
                                        <select class="form-select select2-dokter" name="id_dokter">
                                            <option value="">-- Pilih Dokter --</option>
                                            <?php foreach ($list_dokter ?? [] as $d): ?>
                                                <option value="<?= $d->dokter_id ?>" data-poli="<?= $d->id_poli ?>">
                                                    <?= $d->nama_dokter ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Tanggal Periksa <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" name="tanggal_periksa" 
                                               value="<?= date('Y-m-d') ?>" min="<?= date('Y-m-d') ?>" required>
                                        <div class="invalid-feedback" data-error="tanggal_periksa"></div>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Jenis Kunjungan</label>
                                        <select class="form-control" name="jenis_kunjungan">
                                            <option value="SAKIT">SAKIT</option>
                                            <option value="SEHAT">SEHAT</option>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Jenis Pembayaran</label>
                                        <select class="form-control" name="jenis_pembayaran">
                                            <option value="UMUM">UMUM</option>
                                            <option value="BPJS">BPJS</option>
                                            <option value="ASURANSI">ASURANSI LAINNYA</option>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">No. Asuransi/BPJS</label>
                                        <input type="text" class="form-control" name="no_asuransi" 
                                               placeholder="Nomor kartu asuransi/BPJS">
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">Keluhan Utama</label>
                                        <textarea class="form-control" name="keluhan" rows="2" 
                                                  placeholder="Jelaskan keluhan utama (opsional)"></textarea>
                                    </div>

                                    <div class="d-grid mt-4">
                                        <button type="submit" class="btn btn-primary btn-lg" id="btn-daftar-baru">
                                            <i class="fa-solid fa-paper-plane me-2"></i>Daftar Sekarang
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Form Pasien Lama -->
                    <div class="form-card pasien-form" id="form-pasien-lama">
                        <h4 class="mb-4 text-center"><i class="fa-solid fa-user-check me-2"></i>Formulir Pasien Lama</h4>

                        <div class="row">
                            <!-- Pencarian Pasien -->
                            <div class="col-md-5">
                                <div class="card border-primary">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0"><i class="fa-solid fa-search me-2"></i>Cari Data Pasien</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="form-group">
                                            <label class="form-label">No. Rekam Medis <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="cari_rme" 
                                                   placeholder="Contoh: RME-2025-0001" required>
                                            <div class="invalid-feedback" data-error="cari_rme"></div>
                                        </div>

                                        <div class="form-group">
                                            <label class="form-label">Bulan Lahir <span class="text-danger">*</span></label>
                                            <select class="form-control" id="cari_bulan_lahir" required>
                                                <option value="">-- Pilih Bulan --</option>
                                                <option value="01">Januari</option>
                                                <option value="02">Februari</option>
                                                <option value="03">Maret</option>
                                                <option value="04">April</option>
                                                <option value="05">Mei</option>
                                                <option value="06">Juni</option>
                                                <option value="07">Juli</option>
                                                <option value="08">Agustus</option>
                                                <option value="09">September</option>
                                                <option value="10">Oktober</option>
                                                <option value="11">November</option>
                                                <option value="12">Desember</option>
                                            </select>
                                            <div class="invalid-feedback" data-error="cari_bulan_lahir"></div>
                                        </div>

                                        <div class="d-grid">
                                            <button type="button" class="btn btn-primary" id="btn-cari-pasien">
                                                <i class="fa-solid fa-search me-2"></i>Cari Pasien
                                            </button>
                                        </div>

                                        <div id="info-pasien" class="mt-3" style="display: none;">
                                            <div class="alert alert-success">
                                                <h6 class="alert-heading">Data Ditemukan</h6>
                                                <hr>
                                                <p class="mb-1"><strong>No. RM:</strong> <span id="info-rme"></span></p>
                                                <p class="mb-1"><strong>Nama:</strong> <span id="info-nama"></span></p>
                                                <p class="mb-1"><strong>NIK:</strong> <span id="info-nik"></span></p>
                                                <p class="mb-0"><strong>Tanggal Lahir:</strong> <span id="info-tgl-lahir"></span></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Pendaftaran -->
                            <div class="col-md-7">
                                <div class="card">
                                    <div class="card-header bg-success text-white">
                                        <h5 class="mb-0"><i class="fa-solid fa-calendar-check me-2"></i>Pendaftaran Poli</h5>
                                    </div>
                                    <div class="card-body">
                                        <form id="formDaftarLama" method="post" action="<?= site_url('pendaftaran_online/simpan_pasien_lama') ?>">
                                            <input type="hidden" name="id_pasien" id="id_pasien">

                                            <div class="form-group">
                                                <label class="form-label">Poli Tujuan <span class="text-danger">*</span></label>
                                                <select class="form-select select2-poli" name="id_poli" required>
                                                    <option value="">-- Pilih Poli --</option>
                                                    <?php foreach ($list_poli ?? [] as $p): ?>
                                                        <option value="<?= $p->poli_id ?>"><?= $p->nama_poli ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <div class="invalid-feedback" data-error="id_poli"></div>
                                            </div>

                                            <div class="form-group">
                                                <label class="form-label">Dokter</label>
                                                <select class="form-select select2-dokter" name="id_dokter">
                                                    <option value="">-- Pilih Dokter --</option>
                                                    <?php foreach ($list_dokter ?? [] as $d): ?>
                                                        <option value="<?= $d->dokter_id ?>" data-poli="<?= $d->id_poli ?>">
                                                            <?= $d->nama_dokter ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <div class="form-group">
                                                <label class="form-label">Tanggal Periksa <span class="text-danger">*</span></label>
                                                <input type="date" class="form-control" name="tanggal_periksa" 
                                                       value="<?= date('Y-m-d') ?>" min="<?= date('Y-m-d') ?>" required>
                                                <div class="invalid-feedback" data-error="tanggal_periksa"></div>
                                            </div>

                                            <div class="form-group">
                                                <label class="form-label">Jenis Kunjungan</label>
                                                <select class="form-control" name="jenis_kunjungan">
                                                    <option value="SAKIT">SAKIT</option>
                                                    <option value="SEHAT">SEHAT</option>
                                                </select>
                                            </div>

                                            <div class="form-group">
                                                <label class="form-label">Keluhan Utama</label>
                                                <textarea class="form-control" name="keluhan" rows="2" 
                                                          placeholder="Jelaskan keluhan utama (opsional)"></textarea>
                                            </div>

                                            <div class="d-grid mt-4">
                                                <button type="submit" class="btn btn-success btn-lg" id="btn-daftar-lama" disabled>
                                                    <i class="fa-solid fa-calendar-plus me-2"></i>Daftar Poli
                                                </button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- Modal Kartu Antrian -->
    <div class="modal fade" id="modalKartuAntrian" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fa-solid fa-ticket-alt me-2"></i>Kartu Antrian</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <div class="kartu-antrian">
                        <h4><i class="fa-solid fa-hospital me-2"></i>RS Poltekkes Kemenkes Semarang</h4>
                        <p class="mb-0">Kartu Antrian Online</p>

                        <div class="nomor-antrian" id="nomor-antrian-display">-</div>

                        <div class="mb-3">
                            <p class="mb-1"><strong>Nama:</strong> <span id="nama-pasien-display">-</span></p>
                            <p class="mb-1"><strong>No. RM:</strong> <span id="rme-display">-</span></p>
                            <p class="mb-1"><strong>Poli:</strong> <span id="poli-display">-</span></p>
                            <p class="mb-1"><strong>Dokter:</strong> <span id="dokter-display">-</span></p>
                            <p class="mb-1"><strong>Tanggal:</strong> <span id="tanggal-display">-</span></p>
                            <p class="mb-0"><strong>Waktu:</strong> <span id="waktu-display">-</span></p>
                        </div>

                        <!-- Info Reservasi akan ditambahkan via JavaScript -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="button" class="btn btn-primary" onclick="cetakKartuAntrian()">
                        <i class="fa-solid fa-print me-2"></i>Cetak
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Layanan -->
    <section id="layanan" class="py-5 bg-light">
        <div class="container text-center">
            <h2 class="section-title mb-4" data-aos="zoom-in">Layanan Unggulan</h2>
            <div class="row g-4">
                <div class="col-md-4" data-aos="fade-up" data-aos-delay="100">
                    <div class="icon-box"><i class="fa-solid fa-stethoscope"></i></div>
                    <h5>Konsultasi Dokter</h5>
                    <p>Konsultasi dengan dokter spesialis terbaik secara mudah.</p>
                </div>
                <div class="col-md-4" data-aos="fade-up" data-aos-delay="200">
                    <div class="icon-box"><i class="fa-solid fa-flask"></i></div>
                    <h5>Laboratorium</h5>
                    <p>Pemeriksaan laboratorium lengkap dengan teknologi modern.</p>
                </div>
                <div class="col-md-4" data-aos="fade-up" data-aos-delay="300">
                    <div class="icon-box"><i class="fa-solid fa-ambulance"></i></div>
                    <h5>Emergency</h5>
                    <p>Layanan darurat 24 jam dengan tim medis profesional.</p>
                </div>
            </div>
        </div>
    </section>

    <!-- Kontak -->
    <section id="kontak" class="py-5">
        <div class="container text-center">
            <h2 class="section-title mb-4" data-aos="zoom-in">Hubungi Kami</h2>
            <p data-aos="fade-right"><i class="fa-solid fa-location-dot"></i> Jl. Sehat No. 123, Jakarta</p>
            <p data-aos="fade-right" data-aos-delay="150"><i class="fa-solid fa-phone"></i> (021) 123456</p>
            <p data-aos="fade-right" data-aos-delay="300"><i class="fa-solid fa-envelope"></i> info@rssehat.com</p>
        </div>
    </section>

    <!-- Footer -->
    <footer class="text-center py-3" style="background:#0097B2; color:#fff;">
        <p>&copy; <?= date('Y'); ?> RS Poltekkes Kemenkes Semarang - Semua Hak Dilindungi</p>
    </footer>

    <!-- JS -->
    <script src="<?= base_url('assets/adminlte/plugins/jquery/jquery.min.js'); ?>"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- AOS JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Select2 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

    <script>
        // Inisialisasi
        document.addEventListener('DOMContentLoaded', function() {
            AOS.init({
                duration: 1000,
                once: true
            });

            initializeSelect2();
            initializeEventListeners();
            initializeFormValidation();
        });

        // Initialize Select2
        function initializeSelect2() {
            $('.select2-poli, .select2-dokter').select2({
                theme: 'bootstrap-5',
                placeholder: '-- Pilih --',
                allowClear: true,
                width: '100%'
            });
        }

        // Initialize Event Listeners
        function initializeEventListeners() {
            // Smooth scroll
            document.querySelectorAll('a.nav-link[href^="#"]').forEach(a => {
                a.addEventListener('click', e => {
                    const id = a.getAttribute('href').slice(1);
                    const el = document.getElementById(id);
                    if (el) {
                        e.preventDefault();
                        el.scrollIntoView({
                            behavior: 'smooth'
                        });
                    }
                });
            });

            // Mode selector
            document.querySelectorAll('.mode-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');

                    const mode = this.dataset.mode;
                    document.querySelectorAll('.pasien-form').forEach(form => form.classList.remove('active'));
                    document.getElementById(`form-pasien-${mode}`).classList.add('active');
                    
                    // Reset form ketika ganti mode
                    resetForms();
                });
            });

            // Filter dokter berdasarkan poli
            document.querySelectorAll('select[name="id_poli"]').forEach(select => {
                select.addEventListener('change', function() {
                    const poliId = this.value;
                    const form = this.closest('form');
                    const dokterSelect = form.querySelector('select[name="id_dokter"]');

                    if (!poliId) {
                        $(dokterSelect).empty().append('<option value="">-- Pilih Dokter --</option>').trigger('change');
                        return;
                    }

                    // AJAX untuk mengambil dokter berdasarkan poli
                    fetch(`<?= site_url('pendaftaran_online/dokter_by_poli/') ?>${poliId}`)
                        .then(response => response.json())
                        .then(dokterList => {
                            let options = '<option value="">-- Pilih Dokter --</option>';
                            if (dokterList && dokterList.length > 0) {
                                dokterList.forEach(dokter => {
                                    options += `<option value="${dokter.dokter_id}">${dokter.nama_dokter}</option>`;
                                });
                            } else {
                                options += '<option value="">Tidak ada dokter tersedia</option>';
                            }
                            $(dokterSelect).html(options).trigger('change');
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            $(dokterSelect).html('<option value="">Error memuat data dokter</option>').trigger('change');
                        });
                });
            });

            // Validasi NIK (hanya angka)
            document.querySelectorAll('input[name="nik"]').forEach(input => {
                input.addEventListener('input', function() {
                    this.value = this.value.replace(/\D/g, '').slice(0, 16);
                });
            });

            // Validasi telepon (hanya angka)
            document.querySelectorAll('input[name="no_telp"]').forEach(input => {
                input.addEventListener('input', function() {
                    this.value = this.value.replace(/\D/g, '').slice(0, 15);
                });
            });
        }

        // Initialize Form Validation
        function initializeFormValidation() {
            // Form Pasien Baru
            const formBaru = document.getElementById('formDaftarBaru');
            if (formBaru) {
                formBaru.addEventListener('submit', handleSubmitPasienBaru);
            }

            // Form Pasien Lama
            const formLama = document.getElementById('formDaftarLama');
            if (formLama) {
                formLama.addEventListener('submit', handleSubmitPasienLama);
            }

            // Cari Pasien Lama
            const btnCariPasien = document.getElementById('btn-cari-pasien');
            if (btnCariPasien) {
                btnCariPasien.addEventListener('click', handleCariPasienLama);
            }
        }

        // Handle Submit Pasien Baru
        async function handleSubmitPasienBaru(e) {
            e.preventDefault();
            
            const form = e.target;
            const formData = new FormData(form);
            const btnSubmit = form.querySelector('#btn-daftar-baru');
            
            // Validasi client-side
            if (!validateForm(form)) {
                return;
            }

            showLoading(true);
            disableButton(btnSubmit, true);

            try {
                const response = await fetch(form.action, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    await Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: result.message,
                        timer: 3000,
                        showConfirmButton: false
                    });
                    
                    tampilkanKartuAntrian(result);
                    resetForm(form);
                } else {
                    showFormErrors(form, result.errors || {});
                    await Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: result.message
                    });
                }
            } catch (error) {
                console.error('Error:', error);
                await Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Terjadi kesalahan sistem. Silakan coba lagi.'
                });
            } finally {
                showLoading(false);
                disableButton(btnSubmit, false);
            }
        }

        // Handle Submit Pasien Lama
        async function handleSubmitPasienLama(e) {
            e.preventDefault();
            
            const form = e.target;
            const formData = new FormData(form);
            const btnSubmit = form.querySelector('#btn-daftar-lama');
            
            if (!validateForm(form)) {
                return;
            }

            showLoading(true);
            disableButton(btnSubmit, true);

            try {
                const response = await fetch(form.action, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    await Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: result.message,
                        timer: 3000,
                        showConfirmButton: false
                    });
                    
                    tampilkanKartuAntrian(result);
                    resetForm(form);
                } else {
                    showFormErrors(form, result.errors || {});
                    await Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        text: result.message
                    });
                }
            } catch (error) {
                console.error('Error:', error);
                await Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Terjadi kesalahan sistem. Silakan coba lagi.'
                });
            } finally {
                showLoading(false);
                disableButton(btnSubmit, false);
            }
        }

        // Handle Cari Pasien Lama
        async function handleCariPasienLama() {
            const rme = document.getElementById('cari_rme').value.trim();
            const bulanLahir = document.getElementById('cari_bulan_lahir').value;
            const btnCari = document.getElementById('btn-cari-pasien');
            const infoPasien = document.getElementById('info-pasien');
            const btnDaftar = document.getElementById('btn-daftar-lama');

            // Validasi input
            if (!rme) {
                showFieldError('cari_rme', 'No. RM harus diisi');
                return;
            }
            if (!bulanLahir) {
                showFieldError('cari_bulan_lahir', 'Bulan lahir harus dipilih');
                return;
            }

            showLoading(true);
            disableButton(btnCari, true);

            try {
                const response = await fetch('<?= site_url('pendaftaran_online/cari_pasien_lama') ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        'rme_no': rme,
                        'bulan_lahir': bulanLahir
                    })
                });

                const result = await response.json();

                if (result.success) {
                    // Tampilkan info pasien
                    document.getElementById('info-rme').textContent = result.data.rme_no;
                    document.getElementById('info-nama').textContent = result.data.nama_lengkap;
                    document.getElementById('info-nik').textContent = result.data.nik;
                    document.getElementById('info-tgl-lahir').textContent = formatTanggal(result.data.tanggal_lahir);
                    infoPasien.style.display = 'block';

                    // Set id pasien untuk form
                    document.getElementById('id_pasien').value = result.data.pasien_id;

                    // Aktifkan tombol daftar
                    btnDaftar.disabled = false;

                    clearFieldError('cari_rme');
                    clearFieldError('cari_bulan_lahir');

                    await Swal.fire({
                        icon: 'success',
                        title: 'Data Ditemukan!',
                        text: 'Data pasien berhasil ditemukan. Silakan lanjutkan pendaftaran.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                } else {
                    infoPasien.style.display = 'none';
                    btnDaftar.disabled = true;
                    await Swal.fire({
                        icon: 'error',
                        title: 'Data Tidak Ditemukan!',
                        text: result.message
                    });
                }
            } catch (error) {
                console.error('Error:', error);
                await Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Terjadi kesalahan sistem. Silakan coba lagi.'
                });
            } finally {
                showLoading(false);
                disableButton(btnCari, false);
            }
        }

        // Utility Functions
        function validateForm(form) {
            let isValid = true;
            const requiredFields = form.querySelectorAll('[required]');
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    showFieldError(field.name, 'Field ini harus diisi');
                    isValid = false;
                } else {
                    clearFieldError(field.name);
                }
            });

            return isValid;
        }

        function showFieldError(fieldName, message) {
            const field = document.querySelector(`[name="${fieldName}"]`);
            const feedback = document.querySelector(`[data-error="${fieldName}"]`);
            
            if (field) field.classList.add('is-invalid');
            if (feedback) feedback.textContent = message;
        }

        function clearFieldError(fieldName) {
            const field = document.querySelector(`[name="${fieldName}"]`);
            const feedback = document.querySelector(`[data-error="${fieldName}"]`);
            
            if (field) field.classList.remove('is-invalid');
            if (feedback) feedback.textContent = '';
        }

        function showFormErrors(form, errors) {
            // Reset semua error terlebih dahulu
            form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
            form.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');

            // Tampilkan error baru
            Object.entries(errors).forEach(([field, message]) => {
                showFieldError(field, message);
            });
        }

        function resetForm(form) {
            form.reset();
            form.querySelectorAll('.select2').forEach(select => {
                $(select).val(null).trigger('change');
            });
            form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
            form.querySelectorAll('.invalid-feedback').forEach(el => el.textContent = '');
        }

        function resetForms() {
            document.querySelectorAll('form').forEach(form => resetForm(form));
            document.getElementById('info-pasien').style.display = 'none';
            document.getElementById('btn-daftar-lama').disabled = true;
        }

        function showLoading(show) {
            document.querySelector('.loading-overlay').style.display = show ? 'flex' : 'none';
        }

        function disableButton(button, disabled) {
            if (disabled) {
                button.disabled = true;
                button.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i>Memproses...';
            } else {
                button.disabled = false;
                if (button.id === 'btn-daftar-baru') {
                    button.innerHTML = '<i class="fa-solid fa-paper-plane me-2"></i>Daftar Sekarang';
                } else if (button.id === 'btn-daftar-lama') {
                    button.innerHTML = '<i class="fa-solid fa-calendar-plus me-2"></i>Daftar Poli';
                } else if (button.id === 'btn-cari-pasien') {
                    button.innerHTML = '<i class="fa-solid fa-search me-2"></i>Cari Pasien';
                }
            }
        }

        // Tampilkan kartu antrian dengan informasi reservasi
        function tampilkanKartuAntrian(response) {
            document.getElementById('nomor-antrian-display').textContent = response.kode_verifikasi;
            document.getElementById('nama-pasien-display').textContent = response.data.nama_lengkap;
            document.getElementById('rme-display').textContent = response.data.rme_no;
            document.getElementById('poli-display').textContent = response.data.nama_poli;
            document.getElementById('dokter-display').textContent = response.data.nama_dokter;
            document.getElementById('tanggal-display').textContent = formatTanggal(response.data.tanggal_periksa);
            document.getElementById('waktu-display').textContent = response.data.waktu_periksa;
			// document.getElementById('kode-reservasi').textContent = response.data.kode_verifikasi;

            // Tambahkan informasi reservasi
            const kartuAntrian = document.querySelector('.kartu-antrian');
            const existingInfo = kartuAntrian.querySelector('.info-reservasi');
            if (existingInfo) {
                existingInfo.remove();
            }

            const infoReservasi = document.createElement('div');
            infoReservasi.className = 'info-reservasi mt-3 p-3 rounded';
            infoReservasi.innerHTML = `
                <h6 class="text-center mb-2"><i class="fas fa-ticket-alt me-2"></i>Informasi Reservasi</h6>
                <p class="mb-1"><strong>Nomor Reservasi:</strong> <span class="fw-bold">${response.data.nomor_reservasi}</span></p>
                <p class="mb-0"><strong>Kode Verifikasi:</strong> <span class="fw-bold">${response.data.kode_verifikasi}</span></p>
                <small class="text-light">*Simpan informasi ini untuk verifikasi di rumah sakit</small>
            `;
            
            kartuAntrian.appendChild(infoReservasi);

            const modal = new bootstrap.Modal(document.getElementById('modalKartuAntrian'));
            modal.show();
        }

        // Format tanggal untuk tampilan
        function formatTanggal(tanggal) {
            if (!tanggal) return '-';
            const options = {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            };
            return new Date(tanggal).toLocaleDateString('id-ID', options);
        }

        // Cetak kartu antrian
        function cetakKartuAntrian() {
            const modal = bootstrap.Modal.getInstance(document.getElementById('modalKartuAntrian'));
            modal.hide();
            
            setTimeout(() => {
                const kartuContent = document.querySelector('.kartu-antrian').cloneNode(true);
                const printWindow = window.open('', '_blank');
                
                printWindow.document.write(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>Kartu Antrian - RS Poltekkes Kemenkes Semarang</title>
                        <style>
                            body { 
                                font-family: Arial, sans-serif; 
                                margin: 20px;
                                text-align: center;
                            }
                            .kartu-antrian {
                                border: 2px solid #0097B2;
                                border-radius: 15px;
                                padding: 20px;
                                max-width: 400px;
                                margin: 0 auto;
                            }
                            .nomor-antrian {
                                font-size: 3rem;
                                font-weight: bold;
                                color: #0097B2;
                                margin: 15px 0;
                            }
                            .info-reservasi {
                                background: #f8f9fa;
                                border-radius: 8px;
                                padding: 15px;
                                margin-top: 15px;
                            }
                            @media print {
                                body { margin: 0; }
                                .kartu-antrian { border: none; box-shadow: none; }
                            }
                        </style>
                    </head>
                    <body>
                `);
                printWindow.document.write(kartuContent.outerHTML);
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                
                printWindow.onload = function() {
                    printWindow.print();
                    printWindow.onafterprint = function() {
                        printWindow.close();
                        modal.show();
                    };
                };
            }, 500);
        }


    (function() {
      const form = document.getElementById('formLoginPetugas');
      if (!form) return;

      const submitBtn = form.querySelector('button[type="submit"]');
      const btnText   = submitBtn.querySelector('.btn-text');
      const spinner   = submitBtn.querySelector('.spinner-border');

      function setSubmitting(state) {
        submitBtn.disabled = state;
        spinner.classList.toggle('d-none', !state);
        btnText.textContent = state ? 'Memproses...' : 'Masuk';
      }
      function clearErrors() {
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        form.querySelectorAll('[data-error]').forEach(el => el.textContent = '');
      }
      function showErrors(errors) {
        Object.entries(errors || {}).forEach(([field, msg]) => {
          const input = form.querySelector(`[name="${field}"]`);
          const errEl = form.querySelector(`[data-error="${field}"]`);
          if (input) input.classList.add('is-invalid');
          if (errEl) errEl.textContent = msg || 'Invalid';
        });
      }
      function updateCsrf(newHash) {
        const csrfInput = form.querySelector('input[type="hidden"][name*="csrf"]');
        if (csrfInput && newHash) csrfInput.value = newHash;
      }

      form.addEventListener('submit', async function(e) {
        e.preventDefault();
        clearErrors();
        setSubmitting(true);

        try {
          const res = await fetch(form.action, {
            method: 'POST',
            body: new FormData(form),
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
          });
          const data = await res.json();
          updateCsrf(data.csrf);

          if (data.ok && data.redirect) {
            location.assign(data.redirect);
            return;
          }
          showErrors(data.errors);
        } catch (err) {
          // fallback error global
          const pass = form.querySelector('[name="password"]');
          const errEl = form.querySelector('[data-error="password"]');
          if (pass) pass.classList.add('is-invalid');
          if (errEl) errEl.textContent = 'Login gagal. Coba lagi.';
          console.error(err);
        } finally {
          setSubmitting(false);
        }
      });
    })();

    // Flash error dari server → tampilkan modal & alert
    <?php if ($this->session->flashdata('login_error')): ?>
      document.addEventListener("DOMContentLoaded", function() {
        const modal = new bootstrap.Modal(document.getElementById('loginPetugasModal'));
        modal.show();
        Swal.fire({ icon:'error', title:'Login gagal', text:'<?= $this->session->flashdata('login_error'); ?>' });
      });
    <?php endif; ?>
    </script>
</body>

</html>
