<?php
require_once __DIR__ . "/../../app/config/auth.php";
require_login();
require_once __DIR__ . "/../../app/config/app.php";
require_once __DIR__ . "/../../app/config/session.php";
require_once __DIR__ . "/../../app/config/koneksi.php";

// Ambil user login
$nama     = getSession('pengurus_nama') ?? 'Pengurus';
$jabatan  = getSession('pengurus_jabatan') ?? '—';
$fotoUser = getSession('pengurus_foto')
    ? base_url("/assets/img/pengurus/" . getSession('pengurus_foto'))
    : base_url("/assets/img/pengurus/user_default.png");

function esc($v) { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$currentPage = "kegiatan";

// Pastikan ada ID
if (!isset($_GET['id'])) {
    header("Location: semua_kegiatan.php");
    exit;
}
$id = intval($_GET['id']);

// Ambil data kegiatan
$q = $koneksi->prepare("SELECT * FROM kegiatan WHERE id = ?");
$q->bind_param("i", $id);
$q->execute();
$result = $q->get_result();

if ($result->num_rows == 0) {
    die("Data tidak ditemukan!");
}

$data = $result->fetch_assoc();
$oldFoto = $data['foto'];

$success = "";
$err = "";

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

    $namaKegiatan = esc($_POST['nama_kegiatan']);
    $tanggal      = esc($_POST['tanggal']);
    $deskripsi    = esc($_POST['deskripsi']);

    if (!empty($namaKegiatan) && !empty($tanggal) && !empty($deskripsi)) {

        $folder = __DIR__ . "/../../assets/img/kegiatan/";
        if (!file_exists($folder)) mkdir($folder, 0777, true);

        $fotoName = $oldFoto;

        if (!empty($_FILES['foto']['name'])) {
            $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
            $fotoName = time() . "-" . rand(100,999) . "." . $ext;

            if (move_uploaded_file($_FILES['foto']['tmp_name'], $folder . $fotoName)) {
                if ($oldFoto && file_exists($folder . $oldFoto)) {
                    unlink($folder . $oldFoto);
                }
            }
        }

        $sql = $koneksi->prepare("
            UPDATE kegiatan 
            SET nama_kegiatan=?, tanggal=?, deskripsi=?, foto=? 
            WHERE id=?
        ");
        $sql->bind_param("ssssi", $namaKegiatan, $tanggal, $deskripsi, $fotoName, $id);

        if ($sql->execute()) {
            $success = "Agenda berhasil diperbarui 🎉";
        } else {
            $err = "Gagal memperbarui data!";
        }

    } else {
        $err = "Semua field wajib diisi!";
    }
}
?>
<!doctype html>
<html lang="id">
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width,initial-scale=1">
   <title>Edit Agenda — Sistem Informasi Masjid</title>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

   <link rel="stylesheet" href="<?= base_url('/assets/css/dashboard/sidebar.css'); ?>">
   <link rel="stylesheet" href="<?= base_url('/assets/css/dashboard/layout.css'); ?>">
   <link rel="stylesheet" href="<?= base_url('/assets/css/dashboard/dashboard.css'); ?>">
   <link rel="stylesheet" href="<?= base_url('/assets/css/dashboard/widgets.css'); ?>">

</head>

<body class="dashboard-page">

<?php include __DIR__ . "/../../assets/component/dashboard_sidebar.php"; ?>

<div id="content-wrapper" class="content-wrapper">
<?php include __DIR__ . "/../../assets/component/dashboard_navbar.php"; ?>

<main class="container-fluid mt-4">
    <h1 class="page-title">Edit Agenda</h1>
    <p class="subtitle small text-muted">Update agenda masjid — <?= date('d M Y'); ?></p>

    <div class="card shadow-sm mt-4">
        <div class="card-header bg-warning text-dark fw-bold">
            Form Edit Agenda Masjid
        </div>

        <div class="card-body">

            <?php if (!empty($success)): ?>
                <div class="alert alert-success"><?= esc($success) ?></div>
            <?php endif; ?>

            <?php if (!empty($err)): ?>
                <div class="alert alert-danger"><?= esc($err) ?></div>
            <?php endif; ?>

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

                <div class="mb-3">
                    <label class="form-label fw-bold">Nama Kegiatan</label>
                    <input type="text" class="form-control" name="nama_kegiatan" required
                           value="<?= esc($data['nama_kegiatan']); ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Tanggal Kegiatan</label>
                    <input type="date" class="form-control" name="tanggal" required
                           value="<?= esc($data['tanggal']); ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Deskripsi</label>
                    <textarea class="form-control" name="deskripsi" rows="3" required><?= esc($data['deskripsi']); ?></textarea>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Foto Kegiatan</label><br>
                    <img src="<?= base_url('/assets/img/kegiatan/' . esc($data['foto'])); ?>"
                         style="width:150px;height:90px;object-fit:cover;border-radius:6px;">
                    <input type="file" class="form-control mt-2" name="foto" accept="image/*">
                    <small class="text-muted">Biarkan kosong jika tidak ingin ganti foto</small>
                </div>

                <button class="btn btn-warning px-4 text-dark fw-bold">
                    <i class="fa fa-save"></i> Update
                </button>

                <a href="semua_kegiatan.php" class="btn btn-secondary">
                    <i class="fa fa-arrow-left"></i> Kembali
                </a>

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

</main>

</div>

<?php include __DIR__ . "/../../assets/component/dashboard_footer.php"; ?>

</body>
</html>
