<?php
$page_title = 'Tambah Penjualan';
require_once('includes/load.php');
page_require_level(5);

// Fungsi untuk mengambil semua produk
function find_all_products_local() {
    global $db;
    $sql = "SELECT id, name, part_number, buy_price, coa_kode FROM products ORDER BY name ASC";
    return find_by_sql($sql);
}

// Fungsi untuk mengambil semua pelanggan
function find_all_customers_local() {
    global $db;
    $sql = "SELECT id, name, coa_kode FROM customers ORDER BY name ASC";
    return find_by_sql($sql);
}

// Fungsi untuk mengambil COA berdasarkan akun
function find_coa_by_akun($akun_name) {
    global $db;
    $sql = "SELECT kode FROM coa WHERE akun = '{$db->escape($akun_name)}' LIMIT 1";
    $result = find_by_sql($sql);
    return !empty($result) ? $result[0]['kode'] : null;
}

// Fungsi baru untuk menemukan produk berdasarkan part_number
function find_product_by_part_number($part_number) {
    global $db;
    $sql = "SELECT id, name, buy_price FROM products WHERE part_number = '{$db->escape($part_number)}' LIMIT 1";
    $result = find_by_sql($sql);
    return !empty($result) ? $result[0] : null;
}

// Fungsi baru untuk menemukan pelanggan berdasarkan nama
function find_customer_by_name($customer_name) {
    global $db;
    $sql = "SELECT id, coa_kode FROM customers WHERE name = '{$db->escape($customer_name)}' LIMIT 1";
    $result = find_by_sql($sql);
    return !empty($result) ? $result[0] : null;
}

// Ambil data dari database
$all_products = find_all_products_local();
$all_customers = find_all_customers_local();

// Ambil kode COA statis yang dibutuhkan
$coa_penjualan = find_coa_by_akun('Pendapatan Usaha');
$coa_hpp = find_coa_by_akun('Harga Pokok Penjualan');
$coa_kas = find_coa_by_akun('Kas Besar');
$coa_persediaan = find_coa_by_akun('Persediaan Peralatan dan Bahan');


