<?php
include 'aksi/koneksi.php';
include '_header.php';
include '_nav.php';
include '_sidebar.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

$sessionCabang = intval($sessionCabang);
$data = query("SELECT * FROM stok_pm_pending WHERE stok_pm_pending_cabang = $sessionCabang ORDER BY stok_pm_pending_barang_id DESC");

// Proses Edit Data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit'])) {
    $id = intval($_POST['stok_pm_pending_id']);
    $jumlah = intval($_POST['jumlah']);

    if ($id > 0 && $jumlah >= 0) {
        $query = "UPDATE stok_pm_pending SET stok_pm_pending_jumlah = $jumlah WHERE stok_pm_pending_id = $id";
        mysqli_query($conn, $query);
    }
    echo "<script>alert('Data stok berhasil diperbarui.');window.location.href = 'stok_plus_min_persetujuan';</script>";
    exit;
}

// Proses Setujui
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve'])) {
    $id = intval($_POST['stok_pm_pending_id']);
    $query = "SELECT * FROM stok_pm_pending WHERE stok_pm_pending_id = $id";
    $result = mysqli_query($conn, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $data = mysqli_fetch_assoc($result);
        $jenis = strtolower($data['stok_pm_pending_jenis']);

        if ($jenis == 'masuk' || $jenis == 'plus') {
            $updateStock = "UPDATE barang SET barang_stock = barang_stock + {$data['stok_pm_pending_jumlah']} WHERE barang_id = {$data['stok_pm_pending_barang_id']}";
        } elseif ($jenis == 'keluar' || $jenis == 'min') {
            $updateStock = "UPDATE barang SET barang_stock = barang_stock - {$data['stok_pm_pending_jumlah']} WHERE barang_id = {$data['stok_pm_pending_barang_id']}";
        } else {
            die("Jenis transaksi tidak dikenali: $jenis");
        }

        if (!mysqli_query($conn, $updateStock)) {
            die("Gagal update stok barang: " . mysqli_error($conn));
        }

        // Insert ke riwayat
        $barang_id   = $data['stok_pm_pending_barang_id'];
        $barang_kode = mysqli_real_escape_string($conn, $data['stok_pm_pending_barang_kode']);
        $jumlah      = $data['stok_pm_pending_jumlah'];
        $status      = 'selesai';
        $jenis       = mysqli_real_escape_string($conn, $data['stok_pm_pending_jenis']);
        $keterangan  = mysqli_real_escape_string($conn, $data['stok_pm_pending_keterangan']);
        $user_id     = $data['stok_pm_pending_user_id'];
        $cabang_id   = $data['stok_pm_pending_cabang'];

        $insertRiwayat = "INSERT INTO stok_pm_riwayat (
            stok_pm_riwayat_barang_id,
            stok_pm_riwayat_barang_kode,
            stok_pm_riwayat_jumlah,
            stok_pm_riwayat_status,
            stok_pm_riwayat_jenis,
            stok_pm_riwayat_tanggal,
            stok_pm_riwayat_user_id,
            stok_pm_riwayat_keterangan,
            stok_pm_riwayat_cabang
        ) VALUES (
            $barang_id,
            '$barang_kode',
            $jumlah,
            '$status',
            '$jenis',
            NOW(),
            $user_id,
            '$keterangan',
            $cabang_id
        )";

        if (!mysqli_query($conn, $insertRiwayat)) {
            die("Gagal input ke stok_pm_riwayat: " . mysqli_error($conn));
        }

        if (!mysqli_query($conn, "UPDATE stok_pm_pending SET stok_pm_pending_status = 'selesai' WHERE stok_pm_pending_id = $id")) {
            die("Gagal update status selesai: " . mysqli_error($conn));
        }

        echo "<script>alert('Persetujuan berhasil!');window.location.href = 'stok_plus_min_persetujuan';</script>";
        exit;
    }
}

// Proses Tolak
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reject'])) {
    $id = intval($_POST['stok_pm_pending_id']);
    if (!mysqli_query($conn, "UPDATE stok_pm_pending SET stok_pm_pending_status = 'ditolak' WHERE stok_pm_pending_id = $id")) {
        die("Gagal update status ditolak: " . mysqli_error($conn));
    }

    echo "<script>alert('Permintaan telah ditolak.');window.location.href = 'stok_plus_min_persetujuan';</script>";
    exit;
}

