<?php
// public/ppdb_register.php - Form Pendaftaran PPDB untuk Calon Siswa
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/db.php';
$db = get_db();

// Check if PPDB is open
$ppdb_open = $db->query("SELECT setting_value FROM ppdb_settings WHERE setting_key = 'ppdb_open'")->fetchColumn();
$ppdb_year = $db->query("SELECT setting_value FROM ppdb_settings WHERE setting_key = 'ppdb_year'")->fetchColumn();

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    // Generate registration number
    $year = date('Y');
    $count = $db->query("SELECT COUNT(*) FROM ppdb_registrations WHERE YEAR(created_at) = $year")->fetchColumn();
    $reg_number = 'PPDB' . $year . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
    
    // Handle file uploads
    $photo = '';
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === 0) {
      $upload_dir = __DIR__ . '/../data/uploads/ppdb/';
      if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
      $photo = 'photo_' . time() . '_' . basename($_FILES['photo']['name']);
      move_uploaded_file($_FILES['photo']['tmp_name'], $upload_dir . $photo);
    }
    
    // Insert registration
    $stmt = $db->prepare("
      INSERT INTO ppdb_registrations (
        registration_number, full_name, nickname, gender, birth_place, birth_date,
        religion, address, city, province, phone, email,
        father_name, father_occupation, father_phone,
        mother_name, mother_occupation, mother_phone,
        previous_school, graduation_year, nisn,
        major_choice_1, major_choice_2, photo, status
      ) VALUES (
        :reg_number, :full_name, :nickname, :gender, :birth_place, :birth_date,
        :religion, :address, :city, :province, :phone, :email,
        :father_name, :father_occupation, :father_phone,
        :mother_name, :mother_occupation, :mother_phone,
        :previous_school, :graduation_year, :nisn,
        :major_choice_1, :major_choice_2, :photo, 'pending'
      )
    ");
    
    $stmt->execute([
      ':reg_number' => $reg_number,
      ':full_name' => $_POST['full_name'],
      ':nickname' => $_POST['nickname'] ?? '',
      ':gender' => $_POST['gender'],
      ':birth_place' => $_POST['birth_place'],
      ':birth_date' => $_POST['birth_date'],
      ':religion' => $_POST['religion'],
      ':address' => $_POST['address'],
      ':city' => $_POST['city'],
      ':province' => $_POST['province'],
      ':phone' => $_POST['phone'] ?? '',
      ':email' => $_POST['email'] ?? '',
      ':father_name' => $_POST['father_name'] ?? '',
      ':father_occupation' => $_POST['father_occupation'] ?? '',
      ':father_phone' => $_POST['father_phone'] ?? '',
      ':mother_name' => $_POST['mother_name'] ?? '',
      ':mother_occupation' => $_POST['mother_occupation'] ?? '',
      ':mother_phone' => $_POST['mother_phone'] ?? '',
      ':previous_school' => $_POST['previous_school'] ?? '',
      ':graduation_year' => $_POST['graduation_year'] ?? null,
      ':nisn' => $_POST['nisn'] ?? '',
      ':major_choice_1' => $_POST['major_choice_1'] ?? '',
      ':major_choice_2' => $_POST['major_choice_2'] ?? '',
      ':photo' => $photo
    ]);
    
    $success = "Pendaftaran berhasil! Nomor pendaftaran Anda: <strong>$reg_number</strong>. Silakan simpan nomor ini untuk cek status pendaftaran.";
  } catch (Exception $e) {
    $error = "Terjadi kesalahan: " . $e->getMessage();
  }
}

require __DIR__ . '/_header.php';
?>

