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

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

$role       = $_SESSION['role'];
$npsn_login = $_SESSION['npsn'] ?? '';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("ID tidak valid");

/* =====================
   AMBIL DATA LAPORAN
===================== */
if ($role === 'admin') {
    $q = mysqli_query($conn,"SELECT * FROM upload_laporan WHERE id_laporan='$id'");
} else {
    $q = mysqli_query($conn,"
        SELECT * FROM upload_laporan
        WHERE id_laporan='$id' AND npsn='$npsn_login'
    ");
}

$r = mysqli_fetch_assoc($q);
if (!$r) die("⛔ Akses ditolak atau data tidak ditemukan");

/* =====================
   PROSES UPDATE
===================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

    // LOGIKA STATUS
    $status = ($r['status_verifikasi'] === 'ditolak')
        ? 'diajukan_ulang'
        : 'menunggu';

    /* =====================
       FILE LAPORAN
    ===================== */
    $file_laporan = $r['upload_laporan'];

    if (!empty($_FILES['upload_laporan']['name'])) {

        $ext  = strtolower(pathinfo($_FILES['upload_laporan']['name'], PATHINFO_EXTENSION));
        $size = $_FILES['upload_laporan']['size'];

        if ($ext !== 'pdf') die("File laporan harus PDF");
        if ($size > 50 * 1024 * 1024) die("Ukuran maksimal 50MB");

        $file_laporan = 'laporan_' . $r['npsn'] . '_' . time() . '.pdf';
        move_uploaded_file($_FILES['upload_laporan']['tmp_name'], "upload/" . $file_laporan);

        if (!empty($r['upload_laporan']) && file_exists("upload/".$r['upload_laporan'])) {
            unlink("upload/".$r['upload_laporan']);
        }
    }

    /* =====================
       FILE REKENING KORAN
    ===================== */
    $file_koran = $r['upload_rekening_koran'];

    if (!empty($_FILES['upload_rekening_koran']['name'])) {

        $ext = strtolower(pathinfo($_FILES['upload_rekening_koran']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['pdf','jpg','jpeg','png'])) {
            die("Rekening koran harus PDF / JPG / PNG");
        }

        $file_koran = 'koran_' . $r['npsn'] . '_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['upload_rekening_koran']['tmp_name'], "upload/" . $file_koran);

        if (!empty($r['upload_rekening_koran']) && file_exists("upload/".$r['upload_rekening_koran'])) {
            unlink("upload/".$r['upload_rekening_koran']);
        }
    }

    /* =====================
       UPDATE DATABASE
    ===================== */
    mysqli_query($conn,"
        UPDATE upload_laporan SET
            tgl_lapor              = '$tgl',
            bulan                  = '$bulan',
            tahun                  = '$tahun',
            upload_laporan         = '$file_laporan',
            upload_rekening_koran  = '$file_koran',
            status_verifikasi      = '$status',
            catatan_admin          = NULL,
            tgl_verifikasi         = NULL
        WHERE id_laporan='$id'
    ");

    header("Location: list_laporan.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Edit Laporan</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container mt-4">
<div class="card shadow-sm">
<div class="card-header bg-warning fw-bold">
✏️ Edit Laporan BOS
</div>

<div class="card-body">
<form method="post" enctype="multipart/form-data">

<div class="mb-2">
<label>NPSN</label>
<input type="text" class="form-control" value="<?= htmlspecialchars($r['npsn']) ?>" readonly>
</div>

<div class="mb-2">
<label>Nama Sekolah</label>
<input type="text" class="form-control" value="<?= htmlspecialchars($r['nama_sekolah']) ?>" readonly>
</div>

<div class="row">
<div class="col-md-4 mb-2">
<label>Tanggal Lapor</label>
<input type="date" name="tgl_lapor" class="form-control" value="<?= $r['tgl_lapor'] ?>" required>
</div>

<div class="col-md-4 mb-2">
<label>Bulan</label>
<input type="text" name="bulan" class="form-control" value="<?= $r['bulan'] ?>" required>
</div>

<div class="col-md-4 mb-2">
<label>Tahun</label>
<input type="number" name="tahun" class="form-control" value="<?= $r['tahun'] ?>" required>
</div>
</div>

<div class="mb-3">
<label>Rekening Koran</label><br>
<?php if(!empty($r['upload_rekening_koran'])){ ?>
    <a href="upload/<?= $r['upload_rekening_koran'] ?>"
       target="_blank"
       class="btn btn-info btn-sm mb-1">📑 Lihat File Lama</a>
<?php } ?>
<input type="file" name="upload_rekening_koran" class="form-control">
</div>

<div class="mb-3">
<label>File Laporan (PDF)</label><br>
<small class="text-muted">File lama: <?= $r['upload_laporan'] ?></small>
<input type="file" name="upload_laporan" class="form-control mt-1" accept="application/pdf">
</div>

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

</form>
</div>
</div>
</div>

</body>
</html>
