<?php 
include 'template/header.php';
check_user_access(); // Both admin and kasir can access returns
?>

<br>

<?php
if(isset($_POST['process_return'])){
    $no_nota = $_POST['no_nota'];
    $idproduk = $_POST['idproduk'];
    $quantity = (int)$_POST['quantity'];
    $keterangan = htmlspecialchars($_POST['keterangan']);
    
    // Get product info
    $produk = mysqli_query($conn, "SELECT * FROM produk WHERE idproduk='$idproduk'");
    $produk_info = mysqli_fetch_assoc($produk);
    
    if($produk_info) {
        $harga_satuan = $produk_info['harga_jual'];
        $subtotal = $harga_satuan * $quantity;
        
        // Insert return record
        $insert_return = mysqli_query($conn, "INSERT INTO retur_barang (no_nota, idproduk, quantity, harga_satuan, subtotal, keterangan, user_id) 
                                              VALUES ('$no_nota', '$idproduk', '$quantity', '$harga_satuan', '$subtotal', '$keterangan', '{$_SESSION['id_login']}')");
        
        if($insert_return) {
            // Update product stock
            $new_stock = $produk_info['stock'] + $quantity;
            mysqli_query($conn, "UPDATE produk SET stock='$new_stock' WHERE idproduk='$idproduk'");
            
            // Update the original transaction in tb_nota (reduce quantity)
            $current_qty_result = mysqli_query($conn, "SELECT quantity FROM tb_nota WHERE no_nota='$no_nota' AND idproduk='$idproduk'");
            $current_qty_row = mysqli_fetch_assoc($current_qty_result);
            $new_qty = $current_qty_row['quantity'] - $quantity;
            
            if($new_qty <= 0) {
                // If quantity becomes 0 or less, remove the item from the transaction
                mysqli_query($conn, "DELETE FROM tb_nota WHERE no_nota='$no_nota' AND idproduk='$idproduk'");
            } else {
                // Otherwise, update the quantity
                mysqli_query($conn, "UPDATE tb_nota SET quantity='$new_qty' WHERE no_nota='$no_nota' AND idproduk='$idproduk'");
            }
            
            // Update the total amount in the laporan table to reflect the return
            if(!empty($no_nota)) {
                $current_laporan = mysqli_query($conn, "SELECT totalbeli FROM laporan WHERE no_nota='$no_nota'");
                $current_data = mysqli_fetch_assoc($current_laporan);
                $new_total = $current_data['totalbeli'] - $subtotal;
                
                mysqli_query($conn, "UPDATE laporan SET totalbeli='$new_total' WHERE no_nota='$no_nota'");
            }
            
            echo '<script>alert("Retur barang berhasil diproses");window.location="returns.php"</script>';
        } else {
            echo '<script>alert("Gagal memproses retur barang");</script>';
        }
    } else {
        echo '<script>alert("Produk tidak ditemukan");</script>';
    }
}
?>

<div class="card">
    <div class="card-header">
        <div class="card-tittle"><i class="fa fa-exchange-alt me-2"></i> Retur & Tukar Barang</div>
    </div>
    <form method="post">
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group mb-3">
                        <label>No. Nota:</label>
                        <div class="input-group">
                            <input type="text" name="no_nota" id="no_nota" class="form-control" placeholder="Masukkan nomor nota transaksi..." required>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-outline-secondary" onclick="loadNotaProducts()">Cari</button>
                            </div>
                        </div>
                        <small class="form-text text-muted">Masukkan nomor nota transaksi yang akan diretur</small>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Produk untuk Diretur:</label>
                        <select name="idproduk" id="idproduk" class="form-control" required>
                            <option value="">Pilih Produk dari Nota</option>
                        </select>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Jumlah Retur:</label>
                        <input type="number" name="quantity" id="quantity" class="form-control" min="1" value="1" required>
                        <small class="form-text text-muted">Maksimal: <span id="max_quantity">0</span> | Stok saat ini: <span id="current_stock">-</span></small>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label>Keterangan Retur:</label>
                        <textarea name="keterangan" class="form-control" rows="3" placeholder="Alasan retur..."></textarea>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card bg-light p-3">
                        <h6><i class="fas fa-info-circle"></i> Petunjuk Retur Barang</h6>
                        <ul class="mb-0">
                            <li>Masukkan nomor nota transaksi yang akan diretur</li>
                            <li>Pilih produk yang akan diretur dari daftar produk pada nota tersebut</li>
                            <li>Masukkan jumlah produk yang akan diretur</li>
                            <li>Stok produk akan otomatis bertambah kembali</li>
                            <li>Transaksi penjualan akan diperbarui sesuai jumlah retur</li>
                            <li>Pendapatan bersih akan dikurangi sesuai jumlah retur</li>
                        </ul>
                    </div>
                    
                    <div class="card mt-3">
                        <div class="card-header">
                            <h6>Detail Produk dalam Nota</h6>
                        </div>
                        <div class="card-body">
                            <div id="product_details_container">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Produk</th>
                                            <th>Qty Terjual</th>
                                            <th>Harga</th>
                                            <th>Subtotal</th>
                                        </tr>
                                    </thead>
                                    <tbody id="product_details">
                                        <tr>
                                            <td colspan="4" class="text-center">Masukkan nomor nota untuk melihat detail produk</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="card-footer text-right">
            <button type="submit" name="process_return" class="btn btn-warning px-3" id="process_return_btn" disabled>Proses Retur</button>
        </div>
    </form>
</div>

<!-- Recent Returns -->
<div class="card mt-4">
    <div class="card-header">
        <div class="card-tittle"><i class="fa fa-list me-2"></i> Riwayat Retur Terakhir</div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-sm" id="table">
                <thead>
                    <tr>
                        <th>No. Retur</th>
                        <th>No. Nota</th>
                        <th>Produk</th>
                        <th>Qty</th>
                        <th>Subtotal</th>
                        <th>Tanggal</th>
                        <th>Keterangan</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $retur_data = mysqli_query($conn, "SELECT r.*, p.nama_produk, p.kode_produk FROM retur_barang r 
                                                      JOIN produk p ON r.idproduk = p.idproduk 
                                                      ORDER BY r.idretur DESC LIMIT 10");
                    while($retur = mysqli_fetch_assoc($retur_data)) {
                        echo "<tr>";
                        echo "<td>RET" . str_pad($retur['idretur'], 6, "0", STR_PAD_LEFT) . "</td>";
                        echo "<td>" . ($retur['no_nota'] ?: '-') . "</td>";
                        echo "<td>" . $retur['nama_produk'] . "</td>";
                        echo "<td>" . $retur['quantity'] . "</td>";
                        echo "<td>Rp. " . ribuan($retur['subtotal']) . "</td>";
                        echo "<td>" . $retur['tanggal_retur'] . "</td>";
                        echo "<td>" . $retur['keterangan'] . "</td>";
                        echo "</tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Function to load products based on nota
function loadNotaProducts() {
    const nota = document.getElementById('no_nota').value;
    if(nota) {
        // Load products for this nota
        fetch('get_products_by_nota.php?nota=' + encodeURIComponent(nota))
        .then(response => response.json())
        .then(data => {
            const productSelect = document.getElementById('idproduk');
            const productDetails = document.getElementById('product_details');
            
            // Clear existing options
            productSelect.innerHTML = '<option value="">Pilih Produk dari Nota</option>';
            
            if(data.success && data.products.length > 0) {
                // Populate product select with products from this nota
                data.products.forEach(product => {
                    const option = document.createElement('option');
                    option.value = product.idproduk;
                    option.textContent = product.nama_produk + ' (Qty: ' + product.quantity + ', Harga: Rp. ' + product.harga_jual + ')';
                    option.setAttribute('data-qty', product.quantity);
                    option.setAttribute('data-harga', product.harga_jual);
                    option.setAttribute('data-stok', product.stock);
                    productSelect.appendChild(option);
                });
                
                // Populate product details table
                productDetails.innerHTML = '';
                data.products.forEach(product => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${product.nama_produk}</td>
                        <td>${product.quantity}</td>
                        <td>Rp. ${product.harga_jual}</td>
                        <td>Rp. ${product.subtotal}</td>
                    `;
                    productDetails.appendChild(row);
                });
                
                // Enable the process button
                document.getElementById('process_return_btn').disabled = false;
            } else {
                productDetails.innerHTML = '<tr><td colspan="4" class="text-center">Tidak ada produk ditemukan untuk nota ini</td></tr>';
                productSelect.innerHTML = '<option value="">Tidak ada produk dalam nota ini</option>';
                document.getElementById('process_return_btn').disabled = true;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error saat mengambil data produk dari nota');
        });
    } else {
        alert('Silakan masukkan nomor nota terlebih dahulu');
    }
}

// Update quantity max and stock when product is selected
document.getElementById('idproduk').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    if(selectedOption.value !== "") {
        const maxQty = parseInt(selectedOption.getAttribute('data-qty'));
        const stok = parseInt(selectedOption.getAttribute('data-stok'));
        
        document.getElementById('max_quantity').textContent = maxQty;
        document.getElementById('current_stock').textContent = stok;
        
        // Set max value for quantity input
        const quantityInput = document.getElementById('quantity');
        quantityInput.max = maxQty;
        quantityInput.value = 1; // Reset to 1
    } else {
        document.getElementById('max_quantity').textContent = '0';
        document.getElementById('current_stock').textContent = '-';
    }
});

// Limit quantity to max available
document.getElementById('quantity').addEventListener('input', function() {
    const maxQty = parseInt(document.getElementById('max_quantity').textContent);
    const quantity = parseInt(this.value);
    
    if (quantity > maxQty) {
        this.value = maxQty;
        alert('Jumlah retur tidak boleh melebihi jumlah produk dalam nota!');
    }
    
    if (quantity < 1) {
        this.value = 1;
    }
});
</script>

<?php include 'template/footer.php';?>