<div class="container py-5">
  <div class="row mb-4">
    <div class="col-12 text-center">
      <h1 class="display-5 fw-bold mb-3">Pendaftaran Peserta Didik Baru</h1>
      <p class="lead text-muted">Tahun Ajaran <?php echo e($ppdb_year ?? '2024/2025'); ?></p>
    </div>
  </div>

  <?php if ($ppdb_open != '1'): ?>
    <div class="row">
      <div class="col-md-8 mx-auto">
        <div class="alert alert-warning text-center">
          <i class="fa fa-exclamation-triangle fa-3x mb-3"></i>
          <h4>Pendaftaran Ditutup</h4>
          <p class="mb-0">Maaf, pendaftaran peserta didik baru saat ini sedang ditutup.</p>
        </div>
      </div>
    </div>
  <?php else: ?>
    
    <?php if ($success): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="fa fa-check-circle me-2"></i><?php echo $success; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
      <div class="alert alert-danger alert-dismissible fade show">
        <i class="fa fa-exclamation-circle me-2"></i><?php echo $error; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
      <!-- Data Pribadi -->
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0"><i class="fa fa-user me-2"></i>Data Pribadi Calon Siswa</h5>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-8">
              <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
              <input type="text" name="full_name" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Nama Panggilan</label>
              <input type="text" name="nickname" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">Jenis Kelamin <span class="text-danger">*</span></label>
              <select name="gender" class="form-select" required>
                <option value="">Pilih...</option>
                <option value="L">Laki-laki</option>
                <option value="P">Perempuan</option>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">Tempat Lahir <span class="text-danger">*</span></label>
              <input type="text" name="birth_place" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Tanggal Lahir <span class="text-danger">*</span></label>
              <input type="date" name="birth_date" class="form-control" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Agama <span class="text-danger">*</span></label>
              <select name="religion" class="form-select" required>
                <option value="">Pilih...</option>
                <option value="Islam">Islam</option>
                <option value="Kristen">Kristen</option>
                <option value="Katolik">Katolik</option>
                <option value="Hindu">Hindu</option>
                <option value="Buddha">Buddha</option>
                <option value="Konghucu">Konghucu</option>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">NISN</label>
              <input type="text" name="nisn" class="form-control" maxlength="20">
            </div>
            <div class="col-md-4">
              <label class="form-label">Foto <small class="text-muted">(3x4, max 2MB)</small></label>
              <input type="file" name="photo" class="form-control" accept="image/*">
            </div>
          </div>
        </div>
      </div>

      <!-- Alamat -->
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0"><i class="fa fa-map-marker-alt me-2"></i>Alamat</h5>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Alamat Lengkap <span class="text-danger">*</span></label>
              <textarea name="address" class="form-control" rows="3" required></textarea>
            </div>
            <div class="col-md-6">
              <label class="form-label">Kota/Kabupaten <span class="text-danger">*</span></label>
              <input type="text" name="city" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Provinsi <span class="text-danger">*</span></label>
              <input type="text" name="province" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">No. Telepon/HP</label>
              <input type="tel" name="phone" class="form-control">
            </div>
            <div class="col-md-6">
              <label class="form-label">Email</label>
              <input type="email" name="email" class="form-control">
            </div>
          </div>
        </div>
      </div>

      <!-- Data Orang Tua -->
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0"><i class="fa fa-users me-2"></i>Data Orang Tua/Wali</h5>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-12"><h6 class="text-primary">Data Ayah</h6></div>
            <div class="col-md-4">
              <label class="form-label">Nama Ayah</label>
              <input type="text" name="father_name" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">Pekerjaan</label>
              <input type="text" name="father_occupation" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">No. Telepon</label>
              <input type="tel" name="father_phone" class="form-control">
            </div>
            
            <div class="col-12"><h6 class="text-primary mt-3">Data Ibu</h6></div>
            <div class="col-md-4">
              <label class="form-label">Nama Ibu</label>
              <input type="text" name="mother_name" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">Pekerjaan</label>
              <input type="text" name="mother_occupation" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">No. Telepon</label>
              <input type="tel" name="mother_phone" class="form-control">
            </div>
          </div>
        </div>
      </div>

      <!-- Sekolah Asal -->
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0"><i class="fa fa-school me-2"></i>Sekolah Asal</h5>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-8">
              <label class="form-label">Nama Sekolah</label>
              <input type="text" name="previous_school" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">Tahun Lulus</label>
              <input type="number" name="graduation_year" class="form-control" min="2000" max="2030">
            </div>
          </div>
        </div>
      </div>

      <!-- Pilihan Jurusan -->
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h5 class="mb-0"><i class="fa fa-graduation-cap me-2"></i>Pilihan Jurusan</h5>
        </div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">Pilihan 1</label>
              <select name="major_choice_1" class="form-select">
                <option value="">Pilih Jurusan...</option>
                <option value="IPA">IPA</option>
                <option value="IPS">IPS</option>
                <option value="Bahasa">Bahasa</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Pilihan 2</label>
              <select name="major_choice_2" class="form-select">
                <option value="">Pilih Jurusan...</option>
                <option value="IPA">IPA</option>
                <option value="IPS">IPS</option>
                <option value="Bahasa">Bahasa</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- Submit -->
      <div class="card">
        <div class="card-body text-center">
          <p class="text-muted mb-3">
            <small>Dengan mendaftar, saya menyatakan bahwa data yang saya isi adalah benar dan dapat dipertanggungjawabkan.</small>
          </p>
          <button type="submit" class="btn btn-primary btn-lg px-5">
            <i class="fa fa-paper-plane me-2"></i>Daftar Sekarang
          </button>
          <a href="<?php echo base_url(); ?>/public/ppdb_check.php" class="btn btn-outline-secondary btn-lg px-5 ms-2">
            <i class="fa fa-search me-2"></i>Cek Status
          </a>
        </div>
      </div>
    </form>
  <?php endif; ?>
</div>

<?php require __DIR__ . '/_footer.php'; ?>
