<?php
$unit_name = '';
if ($_GET['cabang'] == 'khm-wonorejo') {
    $unit_name = 'KHM Wonorejo';
    $url = $baseUrlKHMWonorejo;
    $DBname = "pembelian_obat_pajak_wonorejo";
} elseif ($_GET['cabang'] == 'khm-klakah') {
    $unit_name = 'KHM Klakah';
    $url = $baseUrlKHMKlakah;
    $DBname = "pembelian_obat_pajak_klakah";
} elseif ($_GET['cabang'] == 'khm-tunjung') {
    $unit_name = 'KHM Tunjung';
    $url = $baseUrlKHMTunjung;
    $DBname = "pembelian_obat_pajak_tunjung";
}

require "khm/php_reader/excel_reader2.php";

use Shuchkin\SimpleXLSX;


?>
<div class="container-fluid">
    <h3 class="h3 mb-2 text-gray-800">Rekap Pembelian Obat Pajak <?= $unit_name ?></h3>
    <button class="btn btn-sm btn-danger mb-2" data-toggle="modal" data-target="#addData">Tambah Data</button>
    <button class="btn btn-sm btn-danger mb-2" data-toggle="modal" data-target="#impData">Import Data Excel</button>
    <!-- Modal Import -->
    <div class="modal fade" id="impData" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title fs-5" id="staticBackdropLabel">Import Data dari Excel</h4>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        Pastikan Excel Hanya Memiliki Struktur Seperti Ini :
                        <img src="khm/contoh_excel.jpg" class="w-100" alt="">
                        <br><br>
                        <input type="file" name="fileImport" class="form-control mb-2" id="">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" name="import" class="btn btn-sm btn-danger">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php
    if (isset($_POST['import'])) {
        $target_dir = "khm/importExcel/";
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $file = $_FILES['fileImport']['tmp_name'];
        $file_name = $target_dir . basename($_FILES['fileImport']['name']);

        if (move_uploaded_file($file, $file_name)) {
            if ($xlsx = SimpleXLSX::parse($file_name)) {
                $data = $xlsx->rows();

                // Mulai transaksi
                $con_sips->begin_transaction();

                try {
                    foreach ($data as $row) {
                        // Asumsi kolom pada Excel mengikuti urutan berikut:
                        // tanggal, supplier, no_faktur, dpp, ppn, total, no_faktur_pajak, foto_faktur, foto_faktur_pajak
                        $tanggal = $row[0];
                        $supplier = $row[1];
                        $no_faktur = $row[2];
                        $dpp = $row[3];
                        $ppn = $row[4];
                        $total = $row[5];
                        $no_faktur_pajak = $row[6];


                        $sql = "INSERT INTO $DBname (tanggal, supplier, no_faktur, dpp, ppn, total, no_faktur_pajak) 
                                VALUES (?, ?, ?, ?, ?, ?, ?)";
                        if ($stmt = $con_sips->prepare($sql)) {
                            $stmt->bind_param("sssssss", $tanggal, $supplier, $no_faktur, $dpp, $ppn, $total, $no_faktur_pajak);
                            $stmt->execute();
                            $stmt->close();
                        } else {
                            throw new Exception($con_sips->error);
                        }
                    }

                    // Commit transaksi
                    $con_sips->commit();
                    echo "Data successfully imported.";
                } catch (Exception $e) {
                    // Rollback transaksi jika terjadi error
                    $con_sips->rollback();
                    echo "Error importing data: " . $e->getMessage();
                }
            } else {
                echo SimpleXLSX::parseError();
            }
        } else {
            echo "
                <script>
                    alert('Gagal');
                    document.location.href='index.php?hal=$_GET[hal]&unit=$_GET[unit]&cabang=$_GET[cabang]';
                </script>
            ";
        }
        $con_sips->query("DELETE FROM " . $DBname . " WHERE tanggal = '0000-00-00'");
        echo "
            <script>
                alert('Successfully');
                document.location.href='index.php?hal=$_GET[hal]&unit=$_GET[unit]&cabang=$_GET[cabang]';
            </script>
        ";
    }
    ?>

    <!-- Modal Add -->
    <div class="modal fade" id="addData" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title fs-5" id="staticBackdropLabel">Tambah Data</h4>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <label class="mb-0">Tanggal</label>
                                <input type="date" class="form-control mt-0 mb-2" required name="tanggal">
                            </div>
                            <div class="col-md-6">
                                <label class="mb-0">Supplier</label>
                                <input type="text" class="form-control mt-0 mb-2" required name="supplier">
                            </div>
                            <div class="col-md-6">
                                <label class="mb-0">Nomor Faktur</label>
                                <input type="text" class="form-control mt-0 mb-2" required name="no_faktur">
                            </div>
                            <div class="col-md-6">
                                <label class="mb-0">Nomor Faktur Pajak</label>
                                <input type="text" class="form-control mt-0 mb-2" required name="no_faktur_pajak">
                            </div>
                            <div class="col-md-5">
                                <label class="mb-0">DPP</label>
                                <input type="text" oninput="changePPNTotal()" class="form-control mt-0 mb-2" required name="dpp" id="dpp">
                            </div>
                            <div class="col-md-2">
                                <label class="mb-0">PPN (%)</label>
                                <input type="number" value="11" class="form-control mt-0 mb-2" required id="ppnPersen">
                            </div>
                            <div class="col-md-5">
                                <label class="mb-0">Total PPN</label>
                                <input type="text" class="form-control mt-0 mb-2" required name="ppn" id="jumlahPPN">
                            </div>
                            <div class="col-md-12">
                                <label class="mb-0">Total</label>
                                <input type="text" class="form-control mt-0 mb-2" required name="total" id="total">
                            </div>
                            <div class="col-md-6">
                                <label class="mb-0">Foto Faktur</label>
                                <input type="file" class="form-control mt-0 mb-2" required name="foto_faktur">
                            </div>
                            <div class="col-md-6">
                                <label class="mb-0">Foto Faktur Pajak</label>
                                <input type="file" class="form-control mt-0 mb-2" required name="foto_faktur_pajak">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" name="add" class="btn btn-sm btn-danger">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        function changePPNTotal() {
            var dpp = document.getElementById("dpp");
            var ppnPersen = document.getElementById("ppnPersen");
            var jumlahPPN = document.getElementById("jumlahPPN");
            var total = document.getElementById("total");

            var ppnTot = dpp.value * ppnPersen.value / 100;
            jumlahPPN.value = ppnTot;

            total.value = parseFloat(dpp.value) + parseFloat(ppnTot);
        }
    </script>
    <?php
    if (isset($_POST['add'])) {
        $target_dir = "khm/faktur/";

        $nama_foto_faktur = date('dmyhis') . basename($_FILES["foto_faktur"]["name"]);
        $foto_faktur = $target_dir . $nama_foto_faktur;

        $nama_foto_faktur_pajak = date('dmyhis') . basename($_FILES["foto_faktur_pajak"]["name"]);
        $foto_faktur_pajak = $target_dir . $nama_foto_faktur_pajak;

        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        move_uploaded_file($_FILES["foto_faktur"]["tmp_name"], $foto_faktur);
        move_uploaded_file($_FILES["foto_faktur_pajak"]["tmp_name"], $foto_faktur_pajak);

        $con_sips->query("INSERT INTO " . $DBname . " (`tanggal`, `supplier`, `no_faktur`, `dpp`, `ppn`, `total`, `no_faktur_pajak`, `foto_faktur`, `foto_faktur_pajak`) VALUES ('$_POST[tanggal]','$_POST[supplier]','$_POST[no_faktur]','$_POST[dpp]','$_POST[ppn]','$_POST[total]','$_POST[no_faktur_pajak]','" . $nama_foto_faktur . "','" . $nama_foto_faktur_pajak . "')");

        echo "
            <script>
                alert('Successfully');
                document.location.href='index.php?hal=$_GET[hal]&unit=$_GET[unit]&cabang=$_GET[cabang]';
            </script>
        ";
    }
    ?>
    <div class="card shadow p-2">
        <form method="POST">
            <div class="row">
                <div class="col-md-5">
                    <label class="mb-0">Mulai Tanggal</label>
                    <input type="date" class="form-control mt-0" name="tglmulai" value=<?= $_POST['tglmulai'] ?? $_GET['tglmulai'] ?? '' ?>>
                </div>
                <div class="col-md-5">
                    <label class="mb-0">Hingga Tanggal</label>
                    <input type="date" class="form-control mt-0" name="tglhingga" value=<?= $_POST['tglhingga'] ?? $_GET['tglhingga'] ?? '' ?>>
                </div>
                <div class="col-md-2">
                    <br>
                    <button class="btn btn-danger" name="fil"><i class="bi bi-funnel-fill"></i></button>
                </div>
            </div>
        </form>
    </div>

    <div class="card shadow p-2 mt-2">
        <div class="table-responsive">
            <table class="table-striped" id="myTable">
                <thead>
                    <tr>
                        <th>Tgl</th>
                        <th>Supplier</th>
                        <th>No. Faktur</th>
                        <th>DPP</th>
                        <th>PPN</th>
                        <th>Total</th>
                        <th>No. Faktur Pajak</th>
                        <th>Foto Faktur</th>
                        <th>Foto Faktur Pajak</th>
                        <th>Act</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if (isset($_POST['fil'])) {
                        $getPembelianPajak = $con_sips->query("SELECT * FROM " . $DBname . " WHERE tanggal >= '$_POST[tglmulai]' AND tanggal <= '$_POST[tglhingga]' ORDER BY tanggal ASC");
                    } else if (isset($_GET['tglmulai'])) {
                        $getPembelianPajak = $con_sips->query("SELECT * FROM " . $DBname . " WHERE tanggal >= '$_GET[tglmulai]' AND tanggal <= '$_GET[tglhingga]' ORDER BY tanggal ASC");
                    } else {
                        $getPembelianPajak = $con_sips->query("SELECT * FROM " . $DBname . " ORDER BY tanggal ASC LIMIT 0");
                    }

                    $tglmulai = $_POST['tglmulai'] ?? $_GET['$tglmulai'] ?? '';
                    $tglhingga = $_POST['tglhingga'] ?? $_GET['$tglhingga'] ?? '';

                    foreach ($getPembelianPajak as $data) {
                    ?>
                        <tr>
                            <td><?= $data['tanggal'] ?></td>
                            <td><?= $data['supplier'] ?></td>
                            <td><?= $data['no_faktur'] ?></td>
                            <td><?= number_format($data['dpp'] ?? 0, decimal_separator: ',', thousands_separator: '.') ?></td>
                            <td><?= number_format($data['ppn'] ?? 0, decimal_separator: ',', thousands_separator: '.') ?></td>
                            <td><?= number_format($data['total'] ?? 0, decimal_separator: ',', thousands_separator: '.') ?></td>
                            <td><?= $data['no_faktur_pajak'] ?></td>
                            <td><img src="khm/faktur/<?= $data['foto_faktur'] ?>" style="width:100px;" alt=""></td>
                            <td><img src="khm/faktur/<?= $data['foto_faktur_pajak'] ?>" style="width:100px;" alt=""></td>
                            <td>
                                <button class="btn btn-sm btn-success mb-1" type="button" data-toggle="modal" data-target="#update<?= $data['id'] ?>"><i class="bi bi-pencil"></i></button>
                                <a class="btn btn-sm btn-danger" href="index.php?hal=<?= $_GET['hal'] ?>&unit=<?= $_GET['unit'] ?>&cabang=<?= $_GET['cabang'] ?>&delId=<?= $data['id'] ?>&faktur=<?= $data['foto_faktur'] ?>&fakturpajak=<?= $data['foto_faktur_pajak'] ?>&tglmulai=<?= $tglmulai ?>&tglhingga=<?= $tglhingga ?>" onclick="return confirm('Apakah Anda Yakin Ingin Menghapus Data ini ?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                        <!-- Modal -->
                        <div class="modal fade" id="update<?= $data['id'] ?>" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h4 class="modal-title fs-5" id="staticBackdropLabel">Update Data Pembelian</h4>
                                        <!-- <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button> -->
                                    </div>
                                    <form method="post" enctype="multipart/form-data">
                                        <div class="modal-body">
                                            <div class="row">
                                                <input type="text" hidden class="form-control mt-0 mb-2" name="id" value="<?= $data['id'] ?>">

                                                <div class="col-md-6">
                                                    <label class="mb-0">Tanggal</label>
                                                    <input type="date" class="form-control mt-0 mb-2" name="tanggal" value="<?= $data['tanggal'] ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="mb-0">Supplier</label>
                                                    <input type="text" class="form-control mt-0 mb-2" name="supplier" value="<?= $data['supplier'] ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="mb-0">Nomor Faktur</label>
                                                    <input type="text" class="form-control mt-0 mb-2" name="no_faktur" value="<?= $data['no_faktur'] ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="mb-0">Nomor Faktur Pajak</label>
                                                    <input type="text" class="form-control mt-0 mb-2" name="no_faktur_pajak" value="<?= $data['no_faktur_pajak'] ?>">
                                                </div>
                                                <div class="col-md-5">
                                                    <label class="mb-0">DPP</label>
                                                    <input type="text" oninput="changePPNTotal<?= $data['id'] ?>()" class="form-control mt-0 mb-2" name="dpp" value="<?= $data['dpp'] ?>" id="dpp<?= $data['id'] ?>">
                                                </div>
                                                <div class="col-md-2">
                                                    <label class="mb-0">PPN (%)</label>
                                                    <input type="number" value="11" class="form-control mt-0 mb-2" id="ppnPersen<?= $data['id'] ?>">
                                                </div>
                                                <div class="col-md-5">
                                                    <label class="mb-0">Total PPN</label>
                                                    <input type="text" class="form-control mt-0 mb-2" name="ppn" value="<?= $data['ppn'] ?>" id="jumlahPPN<?= $data['id'] ?>">
                                                </div>
                                                <div class="col-md-12">
                                                    <label class="mb-0">Total</label>
                                                    <input type="text" class="form-control mt-0 mb-2" name="total" value="<?= $data['total'] ?>" id="total<?= $data['id'] ?>">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="mb-0">Foto Faktur</label>
                                                    <input type="file" class="form-control mt-0 mb-2" name="foto_faktur">
                                                    <input type="text" style="visibility: hidden; width: 0.1px; height: 0.1px;" value="<?= $data['foto_faktur'] ?>" class="form-control mt-0 mb-2" name="old_foto_faktur">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="mb-0">Foto Faktur Pajak</label>
                                                    <input type="file" class="form-control mt-0 mb-2" name="foto_faktur_pajak">
                                                    <input type="text" style="visibility: hidden; width: 0.1px; height: 0.1px;" value="<?= $data['foto_faktur_pajak'] ?>" class="form-control mt-0 mb-2" name="old_foto_faktur_pajak">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Close</button>
                                            <button type="submit" name="update" class="btn btn-sm btn-success">Update</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <script>
                            function changePPNTotal<?= $data['id'] ?>() {
                                var dpp<?= $data['id'] ?> = document.getElementById("dpp<?= $data['id'] ?>");
                                var ppnPersen<?= $data['id'] ?> = document.getElementById("ppnPersen<?= $data['id'] ?>");
                                var jumlahPPN<?= $data['id'] ?> = document.getElementById("jumlahPPN<?= $data['id'] ?>");
                                var total<?= $data['id'] ?> = document.getElementById("total<?= $data['id'] ?>");

                                var ppnTot<?= $data['id'] ?> = dpp<?= $data['id'] ?>.value * ppnPersen<?= $data['id'] ?>.value / 100;
                                jumlahPPN<?= $data['id'] ?>.value = ppnTot<?= $data['id'] ?>;

                                total<?= $data['id'] ?>.value = parseFloat(dpp<?= $data['id'] ?>.value) - parseFloat(ppnTot<?= $data['id'] ?>);
                            }
                        </script>
                    <?php } ?>
                </tbody>
            </table>
            <?php
            if (isset($_POST['update'])) {
                $target_dir = "khm/faktur/";
                if (isset($_FILES['foto_faktur']) and $_FILES['foto_faktur']['name'] != '') {
                    $nama_foto_faktur = date('dmyhis') . basename($_FILES["foto_faktur"]["name"]);
                    $foto_faktur = $target_dir . $nama_foto_faktur;
                    move_uploaded_file($_FILES["foto_faktur"]["tmp_name"], $foto_faktur);

                    $con_sips->query("UPDATE " . $DBname . " SET foto_faktur = '$nama_foto_faktur' WHERE id = '$_POST[id]'");
                    unlink($target_dir . $_POST['old_foto_faktur']);
                }

                if (isset($_FILES['foto_faktur_pajak']) and $_FILES['foto_faktur_pajak']['name'] != '') {
                    $nama_foto_faktur_pajak = date('dmyhis') . basename($_FILES["foto_faktur_pajak"]["name"]);
                    $foto_faktur_pajak = $target_dir . $nama_foto_faktur_pajak;
                    move_uploaded_file($_FILES["foto_faktur_pajak"]["tmp_name"], $foto_faktur_pajak);

                    $con_sips->query("UPDATE " . $DBname . " SET foto_faktur_pajak = '$nama_foto_faktur_pajak' WHERE id = '$_POST[id]'");
                    unlink($target_dir . $_POST['old_foto_faktur_pajak']);
                }

                $con_sips->query("UPDATE " . $DBname . " SET tanggal='$_POST[tanggal]', supplier='$_POST[supplier]', no_faktur='$_POST[no_faktur]', no_faktur_pajak='$_POST[no_faktur_pajak]', dpp='$_POST[dpp]', ppn='$_POST[ppn]', total='$_POST[total]' WHERE id = '$_POST[id]'");

                echo "
                    <script>
                        alert('Successfully');
                        document.location.href='index.php?hal=$_GET[hal]&unit=$_GET[unit]&cabang=$_GET[cabang]';
                    </script>
                ";
            }


            if (isset($_GET['delId'])) {
                $target_dir = "khm/faktur/";
                if ($_GET['faktur'] != '') {
                    unlink($target_dir . $_GET['foto_faktur']);
                }
                if ($_GET['fakturpajak'] != '') {
                    unlink($target_dir . $_GET['fakturpajak']);
                }
                $con_sips->query("DELETE FROM " . $DBname . " WHERE id = '$_GET[delId]' ");
                echo "
                    <script>
                        alert('Successfully');
                        document.location.href='index.php?hal=$_GET[hal]&unit=$_GET[unit]&cabang=$_GET[cabang]&tglmulai=$_GET[tglmulai]&tglhingga=$_GET[tglhingga]';
                    </script>
                ";
            }
            ?>
        </div>
    </div>
</div>