<?php 
include "header.php";
include "sidebar.php";
?>

<div class="main-panel">
    <div class="content">
        <div class="panel-header bg-primary-gradient">
            <div class="page-inner py-1">
                <div class="d-flex align-items-left align-items-md-center flex-column flex-md-row">
                    <div>
                        <h2 class="text-white pb-2 fw-bold">Voucher</h2>
                    </div>
                </div>
            </div>
        </div>

        <?php
        include('config/koneksi.php');

        // Inisialisasi variabel voucher
        $voucher = [
            'kd_voucher' => '',
            'nama' => '',
            'nominal' => '',
            'jenis' => '',
            'target' => '',
            'penggunaan' => '',
            'expired_at' => ''
        ];

        // Cek apakah ada ID di URL untuk edit
        if (isset($_GET['id'])) {
            $kd_voucher = $_GET['id'];

            // Query untuk mengambil data voucher berdasarkan kd_voucher
            $sql = "SELECT * FROM tb_voucher WHERE kd_voucher = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('s', $kd_voucher);
            $stmt->execute();
            $result = $stmt->get_result();

            // Jika voucher ditemukan, ambil data
            if ($result->num_rows > 0) {
                $voucher = $result->fetch_assoc();
            }
        }

        // Cek apakah form disubmit
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            // Ambil data dari form
            $kd_voucher = $_POST['kd_voucher'];
            $nama = $_POST['nama'];
            $nominal = $_POST['nominal'];
            $jenis = $_POST['jenis'];
            $target = $_POST['target'];
            $penggunaan = $_POST['penggunaan'];
            $expired_at = $_POST['expired_at'];

            // Jika kd_voucher sudah ada, berarti ini adalah update
            if (!empty($voucher['kd_voucher'])) {
                // Query untuk mengupdate data voucher
                $sql = "UPDATE tb_voucher SET 
                        nama = ?, 
                        nominal = ?, 
                        jenis = ?, 
                        target = ?, 
                        penggunaan = ?, 
                        expired_at = ? 
                        WHERE kd_voucher = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('sssssss', $nama, $nominal, $jenis, $target, $penggunaan, $expired_at, $voucher['kd_voucher']);
            } else {
                // Jika kd_voucher tidak ada, kita anggap ini adalah penambahan
                $sql = "INSERT INTO tb_voucher (kd_voucher, nama, nominal, jenis, target, penggunaan, created_at, expired_at) 
                        VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param('sssssss', $kd_voucher, $nama, $nominal, $jenis, $target, $penggunaan, $expired_at);
            }

            // Eksekusi query
            if ($stmt->execute()) {
                echo "<div class='alert alert-success'>Voucher berhasil " . (!empty($voucher['kd_voucher']) ? "diupdate!" : "ditambahkan!") . "</div>";
                // Reset form setelah berhasil
                $voucher = [
                    'kd_voucher' => '',
                    'nama' => '',
                    'nominal' => '',
                    'jenis' => '',
                    'target' => '',
                    'penggunaan' => '',
                    'expired_at' => ''
                ];
            } else {
                echo "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
            }
        }

        // Cek apakah ada kd_voucher yang dikirim melalui URL untuk hapus
        if (isset($_GET['kd_voucher'])) {
            $kd_voucher = $_GET['kd_voucher'];

            // Query untuk menghapus voucher
            $sql = "DELETE FROM tb_voucher WHERE kd_voucher = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('s', $kd_voucher);

            // Eksekusi query
            if ($stmt->execute()) {
                echo "<div class='alert alert-success'>Voucher berhasil dihapus.</div>";
            } else {
                echo "<div class='alert alert-danger'>Gagal menghapus voucher: " . $stmt->error . "</div>";
            }
            $stmt->close();
        }
        ?>

        <div class="container mt-5">
            <h2><?php echo !empty($voucher['kd_voucher']) ? 'Edit Voucher' : 'Tambah Voucher'; ?></h2>
            <form action="" method="POST">
                <div class="form-group">
                    <label for="kd_voucher">Kode Voucher:</label>
                    <input type="text" id="kd_voucher" name="kd_voucher" value="<?php echo htmlspecialchars($voucher['kd_voucher']); ?>" required class="form-control">
                </div>

                <div class="form-group">
                    <label for="nama">Nama:</label>
                    <input type="text" id="nama" name="nama" value="<?php echo htmlspecialchars($voucher['nama']); ?>" required class="form-control">
                </div>
                
                <div class="form-group">
                    <label for="nominal">Nominal:</label>
                    <input type="number" id="nominal" name="nominal" value="<?php echo htmlspecialchars($voucher['nominal']); ?>" required class="form-control">
                </div>
                
                <div class="form-group">
                    <label for="jenis">Jenis:</label>
                    <select id="jenis" name="jenis" required class="form-control">
                        <option value="">Pilih Jenis</option>
                        <option value="promosi" <?php echo ($voucher['jenis'] == 'promosi') ? 'selected' : ''; ?>>Promosi</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="target">Target TO:</label>
                    <input type="text" id="target" name="target" value="<?php echo htmlspecialchars($voucher['target']); ?>" required class="form-control">
                </div>
                
                <div class="form-group">
                    <label for="penggunaan">Penggunaan Voucher:</label>
                    <input type="text" id="penggunaan" name="penggunaan" value="<?php echo htmlspecialchars($voucher['penggunaan']); ?>" required class="form-control">
                </div>
                
                <div class="form-group">
                    <label for="expired_at">Tanggal Expired:</label>
                    <input type="datetime-local" id="expired_at" name="expired_at" value="<?php echo date('Y-m-d\TH:i', strtotime($voucher['expired_at'])); ?>" required class="form-control">
                </div>
                
                <button type="submit" class="btn btn-primary"><?php echo !empty($voucher['kd_voucher']) ? 'Update Voucher' : 'Tambah Voucher'; ?></button>
            </form>
        </div>

        <?php
        // Query untuk mengambil data voucher
        $sql = "SELECT * FROM tb_voucher";
        $result = mysqli_query($conn, $sql);
        ?>

        <div class="container mt-5">
            <h2>Daftar Voucher</h2>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Kode Voucher</th>
                        <th>Nama</th>
                        <th>Nominal</th>
                        <th>Jenis</th>
                        <th>Target</th>
                        <th>Penggunaan</th>
                        <th>Tanggal Dibuat</th>
                        <th>Tanggal Expired</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Cek apakah ada data voucher
                    if (mysqli_num_rows($result) > 0) {
                        // Loop melalui hasil query
                        while ($row = mysqli_fetch_assoc($result)) {
                            echo "<tr>";
                            echo "<td>" . htmlspecialchars($row['kd_voucher']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['nama']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['nominal']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['jenis']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['target']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['penggunaan']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['created_at']) . "</td>";
                            echo "<td>" . htmlspecialchars($row['expired_at']) . "</td>";
                            echo "<td>
                                <a href='voucher.php?id=" . urlencode($row['kd_voucher']) . "' class='btn btn-warning'>Edit</a>
                                <a href='voucher.php?kd_voucher=" . urlencode($row['kd_voucher']) . "' class='btn btn-danger' onclick='return confirm(\"Yakin ingin menghapus voucher ini?\")'>Hapus</a>
                              </td>";
                            echo "</tr>";
                        }
                    } else {
                        echo "<tr><td colspan='9' class='text-center'>Tidak ada data voucher.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include "footer.php"; ?>
