<?php
require_once '../admin/config.php';
session_start();
$conn = connectDB();

// Validasi input
function validate_url($url, $allowed_ext) {
    return filter_var($url, FILTER_VALIDATE_URL) && 
           preg_match('/\.(?:' . implode('|', $allowed_ext) . ')$/i', $url);
}

// 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']);
// Extract 'kabupaten' or 'kota' from domisili value for database compatibility
$domisili = (strpos(strtolower($domisili_raw), 'kabupaten') !== false) ? 'kabupaten' : 'kota';
$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']);

// Fungsi validasi Google Drive URL
function is_google_drive_url($url) {
    $parsed = parse_url($url);
    return isset($parsed['host']) && 
           $parsed['host'] === 'drive.google.com' &&
           strpos($parsed['path'], '/file/d/') === 0;
}

// Validasi URL
if(!is_google_drive_url($foto_url)) {
    die("<script>alert('Format URL foto tidak valid. Harus dari Google Drive'); window.history.back();</script>");
}

if(!is_google_drive_url($karya_url)) {
    die("<script>alert('Format URL karya tidak valid. Harus dari Google Drive'); window.history.back();</script>");
}

// Tentukan tabel tujuan
$table = ($domisili == 'kabupaten') ? 'domisilikabupaten' : 'domisilikota';

// Cek keberadaan NISN
$check_sql = "SELECT NISN FROM $table WHERE NISN = '$nisn'";
if($conn->query($check_sql)->num_rows > 0) {
    die("<script>alert('NISN sudah terdaftar'); window.history.back();</script>");
}

// Simpan ke database
$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']);
    echo "<script>alert('Pendaftaran berhasil!'); window.location='index.php';</script>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>