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

/* =========================
   PROTEKSI LOGIN
========================= */
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    die("Akses ditolak!");
}

$npsn = $_SESSION['username'];

/* =========================
   VALIDASI ID
========================= */
if (!isset($_GET['id'])) {
    die("ID tidak ditemukan!");
}

$id = intval($_GET['id']);

/* =========================
   AMBIL DATA LAMA
========================= */
$stmt = $conn->prepare("
    SELECT * FROM rekening_koran 
    WHERE id_koran = ? AND npsn = ?
");
$stmt->bind_param("is", $id, $npsn);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();

if (!$data) {
    die("Data tidak ditemukan!");
}

/* =========================
   UPDATE DATA
========================= */
if (isset($_POST['update'])) {

    $tahun       = $_POST['tahun'];
    $bulan       = $_POST['bulan'];
    $saldo_awal  = str_replace('.', '', $_POST['saldo_awal']);
    $saldo_akhir = str_replace('.', '', $_POST['saldo_akhir']);
    $upload_file = $data['upload_file'];

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

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

        $ext = strtolower(pathinfo($_FILES['upload_file']['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf','jpg','jpeg','png'];

        if (!in_array($ext, $allowed)) {
            die("Format file tidak diizinkan!");
        }

        if ($upload_file && file_exists($folder.$upload_file)) {
            unlink($folder.$upload_file);
        }

        $upload_file = 'rekening_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['upload_file']['tmp_name'], $folder.$upload_file);
    }

    $stmt = $conn->prepare("
        UPDATE rekening_koran SET
            tahun = ?,
            bulan = ?,
            saldo_awal = ?,
            saldo_akhir = ?,
            upload_file = ?
        WHERE id_koran = ? AND npsn = ?
    ");

    $stmt->bind_param(
        "ssddsis",
        $tahun,
        $bulan,
        $saldo_awal,
        $saldo_akhir,
        $upload_file,
        $id,
        $npsn
    );

    if ($stmt->execute()) {
        header("Location: list_rekening_koran.php?status=update");
        exit;
    } else {
        echo "Gagal update data!";
    }

}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Edit Rekening Koran</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
</head>

<body class="bg-light">

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

<div class="card shadow-sm">
    <div class="card-header bg-warning text-dark">
        <i class="bi bi-pencil-square"></i> Edit Rekening Koran
    </div>

    <div class="card-body">

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

        <div class="row mb-3">
            <div class="col-md-6">
                <label class="form-label">NPSN</label>
                <input type="text" class="form-control" value="<?= $data['npsn'] ?>" readonly>
            </div>
            <div class="col-md-6">
                <label class="form-label">Nama Sekolah</label>
                <input type="text" class="form-control" value="<?= $data['nama_sekolah'] ?>" readonly>
            </div>
        </div>

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

            <div class="col-md-4">
                <label class="form-label">Bulan</label>
                <select name="bulan" class="form-select" required>
                    <?php
                    $bulanList = [
                        'Januari','Februari','Maret','April','Mei','Juni',
                        'Juli','Agustus','September','Oktober','November','Desember'
                    ];
                    foreach ($bulanList as $b) {
                        $selected = ($b == $data['bulan']) ? 'selected' : '';
                        echo "<option value=\"$b\" $selected>$b</option>";
                    }
                    ?>
                </select>
            </div>

            <div class="col-md-4">
                <label class="form-label">Saldo Awal</label>
                <input type="text" name="saldo_awal" class="form-control"
                       value="<?= number_format($data['saldo_awal'],0,',','.') ?>" required>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-4">
                <label class="form-label">Saldo Akhir</label>
                <input type="text" name="saldo_akhir" class="form-control"
                       value="<?= number_format($data['saldo_akhir'],0,',','.') ?>" required>
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label">Upload File Baru (Opsional)</label>
            <input type="file" name="upload_file" class="form-control">
            <?php if ($data['upload_file']) { ?>
                <small class="text-muted">
                    File lama: <?= $data['upload_file'] ?>
                </small>
            <?php } ?>
        </div>

        <div class="text-end">
            <a href="list_rekening_koran.php" class="btn btn-secondary">
                <i class="bi bi-arrow-left"></i> Kembali
            </a>
            <button type="submit" name="update" class="btn btn-warning">
                <i class="bi bi-save"></i> Update
            </button>
        </div>

    </form>

    </div>
</div>

</div>
</body>
</html>