// Proses Setujui Semua
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['approve_all'])) {
    $result = mysqli_query($conn, "SELECT * FROM stok_pm_pending WHERE stok_pm_pending_status = 'menunggu' AND stok_pm_pending_cabang = $sessionCabang");

    while ($data = mysqli_fetch_assoc($result)) {
        $id = $data['stok_pm_pending_id'];
        $jenis = strtolower($data['stok_pm_pending_jenis']);

        if ($jenis == 'masuk' || $jenis == 'plus') {
            $updateStock = "UPDATE barang SET barang_stock = barang_stock + {$data['stok_pm_pending_jumlah']} WHERE barang_id = {$data['stok_pm_pending_barang_id']}";
        } elseif ($jenis == 'keluar' || $jenis == 'min') {
            $updateStock = "UPDATE barang SET barang_stock = barang_stock - {$data['stok_pm_pending_jumlah']} WHERE barang_id = {$data['stok_pm_pending_barang_id']}";
        }

        mysqli_query($conn, $updateStock);

        // Riwayat
        $insertRiwayat = "INSERT INTO stok_pm_riwayat (
            stok_pm_riwayat_barang_id,
            stok_pm_riwayat_barang_kode,
            stok_pm_riwayat_jumlah,
            stok_pm_riwayat_status,
            stok_pm_riwayat_jenis,
            stok_pm_riwayat_tanggal,
            stok_pm_riwayat_user_id,
            stok_pm_riwayat_keterangan,
            stok_pm_riwayat_cabang
        ) VALUES (
            {$data['stok_pm_pending_barang_id']},
            '{$data['stok_pm_pending_barang_kode']}',
            {$data['stok_pm_pending_jumlah']},
            'selesai',
            '{$data['stok_pm_pending_jenis']}',
            NOW(),
            {$data['stok_pm_pending_user_id']},
            '{$data['stok_pm_pending_keterangan']}',
            {$data['stok_pm_pending_cabang']}
        )";
        mysqli_query($conn, $insertRiwayat);

        mysqli_query($conn, "UPDATE stok_pm_pending SET stok_pm_pending_status = 'selesai' WHERE stok_pm_pending_id = $id");
    }

    echo "<script>alert('Semua permintaan berhasil disetujui!');window.location.href = 'stok_plus_min_persetujuan';</script>";
    exit;
}

// Proses Tolak Semua
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reject_all'])) {
    mysqli_query($conn, "UPDATE stok_pm_pending SET stok_pm_pending_status = 'ditolak' WHERE stok_pm_pending_status = 'menunggu' AND stok_pm_pending_cabang = $sessionCabang");
    echo "<script>alert('Semua permintaan telah ditolak!');window.location.href = 'stok_plus_min_persetujuan';</script>";
    exit;
}

?>


<div class="content-wrapper">
    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Data Transaksi Stok Pending</h3>
                </div>
                <div class="card-body">
                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>No.</th>
                                <th>Barang</th>
                                <th>Kode Barang</th>
                                <th>Jenis</th>
                                <th>Jumlah</th>
                                <th>Keterangan</th>
                                <th>User</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $query = "SELECT sp.*, b.barang_nama, u.user_nama 
                                      FROM stok_pm_pending sp 
                                      LEFT JOIN barang b ON sp.stok_pm_pending_barang_id = b.barang_id 
                                      LEFT JOIN user u ON sp.stok_pm_pending_user_id = u.user_id 
                                      WHERE sp.stok_pm_pending_status = 'menunggu' AND sp.stok_pm_pending_cabang = $sessionCabang 
                                      ORDER BY sp.stok_pm_pending_id DESC";
                            $result = mysqli_query($conn, $query);
                            $i = 1;
                            while ($row = mysqli_fetch_assoc($result)):
                            ?>
                            <tr>
                                <td><?= $i++; ?></td>
                                <td><?= htmlspecialchars($row['barang_nama']); ?></td>
                                <td><?= htmlspecialchars($row['stok_pm_pending_barang_kode']); ?></td>
                                <td><?= ucfirst(htmlspecialchars($row['stok_pm_pending_jenis'])); ?></td>
                                <td><?= intval($row['stok_pm_pending_jumlah']); ?></td>
                                <td><?= htmlspecialchars($row['stok_pm_pending_keterangan']); ?></td>
                                <td><?= htmlspecialchars($row['user_nama']); ?></td>
                                <td><?= htmlspecialchars($row['stok_pm_pending_status']); ?></td>
                                <td>
                                    
                                    <form action="" method="POST" style="display:inline-block;">
                                        <input type="hidden" name="stok_pm_pending_id" value="<?= $row['stok_pm_pending_id']; ?>">
                                        <button type="submit" name="approve" class="btn btn-success btn-sm">Setujui</button>
                                    </form>
                                    <form action="" method="POST" style="display:inline-block;">
                                        <input type="hidden" name="stok_pm_pending_id" value="<?= $row['stok_pm_pending_id']; ?>">
                                        <button type="submit" name="reject" class="btn btn-danger btn-sm">Tolak</button>
                                    </form>
                                    <button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#editModal<?= $row['stok_pm_pending_id']; ?>">Edit</button>
                                </td>
                            </tr>

                            <div class="modal fade" id="editModal<?= $row['stok_pm_pending_id']; ?>" tabindex="-1" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Edit Stok</h5>
                                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                                        </div>
                                        <form action="" method="POST">
                                            <div class="modal-body">
                                                <input type="hidden" name="stok_pm_pending_id" value="<?= $row['stok_pm_pending_id']; ?>">
                                                <div class="form-group">
                                                    <label>Jumlah</label>
                                                    <input type="number" class="form-control" name="jumlah" value="<?= $row['stok_pm_pending_jumlah']; ?>" required>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                                                <button type="submit" name="edit" class="btn btn-primary">Simpan</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <form action="" method="POST" style="margin-bottom: 10px;">
    <button type="submit" name="approve_all" class="btn btn-success btn-sm" onclick="return confirm('Yakin ingin menyetujui semua data?')">Setujui Semua</button>
    <button type="submit" name="reject_all" class="btn btn-danger btn-sm" onclick="return confirm('Yakin ingin menolak semua data?')">Tolak Semua</button>
</form>

        </div>
    </section>
</div>

<?php require '_footer.php'; ?>

<script src="dist/plugins/datatables/jquery.dataTables.js"></script>
<script src="dist/plugins/datatables-bs4/js/dataTables.bootstrap4.js"></script>
<script>
    $(function () {
        $("#example1").DataTable();
    });
</script>
