<?php
session_start();
require_once __DIR__ . "/config/config.php";

/* =====================
   CEK LOGIN
===================== */
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: index.php");
    exit;
}

/* =====================
   AMBIL NPSN DARI SESSION
===================== */
$npsn = $_SESSION['npsn'] ?? '';
if ($npsn == '') {
    die("NPSN tidak ditemukan di session");
}

/* =====================
   AMBIL DATA SEKOLAH
===================== */
$stmt = $conn->prepare("
    SELECT npsn, nama_sekolah
    FROM sekolah
    WHERE npsn = ?
    LIMIT 1
");
$stmt->bind_param("s", $npsn);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    die("Data sekolah tidak ditemukan. Hubungi Admin.");
}

$sekolah = $res->fetch_assoc();
$nama    = $sekolah['nama_sekolah'];

/* =====================
   SIMPAN DATA
===================== */
if (isset($_POST['simpan'])) {

    $tgl   = $_POST['tgl_lapor'];
    $bulan = $_POST['bulan'];
    $tahun = $_POST['tahun'];

    /* =====================
       VALIDASI FILE LAPORAN
    ===================== */
    if ($_FILES['upload_laporan']['error'] !== 0) {
        echo "<script>alert('File laporan gagal diupload');history.back();</script>";
        exit;
    }

    $lapName = $_FILES['upload_laporan']['name'];
    $lapTmp  = $_FILES['upload_laporan']['tmp_name'];
    $lapSize = $_FILES['upload_laporan']['size'];
    $lapExt  = strtolower(pathinfo($lapName, PATHINFO_EXTENSION));

    if ($lapExt !== 'pdf') {
        echo "<script>alert('File laporan harus PDF');history.back();</script>";
        exit;
    }

    if ($lapSize > (50 * 1024 * 1024)) {
        echo "<script>alert('Ukuran laporan maksimal 50 MB');history.back();</script>";
        exit;
    }

    /* =====================
       VALIDASI REKENING KORAN
    ===================== */
    if ($_FILES['upload_rekening_koran']['error'] !== 0) {
        echo "<script>alert('Rekening koran wajib diupload');history.back();</script>";
        exit;
    }

    $rekName = $_FILES['upload_rekening_koran']['name'];
    $rekTmp  = $_FILES['upload_rekening_koran']['tmp_name'];
    $rekSize = $_FILES['upload_rekening_koran']['size'];
    $rekExt  = strtolower(pathinfo($rekName, PATHINFO_EXTENSION));

    $allowRek = ['pdf','jpg','jpeg','png'];
    if (!in_array($rekExt, $allowRek)) {
        echo "<script>alert('Rekening koran harus PDF / JPG / PNG');history.back();</script>";
        exit;
    }

    if ($rekSize > (20 * 1024 * 1024)) {
        echo "<script>alert('Ukuran rekening koran maksimal 20 MB');history.back();</script>";
        exit;
    }

    /* =====================
       FOLDER UPLOAD
    ===================== */
    $folder = "upload/";
    if (!is_dir($folder)) {
        mkdir($folder, 0777, true);
    }

    /* =====================
       NAMA FILE BARU
    ===================== */
    $fileLaporan  = 'laporan_' . $npsn . '_' . time() . '.pdf';
    $fileRekening = 'rekening_' . $npsn . '_' . time() . '.' . $rekExt;

    move_uploaded_file($lapTmp, $folder . $fileLaporan);
    move_uploaded_file($rekTmp, $folder . $fileRekening);

    /* =====================
       INSERT DATABASE
    ===================== */
    $stmt = $conn->prepare("
        INSERT INTO upload_laporan
        (npsn, nama_sekolah, tgl_lapor, bulan, tahun, upload_rekening_koran, upload_laporan, status_verifikasi)
        VALUES (?,?,?,?,?,?,?, 'menunggu')
    ");
    $stmt->bind_param(
        "sssssss",
        $npsn,
        $nama,
        $tgl,
        $bulan,
        $tahun,
        $fileRekening,
        $fileLaporan
    );

    if ($stmt->execute()) {
        header("Location: list_laporan.php");
        exit;
    } else {
        die("Gagal menyimpan data laporan");
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Tambah Laporan</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{background:#f8f9fa;}
.card{border-radius:14px;}
label{font-weight:600;}
</style>
</head>

<body>

<div class="container-fluid mt-4 px-4">

<div class="card shadow-sm">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">➕ Tambah Laporan</h5>
    </div>

    <div class="card-body">

    <form method="post" enctype="multipart/form-data">

        <div class="row mb-3">
            <div class="col-md-4">
                <label>NPSN</label>
                <input type="text" class="form-control" value="<?= htmlspecialchars($npsn) ?>" readonly>
            </div>
            <div class="col-md-8">
                <label>Nama Sekolah</label>
                <input type="text" class="form-control" value="<?= htmlspecialchars($nama) ?>" readonly>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-4">
                <label>Tanggal Lapor</label>
                <input type="date" name="tgl_lapor" class="form-control" required>
            </div>
            <div class="col-md-4">
                <label>Bulan</label>
                <select name="bulan" class="form-select" required>
                    <option value="">-- Pilih Bulan --</option>
                    <?php
                    $bulanArr = ['Januari','Februari','Maret','April','Mei','Juni',
                                 'Juli','Agustus','September','Oktober','November','Desember'];
                    foreach($bulanArr as $b){
                        echo "<option value='$b'>$b</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="col-md-4">
                <label>Tahun</label>
                <input type="number" name="tahun" class="form-control" value="<?= date('Y') ?>" required>
            </div>
        </div>

        <div class="mb-3">
            <label>Upload Rekening Koran</label>
            <input type="file" name="upload_rekening_koran"
                   class="form-control"
                   accept=".pdf,.jpg,.jpeg,.png" required>
            <small class="text-muted">PDF / JPG / PNG • Maks 20 MB</small>
        </div>

        <div class="mb-4">
            <label>Upload File Laporan</label>
            <input type="file" name="upload_laporan"
                   class="form-control"
                   accept="application/pdf" required>
            <small class="text-muted">PDF • Maks 50 MB</small>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" name="simpan" class="btn btn-success">
                💾 Simpan
            </button>
            <a href="list_laporan.php" class="btn btn-secondary">
                ↩️ Kembali
            </a>
        </div>

    </form>

    </div>
</div>

</div>

</body>
</html>
