<?php
require_once '../../admin/config.php';
session_start();
// Cek apakah halaman ini diakses langsung atau melalui form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // PROSES FORM
    $conn = connectDB();

    // Data dari form
    $nisn = $conn->real_escape_string($_POST['nisn']);
    $nama_peserta = $conn->real_escape_string($_POST['nama_peserta']);
    $nama_sekolah = $conn->real_escape_string($_POST['nama_sekolah']);
    $npsn = $conn->real_escape_string($_POST['npsn']);
    $ttl = $conn->real_escape_string($_POST['ttl']);
    $email = $conn->real_escape_string($_POST['email']);
    $jenis_kelamin = $conn->real_escape_string($_POST['jenis_kelamin']);
    $domisili_raw = $conn->real_escape_string($_POST['domisili']); // Keep raw value for query
    $id_cabang = $conn->real_escape_string($_POST['cabang_lomba']);
    $foto_url = $conn->real_escape_string($_POST['foto_peserta']);
    $karya_url = $conn->real_escape_string($_POST['karya']);

    // Menyiapkan variable untuk pesan
    $error_message = '';
    $success_message = '';
    $modal_type = '';

    // Validasi URL sederhana - hanya memeriksa apakah format URL valid
    if(!filter_var($foto_url, FILTER_VALIDATE_URL)) {
        $error_message = 'Format URL foto tidak valid.';
        $modal_type = 'error';
    } elseif(!filter_var($karya_url, FILTER_VALIDATE_URL)) {
        $error_message = 'Format URL karya tidak valid.';
        $modal_type = 'error';
    } else {
        // VALIDASI NAMA_PESERTA dan NPSN
        // Cek keberadaan Nama_Peserta dan NPSN pada tabel peserta_terdaftar dengan domisili yang sesuai
        $check_data_sql = "SELECT id FROM peserta_terdaftar WHERE Nama_Peserta = '$nama_peserta' AND NPSN = '$npsn' AND domisili = '$domisili_raw'";
        $data_result = $conn->query($check_data_sql);
        
        if($data_result->num_rows == 0) {
            // Data tidak terdaftar atau tidak sesuai dengan domisili yang dipilih
            $error_message = 'Nama Peserta dan NPSN tidak terdaftar atau tidak sesuai dengan domisili yang dipilih. Silakan hubungi administrator.';
            $modal_type = 'error';
        } else {
            // Data terdaftar dan sesuai dengan domisili
            // Tentukan tabel tujuan berdasarkan domisili
            $domisili = (strpos(strtolower($domisili_raw), 'kabupaten') !== false) ? 'kabupaten' : 'kota';
            $table = ($domisili == 'kabupaten') ? 'domisilikabupaten' : 'domisilikota';

            // Cek apakah sudah pernah mendaftar dengan NISN tersebut
            $check_sql = "SELECT NISN FROM $table WHERE NISN = '$nisn'";
            if($conn->query($check_sql)->num_rows > 0) {
                $error_message = 'NISN sudah terdaftar dalam lomba ini';
                $modal_type = 'error';
            } else {
                // Simpan ke database karena data terverifikasi
                $sql = "INSERT INTO $table (
                            NISN, 
                            Nama_Peserta, 
                            Nama_Sekolah,
                            NPSN,
                            TTL,
                            Email, 
                            Jenis_Kelamin, 
                            Foto_Peserta, 
                            Karya, 
                            ID_Cabang_Lomba
                        ) VALUES (
                            '$nisn', 
                            '$nama_peserta', 
                            '$nama_sekolah',
                            '$npsn',
                            '$ttl',
                            '$email', 
                            '$jenis_kelamin', 
                            '$foto_url', 
                            '$karya_url', 
                            '$id_cabang'
                        )";

                if ($conn->query($sql) === TRUE) {
                    unset($_SESSION['cabang_lomba']);
                    unset($_SESSION['domisili']);
                    $success_message = 'Pendaftaran berhasil!';
                    $modal_type = 'success';
                } else {
                    $error_message = "Error: " . $sql . "<br>" . $conn->error;
                    $modal_type = 'error';
                }
            }
        }
    }

    $conn->close();
} else {
    // Halaman form diakses langsung
    if(!isset($_SESSION['cabang_lomba']) || !isset($_SESSION['domisili'])) {
        header("Location: form-daftar");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="..\..\assets\logoFLS3N.png" type="image/x-icon">
    <title>Form Pendaftaran FLS3N</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #9d174d;
            --secondary-color: #f43f5e;
            --accent-color: #fbcfe8;
            --dark-color: #4b5563;
            --light-color: #f9fafb;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f5f7;
            color: var(--dark-color);
            line-height: 1.6;
        }
        
        .page-container {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        
        .main-header {
            position: fixed;
            width: 100%;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            background: rgba(157, 23, 77, 0.95);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 10;
            top: 0;
            height: 80px;
            padding: 0 2rem;
            box-shadow: 0 4px 20px rgba(157, 23, 77, 0.3);
            transition: all 0.3s ease;
        }

        .main-header:hover {
            background: rgba(157, 23, 77, 1);
        }

        /* Logo styling */
        .logo-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .main-header .logo-container img {
            height: 65px;
            transition: transform 0.3s ease;
        }

        .main-header .logo-container img:hover {
            transform: scale(1.05);
        }
        /* Logo styling */
        .main-header .logo img {
            height: 65px;
            transition: transform 0.3s ease;
        }

        .main-header .logo img:hover {
            transform: scale(1.05);
        }

        /* Nama instansi */
        .main-header .instansi-name {
            font-size: 26px;
            font-weight: 700;
            letter-spacing: 1px;
            background: linear-gradient(90deg, #fff, #f0abfc);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-shadow: 0 2px 10px rgba(255, 255, 255, 0.2);
        }

        
        /* Content Styling */
        .content-wrapper {
            flex: 1;
            margin-top: 120px;
            padding-bottom: 60px;
        }
        
        .form-card {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            transform: translateY(0);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            margin-bottom: 30px;
        }
        
        .form-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            padding: 25px 30px;
            position: relative;
            overflow: hidden;
        }
        
        .card-header h3 {
            font-weight: 700;
            margin: 0;
            position: relative;
            z-index: 1;
        }
        
        .card-header::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 150px;
            height: 150px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(40%, -50%);
        }
        
        .card-header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(-30%, 50%);
        }
        
        .card-body {
            padding: 35px;
        }
        
        /* Back Button Styling */
        .back-btn {
            display: inline-flex;
            align-items: center;
            background: linear-gradient(90deg, #9d174d, #be185d);
            color: white;
            border-radius: 50px;
            padding: 12px 30px;
            font-weight: 600;
            box-shadow: 0 4px 10px rgba(157, 23, 77, 0.3);
            transition: all 0.3s ease;
            text-decoration: none;
            border: none;
            cursor: pointer;
            margin-bottom: 20px;
        }
        
        .back-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(157, 23, 77, 0.4);
            color: white;
        }
        
        .back-btn i {
            margin-right: 8px;
        }
        
        /* Form Elements Styling */
        .form-label {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--dark-color);
            margin-bottom: 8px;
        }
        
        .form-control, .form-select {
            padding: 12px 15px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            background-color: #f8fafc;
            transition: border-color 0.3s, box-shadow 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 3px rgba(244, 63, 94, 0.15);
        }
        
        .form-control[readonly] {
            background-color: #f1f5f9;
            border: 1px solid #e2e8f0;
            color: #64748b;
        }
        
        .input-group {
            position: relative;
        }
        
        .input-icon {
            position: absolute;
            top: 50%;
            left: 15px;
            transform: translateY(-50%);
            color: #94a3b8;
            z-index: 10;
        }
        
        .input-with-icon {
            padding-left: 45px;
        }
        
        /* Button Styling */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            border: none;
            padding: 12px 30px;
            font-weight: 600;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(244, 63, 94, 0.2);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(244, 63, 94, 0.3);
            background: linear-gradient(135deg, var(--secondary-color) 0%, var(--primary-color) 100%);
        }
        
        .btn-primary:active {
            transform: translateY(0);
        }
        
        /* Footer Styling */
        footer {
            background: linear-gradient(90deg, #9d174d, #be185d);
            color: white;
            text-align: center;
            padding: 1.5rem 0;
            width: 100%;
            margin-top: auto;
            position: relative;
            box-shadow: 0 -5px 20px rgba(157, 23, 77, 0.2);
        }

        footer p {
            margin: 0;
            font-size: 0.9rem;
            letter-spacing: 0.5px;
        }
        
        /* Form Section Styling */
        .form-section {
            margin-bottom: 30px;
            position: relative;
            padding-bottom: 15px;
        }
        
        .form-section::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 1px;
            background: linear-gradient(to right, var(--accent-color), transparent);
        }
        
        .form-section-title {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
        
        .form-section-title i {
            margin-right: 10px;
        }
        
        /* Animation effects */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.6s ease forwards;
        }
        
        /* Konfirmasi Modal Styling */
        .modal-confirm .modal-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            color: white;
            border-bottom: 0;
            padding: 1.5rem;
        }
        
        .modal-confirm .modal-title {
            font-weight: 700;
        }
        
        .modal-confirm .modal-body {
            padding: 1.5rem;
        }
        
        .modal-confirm .icon-warning {
            color: #ff9800;
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        .modal-confirm .warning-text {
            font-size: 1.1rem;
            font-weight: 500;
            color: #dc3545;
            margin-bottom: 1rem;
        }
        
        .modal-confirm .info-text {
            color: var(--dark-color);
            margin-bottom: 0.5rem;
        }
        
        .modal-confirm .modal-footer {
            border-top: 0;
            justify-content: space-between;
            padding: 1rem 1.5rem 1.5rem;
        }
        
        .modal-confirm .btn-secondary {
            background-color: #6c757d;
            border: none;
            font-weight: 600;
        }
        
        .modal-confirm .btn-confirm {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            border: none;
            font-weight: 600;
        }
        
        /* Tooltip untuk membantu user */
        .nisn-tooltip {
            cursor: help;
            color: var(--primary-color);
            margin-left: 5px;
        }
        
        /* Additional Responsive CSS for better mobile experience */
        @media (max-width: 768px) {
            .main-header {
                padding: 0 1rem;
                height: 70px;
            }
            
            .main-header .logo-container img {
                height: 45px;
            }
            
            .main-header .instansi-name {
                font-size: 20px;
            }
            
            .card-body {
                padding: 20px 15px;
            }
            
            /* Ensure form inputs have enough space on mobile */
            .input-with-icon {
                padding-left: 40px;
                font-size: 14px;
            }
            
            /* Make form labels more compact on mobile */
            .form-label {
                font-size: 14px;
                margin-bottom: 4px;
            }
            
            /* Reduce spacing between sections */
            .form-section {
                margin-bottom: 20px;
                padding-bottom: 10px;
            }
            
            /* Make section titles smaller on mobile */
            .form-section-title {
                font-size: 16px;
                margin-bottom: 15px;
            }
            
            /* Make helper text smaller on mobile */
            small.text-muted {
                font-size: 11px;
            }
            
            /* Make sure icons are properly positioned on mobile */
            .input-icon {
                left: 12px;
                font-size: 14px;
            }
            
            .back-btn {
                padding: 10px 20px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <div class="page-container">
        <header class="main-header">
        <div class="logo-container"> 
            <img src="../../assets/tutwurii.png" alt="Logo TI Unisbank">
            <img src="../../assets/unisbank.png" alt="Logo Unisbank">
            <img src="../../assets/logoFLS3N.png" alt="Logo FLS3N">    
            </div>
            <div class="instansi-name">FLS3N 2026</div>
        </header>

        <div class="content-wrapper">
            <div class="container mt-5">
                <div class="form-card animate-fade-in">
                    <div class="card-header">
                        <h3><i class="fas fa-user-edit me-2"></i>Form Pendaftaran Peserta</h3>
                    </div>
                    <div class="card-body">
                        <?php if (!isset($modal_type)): ?>
                        <div class="alert alert-info" role="alert">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Perhatian!</strong>
                            <ul class="mb-0 mt-2">
                                <li>Pendaftaran akan divalidasi berdasarkan Nama Peserta dan NPSN yang terdaftar.</li>
                                <li>Apabila belum melakukan pendaftaran dapat mengirimkan Nama Siswa, Bukti Pendaftaran FLS3N (dari BPTI), Cabang Lomba dan NPSN Sekolah ke email: <strong>newmild30@gmail.com</strong> (maks 24 April 2026, jam 15:00)</li>
                                <li>Link dipastikan sudah di seting menjadi akses PUBLIK untuk verifikasi dan penilaian karya oleh juri</li>
                                <li>Jika ada perubahan link dapat menghubungi ke email: <strong>newmild30@gmail.com</strong> (maks 25 April 2026, jam 15:00)</li>
                            </ul>
                        </div>
                        
                        <form id="registrationForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
                            <!-- Personal Information Section -->
                            <div class="form-section">
                                <h5 class="form-section-title"><i class="fas fa-id-card"></i> Informasi Pribadi</h5>
                                <div class="row">
                                    <!-- NISN Field with Improved Validation -->
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">NISN</label>
                                        <div class="input-group">
                                            <i class="fas fa-hashtag input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" name="nisn" 
                                                placeholder="Masukkan NISN" required 
                                                pattern="[0-9]{10}" 
                                                maxlength="10"
                                                title="NISN harus terdiri dari 10 digit angka"
                                                oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> NISN harus terdiri dari 10 digit angka</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Nama Peserta</label>
                                        <div class="input-group">
                                            <i class="fas fa-user input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" name="nama_peserta" 
                                                placeholder="Masukkan Nama Lengkap" required 
                                                pattern="[A-Z\s]+" 
                                                title="Nama harus menggunakan huruf kapital" 
                                                oninput="this.value = this.value.toUpperCase()">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- TTL and Email in one row (side by side) -->
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Tempat Tanggal Lahir</label>
                                        <div class="input-group">
                                            <i class="fas fa-calendar-alt input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" name="ttl" oninput="this.value = this.value.toUpperCase()" placeholder="Contoh: Jakarta, 31 Desember 2000" required >
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> Format: Kota/Kab, Tanggal Bulan Tahun (dipisahkan dengan ",")</small>
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Email & No WA</label>
                                        <div class="input-group">
                                            <i class="fas fa-envelope input-icon"></i>
                                            <input type="email" class="form-control input-with-icon" name="email" placeholder="contoh: xxx@xxx.com – 08xxxxx" required>
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> Format: Email – Nomor WA (dipisahkan dengan " – ")</small>
                                    </div>
                                </div>

                                <!-- Jenis Kelamin in a separate row below -->
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Jenis Kelamin</label>
                                        <div class="input-group">
                                            <i class="fas fa-venus-mars input-icon"></i>
                                            <select class="form-select input-with-icon" name="jenis_kelamin" required>
                                                <option value="">Pilih Jenis Kelamin</option>
                                                <option value="Laki-laki">Laki-laki</option>
                                                <option value="Perempuan">Perempuan</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- School Information Section -->
                            <div class="form-section">
                                <h5 class="form-section-title"><i class="fas fa-school"></i> Informasi Sekolah</h5>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Nama Sekolah</label>
                                        <div class="input-group">
                                            <i class="fas fa-school input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" name="nama_sekolah" 
                                                placeholder="Masukkan Nama Sekolah" required
                                                pattern="[A-Z0-9\s/]+"
                                                title="Nama sekolah harus menggunakan huruf kapital" 
                                                oninput="this.value = this.value.toUpperCase()">
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> Jangan disingkat! Contoh: SMA NEGERI 1 SEMARANG, SMA KRISTEN 2</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">NPSN Sekolah</label>
                                        <div class="input-group">
                                            <i class="fas fa-building input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" name="npsn" 
                                                placeholder="Masukkan NPSN Sekolah" required
                                                pattern="[0-9]+"
                                                title="NPSN harus berupa angka" >
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> NPSN harus berupa angka saja</small>
                                    </div>
                                </div>
                            </div>

                            <!-- Competition Information Section -->
                            <div class="form-section">
                                <h5 class="form-section-title"><i class="fas fa-trophy"></i> Informasi Lomba</h5>
                                
                                <!-- Domisili and Cabang Lomba in one row -->
                                <div class="row">
                                    <!-- Field Domisili (Readonly) -->
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Domisili</label>
                                        <div class="input-group">
                                            <i class="fas fa-map-marker-alt input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" 
                                                   value="Kabupaten Semarang" readonly>
                                            <input type="hidden" name="domisili" 
                                                   value="<?= $_SESSION['domisili'] ?>">
                                        </div>
                                    </div>

                                    <!-- Field Cabang Lomba (Readonly) -->
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Cabang Lomba</label>
                                        <?php
                                        $conn2 = connectDB();
                                        $result = $conn2->query("
                                            SELECT Bidang_Lomba 
                                            FROM cabang_lomba
                                            WHERE ID = {$_SESSION['cabang_lomba']}
                                        ");
                                        $cabang = $result->fetch_assoc()['Bidang_Lomba'];
                                        $conn2->close();
                                        ?>
                                        <div class="input-group">
                                            <i class="fas fa-medal input-icon"></i>
                                            <input type="text" class="form-control input-with-icon" value="<?= $cabang ?>" readonly>
                                            <input type="hidden" name="cabang_lomba" 
                                                   value="<?= $_SESSION['cabang_lomba'] ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Upload Section -->
                            <div class="form-section">
                                <h5 class="form-section-title"><i class="fas fa-cloud-upload-alt"></i> Upload Dokumen</h5>
                                
                                <div class="row">
                                    <!-- Input URL Foto Peserta -->
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Link Bukti Peserta</label>
                                        <div class="input-group">
                                            <i class="fas fa-image input-icon"></i>
                                            <input type="url" class="form-control input-with-icon" name="foto_peserta" 
                                                placeholder="Masukkan link foto (URL)" 
                                                required>
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> Masukkan link foto dari mana saja, dan di Public (Google Drive, Youtube, dll)</small>
                                    </div>

                                    <!-- Input URL Karya -->
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Link Karya</label>
                                        <div class="input-group">
                                            <i class="fas fa-file-upload input-icon"></i>
                                            <input type="url" class="form-control input-with-icon" name="karya" 
                                                placeholder="Masukkan link karya (URL)" 
                                                required>
                                        </div>
                                        <small class="text-muted mt-1"><i class="fas fa-info-circle"></i> Masukkan link karya dari mana saja, dan di Public (Google Drive, Youtube, dll)</small>
                                    </div>
                                </div>
                            </div>

                            <div class="text-center mt-4">
                                <button type="button" id="btnConfirm" class="btn btn-primary btn-lg">
                                    <i class="fas fa-paper-plane me-2"></i>Daftar Sekarang
                                </button>
                            </div>
                        </form>
                        
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Add Back Button -->
                <div class="text-center animate-fade-in mt-4">
                    <a href="../../dashboard_awal" class="back-btn">
                        <i class="fas fa-arrow-left"></i> Kembali ke Halaman Utama
                    </a>
                </div>
            </div>
        </div>
        <footer>
            <div class="container mx-auto">
                <p>&copy;<?php echo date("Y"); ?> FTII Unisbank. All rights reserved.</p>
            </div>
        </footer>
    </div>

    <!-- Modal Konfirmasi Pendaftaran -->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content modal-confirm">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Konfirmasi Pendaftaran</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <i class="fas fa-exclamation-circle icon-warning"></i>
                    <p class="warning-text">Submit Karya hanya dapat dilakukan Sekali!</p>
                    <p class="info-text">Harap periksa kembali data yang Anda masukkan:</p>
                    <ul class="text-start mt-3" id="dataConfirmation">
                        <!-- Data akan ditampilkan di sini via JavaScript -->
                    </ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i>Batal
                    </button>
                    <button type="button" id="btnSubmit" class="btn btn-confirm">
                        <i class="fas fa-check me-2"></i>Ya, Saya Yakin
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php if (isset($modal_type) && $modal_type === 'error'): ?>
    <!-- Modal Error -->
    <div class="modal fade" id="alertModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Error</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php echo $error_message; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="history.back()">Kembali</button>
                </div>
            </div>
        </div>
    </div>
    <?php elseif (isset($modal_type) && $modal_type === 'success'): ?>
    <!-- Modal Success -->
    <div class="modal fade" id="alertModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title">Sukses</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <?php echo $success_message; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal" onclick="window.location='../../dashboard_awal'">OK</button>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Initialize tooltips
        document.addEventListener("DOMContentLoaded", function() {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl)
            });
        });

        // Add smooth transitions when scrolling
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });

        <?php if (isset($modal_type)): ?>
        // Show modal automatically
        document.addEventListener("DOMContentLoaded", function() {
            var modal = new bootstrap.Modal(document.getElementById("alertModal"));
            modal.show();
        });
        <?php else: ?>
        // Konfirmasi sebelum submit form
        document.addEventListener("DOMContentLoaded", function() {
            const confirmModal = new bootstrap.Modal(document.getElementById("confirmModal"));
            const btnConfirm = document.getElementById("btnConfirm");
            const btnSubmit = document.getElementById("btnSubmit");
            const form = document.getElementById("registrationForm");
            const dataConfirmation = document.getElementById("dataConfirmation");
            
            // NISN validation - only numbers and exactly 10 digits
            const nisnInput = document.querySelector('input[name="nisn"]');
            nisnInput.addEventListener('input', function() {
                // Remove any non-numeric characters
                this.value = this.value.replace(/[^0-9]/g, '');
                
                // Limit to 10 digits
                if (this.value.length > 10) {
                    this.value = this.value.slice(0, 10);
                }
                
                // Visual feedback
                if (this.value.length === 10) {
                    this.classList.add('is-valid');
                    this.classList.remove('is-invalid');
                } else if (this.value.length > 0) {
                    this.classList.add('is-invalid');
                    this.classList.remove('is-valid');
                } else {
                    this.classList.remove('is-valid');
                    this.classList.remove('is-invalid');
                }
            });
            
            // Capital letters only for Nama Peserta, Nama Sekolah and NPSN
            const capitalOnlyInputs = [
                document.querySelector('input[name="nama_peserta"]'),
                document.querySelector('input[name="nama_sekolah"]'),
                document.querySelector('input[name="npsn"]')
            ];
            
            capitalOnlyInputs.forEach(input => {
                if (input) {
                    input.addEventListener('input', function() {
                        this.value = this.value.toUpperCase();
                    });
                    
                    // Prevent paste of lowercase text
                    input.addEventListener('paste', function(e) {
                        e.preventDefault();
                        const text = (e.originalEvent || e).clipboardData.getData('text/plain');
                        this.value += text.toUpperCase();
                    });
                }
            });
            
            // Fungsi untuk memformat URL agar tampilan lebih baik
            const formatURL = (url) => {
                if (url.length > 50) {
                    return url.substring(0, 47) + '...';
                }
                return url;
            };
            
            btnConfirm.addEventListener("click", function() {
                // Validasi form terlebih dahulu
                if (!form.checkValidity()) {
                    form.reportValidity();
                    return;
                }
                
                // Kumpulkan data untuk ditampilkan
                const formData = new FormData(form);
                let confirmationHTML = '';
                
                // NISN
                confirmationHTML += `<li><strong>NISN:</strong> ${formData.get('nisn')}</li>`;
                
                // Nama Peserta
                confirmationHTML += `<li><strong>Nama Peserta:</strong> ${formData.get('nama_peserta')}</li>`;
                
                // TTL
                confirmationHTML += `<li><strong>Tempat Tanggal Lahir:</strong> ${formData.get('ttl')}</li>`;
                
                // Email
                confirmationHTML += `<li><strong>Email:</strong> ${formData.get('email')}</li>`;
                
                // Jenis Kelamin
                confirmationHTML += `<li><strong>Jenis Kelamin:</strong> ${formData.get('jenis_kelamin')}</li>`;
                
                // Nama Sekolah
                confirmationHTML += `<li><strong>Nama Sekolah:</strong> ${formData.get('nama_sekolah')}</li>`;
                
                // NPSN
                confirmationHTML += `<li><strong>NPSN Sekolah:</strong> ${formData.get('npsn')}</li>`;
                
                // Domisili
                const domisiliValue = document.querySelector('input[name="domisili"]').value;
                const domisiliText = document.querySelector('input[value="' + domisiliValue + '"]').previousElementSibling.value;
                confirmationHTML += `<li><strong>Domisili:</strong> ${domisiliText}</li>`;
                
                // Cabang Lomba
                const cabangInput = document.querySelector('input[name="cabang_lomba"]');
                const cabangText = document.querySelector('input[value="' + cabangInput.value + '"]').previousElementSibling.value;
                confirmationHTML += `<li><strong>Cabang Lomba:</strong> ${cabangText}</li>`;
                
                // URL Foto - with better formatting and link
                const fotoURL = formData.get('foto_peserta');
                confirmationHTML += `<li><strong>Link Foto:</strong> <a href="${fotoURL}" target="_blank" class="text-primary">${formatURL(fotoURL)}</a></li>`;
                
                // URL Karya - with better formatting and link
                const karyaURL = formData.get('karya');
                confirmationHTML += `<li><strong>Link Karya:</strong> <a href="${karyaURL}" target="_blank" class="text-primary">${formatURL(karyaURL)}</a></li>`;
                
                // Tampilkan data di modal
                dataConfirmation.innerHTML = confirmationHTML;
                
                // Add an info text about the validation
                const existingInfo = document.querySelector('.modal-body .alert-info');
                if (!existingInfo) {
                    const additionalInfo = document.createElement('div');
                    additionalInfo.className = 'alert alert-info mt-3';
                    additionalInfo.innerHTML = `
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Penting!</strong> Pendaftaran akan divalidasi berdasarkan Nama Peserta dan NPSN yang terdaftar.
                    `;
                    document.querySelector('.modal-body').appendChild(additionalInfo);
                }
                
                // Tampilkan modal konfirmasi
                confirmModal.show();
            });
            
            // Handler submit form setelah konfirmasi
            btnSubmit.addEventListener("click", function() {
                form.submit();
            });

            // Validasi input NPSN - hanya angka
            const npsnInput = document.querySelector('input[name="npsn"]');
            if (npsnInput) {
                npsnInput.addEventListener('input', function(e) {
                    this.value = this.value.replace(/[^0-9]/g, '');
                });
            }
        });
        <?php endif; ?>
    </script>
</body>
</html>