if (isset($_POST['add_sale'])) {
    $req_fields = array('product_part_number', 'customer_name', 'quantity', 'price', 'payment_method');
    validate_fields($req_fields);

    if (empty($errors)) {
        $p_part_number  = remove_junk($db->escape($_POST['product_part_number']));
        $c_name         = remove_junk($db->escape($_POST['customer_name']));
        $qty            = remove_junk($db->escape($_POST['quantity']));
        $price          = remove_junk($db->escape($_POST['price']));
        $payment_method = remove_junk($db->escape($_POST['payment_method']));

        // Cari ID produk dan harga beli (buy_price) berdasarkan part_number
        $product = find_product_by_part_number($p_part_number);
        if (!$product) {
            $session->msg('d', 'Produk tidak ditemukan.');
            redirect('add_sale.php', false);
        }
        $p_id = $product['id'];
        $buy_price = $product['buy_price'];
        
        // Cari ID pelanggan dan coa_kode berdasarkan nama
        $customer = find_customer_by_name($c_name);
        if (!$customer) {
            $session->msg('d', 'Pelanggan tidak ditemukan.');
            redirect('add_sale.php', false);
        }
        $c_id = $customer['id'];
        
        $total_price  = $qty * $price;
        $hpp_price    = $qty * $buy_price; 
        $date         = make_date();

        // 1. Simpan data penjualan ke tabel 'sales'
        $sql  = "INSERT INTO sales (product_id, customer_id, qty, price, buy_price, total_price, date, payment_method) VALUES (";
        $sql .= " '{$p_id}', '{$c_id}', '{$qty}', '{$price}', '{$buy_price}', '{$total_price}', '{$date}', '{$payment_method}'";
        $sql .= ")";

        if ($db->query($sql)) {
            $session->msg('s', "Penjualan berhasil ditambahkan.");
            
            // 2. Perbarui stok produk
            update_product_qty($qty, $p_id);

            // 3. Catat transaksi ke jurnal umum
            $product_name = remove_junk($product['name']);
            
            // Tentukan COA debet berdasarkan metode pembayaran
            if ($payment_method === 'cash') {
                $coa_debet = $coa_kas;
                $deskripsi_tambahan = " (Tunai)";
            } else { // 'credit'
                // Gunakan coa_kode dari tabel pelanggan untuk piutang
                $coa_debet = $customer['coa_kode']; 
                $deskripsi_tambahan = " (Tempo)";
            }

            // Periksa apakah COA yang dibutuhkan ada
            if ($coa_penjualan && $coa_debet && $coa_hpp && $coa_persediaan) {
                // Jurnal #1: Pendapatan Penjualan
                $deskripsi_penjualan = "Penjualan produk {$product_name} ({$p_part_number}) kepada {$c_name}{$deskripsi_tambahan}.";

                // Debit: Kas atau Piutang
                $sql_jurnal_debet = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (";
                $sql_jurnal_debet .= " '{$date}', '{$deskripsi_penjualan}', '{$coa_debet}', '{$total_price}', '0'";
                $sql_jurnal_debet .= ")";
                $db->query($sql_jurnal_debet);

                // Kredit: Penjualan
                $sql_jurnal_penjualan = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (";
                $sql_jurnal_penjualan .= " '{$date}', '{$deskripsi_penjualan}', '{$coa_penjualan}', '0', '{$total_price}'";
                $sql_jurnal_penjualan .= ")";
                $db->query($sql_jurnal_penjualan);

                // Jurnal #2: Harga Pokok Penjualan
                $deskripsi_hpp_inv = "HPP produk {$product_name} ({$p_part_number}) untuk penjualan kepada {$c_name}.";
                
                // Debit: Harga Pokok Penjualan
                $sql_jurnal_hpp = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (";
                $sql_jurnal_hpp .= " '{$date}', '{$deskripsi_hpp_inv}', '{$coa_hpp}', '{$hpp_price}', '0'";
                $sql_jurnal_hpp .= ")";
                $db->query($sql_jurnal_hpp);

                // Kredit: Persediaan
                $sql_jurnal_persediaan = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (";
                $sql_jurnal_persediaan .= " '{$date}', '{$deskripsi_hpp_inv}', '{$coa_persediaan}', '0', '{$hpp_price}'";
                $sql_jurnal_persediaan .= ")";
                $db->query($sql_jurnal_persediaan);
            } else {
                $session->msg('w', 'Gagal mencatat jurnal: Kode COA tidak ditemukan. Periksa tabel `coa`.');
            }

            redirect('sales.php', false);

        } else {
            $session->msg('d', 'Gagal menambahkan penjualan: ' . $db->error);
            redirect('add_sale.php', false);
        }
    } else {
        $session->msg("d", $errors);
        redirect('add_sale.php', false);
    }
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>
<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Form Tambah Penjualan</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="add_sale.php" class="clearfix">
                    <div class="form-group">
                        <label for="product_part_number">Produk</label>
                        <select class="form-control" name="product_part_number" id="product_part_number" required>
                            <option value="">Pilih Produk</option>
                            <?php foreach ($all_products as $product) : ?>
                                <option value="<?php echo htmlspecialchars($product['part_number']); ?>" data-price="<?php echo htmlspecialchars($product['buy_price']); ?>">
                                    <?php echo remove_junk($product['name']); ?> (<?php echo remove_junk($product['part_number']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="customer_name">Pelanggan</label>
                        <select class="form-control" name="customer_name" id="customer_name" required>
                            <option value="">Pilih Pelanggan</option>
                            <?php foreach ($all_customers as $customer) : ?>
                                <option value="<?php echo htmlspecialchars($customer['name']); ?>">
                                    <?php echo remove_junk($customer['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="payment_method">Metode Pembayaran</label>
                        <select class="form-control" name="payment_method" id="payment_method" required>
                            <option value="cash">Tunai</option>
                            <option value="credit">Hutang (Tempo)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="quantity">Jumlah</label>
                        <input type="number" class="form-control" name="quantity" id="quantity" placeholder="Jumlah barang" required min="1">
                    </div>

                    <div class="form-group">
                        <label for="price">Harga Jual per Unit</label>
                        <div class="input-group">
                            <span class="input-group-addon">Rp</span>
                            <input type="number" class="form-control" name="price" id="price" placeholder="Harga per unit" required step="0.01">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="total_price">Total Harga</label>
                        <div class="input-group">
                            <span class="input-group-addon">Rp</span>
                            <input type="text" class="form-control" id="total_price" placeholder="Total harga" readonly>
                        </div>
                    </div>
                    
                    <input type="hidden" name="buy_price" id="buy_price">

                    <button type="submit" name="add_sale" class="btn btn-danger">Tambah Penjualan</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const productPartNumberSelect = document.getElementById('product_part_number');
    const quantityInput = document.getElementById('quantity');
    const priceInput = document.getElementById('price');
    const totalInput = document.getElementById('total_price');
    const buyPriceInput = document.getElementById('buy_price');

    // Update total price and hidden buy price whenever inputs change
    function updateCalculations() {
        const selectedOption = productPartNumberSelect.options[productPartNumberSelect.selectedIndex];
        const buyPrice = selectedOption.dataset.price;
        const qty = parseFloat(quantityInput.value) || 0;
        const price = parseFloat(priceInput.value) || 0;

        const total = qty * price;
        totalInput.value = total.toFixed(2);
        buyPriceInput.value = buyPrice;
    }

    productPartNumberSelect.addEventListener('change', updateCalculations);
    quantityInput.addEventListener('input', updateCalculations);
    priceInput.addEventListener('input', updateCalculations);
});
</script>

<?php include_once('layouts/footer.php'); ?>