<?php
// Tampilkan semua error untuk debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$page_title = 'Add Product';
require_once('includes/load.php');
page_require_level(5);

// Ambil semua kategori untuk dropdown
$all_categories = find_all('categories');

// Ambil akun COA yang relevan (Persediaan & HPP)
$coas = find_by_sql("SELECT kode, akun FROM coa WHERE type_akun = 'Persediaan' OR type_akun = 'HPP' ORDER BY kode ASC");
$default_coa_kode = '116.01'; // Default value based on your COA table for 'Persediaan'

// Include PhpSpreadsheet library
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

// Handle Excel import form submission
if (isset($_POST['import_excel'])) {
    if (empty($_FILES['excel_file']['name'])) {
        $session->msg('d', "Please select an Excel file to import.");
        redirect('add_product.php', false);
    } else {
        $file = $_FILES['excel_file']['tmp_name'];
        $file_ext = pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION);

        if ($file_ext != 'xlsx' && $file_ext != 'xls') {
            $session->msg('d', "Only Excel files (.xlsx or .xls) are allowed.");
            redirect('add_product.php', false);
        }

        try {
            $spreadsheet = IOFactory::load($file);
            $worksheet = $spreadsheet->getActiveSheet();
            $rows = $worksheet->toArray();

            // Remove header row from the Excel data
            array_shift($rows);

            $success_count = 0;
            $error_rows = []; // Array to store detailed error messages
            $db->begin_transaction(); // Start a transaction

            foreach ($rows as $index => $row) {
                // Skip completely empty rows
                if (empty(array_filter($row))) {
                    continue;
                }

                // Trim whitespace from each cell to avoid validation issues
                $row = array_map('trim', $row);

                // Check for required fields with detailed error messages
                $errors_in_row = [];
                // COA KODE SEKARANG ADA DI INDEKS 8 (SETELAH LOCATION)
                if (empty($row[0])) $errors_in_row[] = "Product Title (nama)";
                if (empty($row[1])) $errors_in_row[] = "Part Number";
                if (empty($row[2])) $errors_in_row[] = "Category ID";
                if (empty($row[3])) $errors_in_row[] = "Quantity";
                if (empty($row[4])) $errors_in_row[] = "Buying Price";
                if (empty($row[5])) $errors_in_row[] = "UoM";
                if (empty($row[6])) $errors_in_row[] = "Lead Time";
                if (empty($row[7])) $errors_in_row[] = "Location";
                if (empty($row[8])) $errors_in_row[] = "Barcode ID"; // Barcode ID pindah ke indeks 8
                // Check if COA Kode is provided, not necessarily empty
                $coa_kode_excel = isset($row[9]) ? remove_junk($db->escape($row[9])) : null;
                
                if (!empty($errors_in_row)) {
                    $error_rows[] = "Row " . ($index + 2) . ": missing required fields (" . implode(", ", $errors_in_row) . ")";
                    continue;
                }
                
                // Prepare and sanitize data from Excel row
                $p_name = $db->escape($row[0]);
                $p_part_number = remove_junk($db->escape($row[1]));
                $p_cat = (int)remove_junk($db->escape($row[2]));
                $p_qty = (float)remove_junk($db->escape($row[3]));
                $p_buy = (float)remove_junk($db->escape($row[4]));
                $p_uom = remove_junk($db->escape($row[5]));
                $p_lead_time = (int)remove_junk($db->escape($row[6]));
                $p_location = remove_junk($db->escape($row[7]));
                $p_barcode_id = remove_junk($db->escape($row[8]));
                $p_coa = $coa_kode_excel;

                $date = make_date();

                // SQL query to insert data into products table
                // MENAMBAHKAN coa_kode PADA QUERY
                $query_product = "INSERT INTO products (
                    name, quantity, UoM, buy_price, categorie_id, date, part_number, lead_time, loc_id, barcode_id, coa_kode
                ) VALUES (
                    '{$p_name}', {$p_qty}, '{$p_uom}', {$p_buy}, {$p_cat}, '{$date}', '{$p_part_number}', {$p_lead_time}, '{$p_location}', '{$p_barcode_id}', '{$p_coa}'
                )";

                if ($db->query($query_product)) {
                    $success_count++;
                } else {
                    $error_rows[] = "Row " . ($index + 2) . ": database error - " . $db->error;
                }
            }

            if (empty($error_rows)) {
                $db->commit();
                $session->msg('s', "All products imported successfully. Total: {$success_count}.");
            } else {
                $db->rollback();
                $error_message = "Import completed with errors. Success: {$success_count}. Failed rows: " . count($error_rows) . ".<br>Details:<br><ul><li>" . implode("</li><li>", $error_rows) . "</li></ul>";
                $session->msg('d', $error_message);
            }
            redirect('add_product.php', false);

        } catch (Exception $e) {
            $db->rollback();
            $session->msg('d', "Error during import: " . $e->getMessage());
            redirect('add_product.php', false);
        }
    }
}

// Handle manual product form submission
if (isset($_POST['add_product'])) {
    // Barcode ID and COA KODE are now required fields for manual input
    $req_fields = array('product-title', 'part-number', 'product-categorie', 'quantity', 'buy_price', 'UoM', 'lead_time', 'loc_id', 'barcode-id', 'coa-kode');
    validate_fields($req_fields);

    if (empty($errors)) {
        // Sanitize and prepare form data
        $p_name = remove_junk($db->escape($_POST['product-title']));
        $p_part_number = remove_junk($db->escape($_POST['part-number']));
        $p_cat = (int)remove_junk($db->escape($_POST['product-categorie']));
        $p_qty = (float)remove_junk($db->escape($_POST['quantity']));
        $p_buy = (float)remove_junk($db->escape($_POST['buy_price']));
        $p_uom = remove_junk($db->escape($_POST['UoM']));
        $p_lead_time = (int)remove_junk($db->escape($_POST['lead_time']));
        $p_location = remove_junk($db->escape($_POST['loc_id']));
        $p_barcode_id = remove_junk($db->escape($_POST['barcode-id']));
        // MENAMBAHKAN COA KODE
        $p_coa = remove_junk($db->escape($_POST['coa-kode']));

        // Default value
        $date = make_date();

        // SQL query to insert data into products table
        // MENAMBAHKAN coa_kode PADA QUERY
        $query_product = "INSERT INTO products (
            name, quantity, UoM, buy_price, categorie_id, date, part_number, lead_time, loc_id, barcode_id, coa_kode
        ) VALUES (
            '{$p_name}', {$p_qty}, '{$p_uom}', {$p_buy}, {$p_cat}, '{$date}', '{$p_part_number}', {$p_lead_time}, '{$p_location}', '{$p_barcode_id}', '{$p_coa}'
        )";

        if ($db->query($query_product)) {
            $session->msg('s', "Product added successfully.");
            redirect('add_product.php', false);
        } else {
            $session->msg('d', 'Failed to add product: ' . $db->error);
            redirect('add_product.php', false);
        }
    } else {
        $session->msg("d", $errors);
        redirect('add_product.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-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Tambah Produk Baru (Manual)</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="add_product.php" class="clearfix">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-th-large"></i></span>
                            <input type="text" class="form-control" name="product-title" placeholder="Nama Produk" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-barcode"></i></span>
                            <input type="text" class="form-control" name="part-number" placeholder="Part Number" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <select class="form-control" name="product-categorie" required>
                            <option value="">Pilih Kategori Produk</option>
                            <?php foreach ($all_categories as $cat): ?>
                            <option value="<?php echo (int)$cat['id'] ?>"><?php echo $cat['name'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-shopping-cart"></i></span>
                                    <input type="number" class="form-control" name="quantity" placeholder="Jumlah Produk" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="input-group">
                                    <span class="input-group-addon"><i class="glyphicon glyphicon-usd"></i></span>
                                    <input type="number" class="form-control" name="buy_price" placeholder="Harga Satuan" required step="0.01">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-scale"></i></span>
                            <input type="text" class="form-control" name="UoM" placeholder="Satuan Ukuran (mis. pcs, kg)" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                            <input type="number" class="form-control" name="lead_time" placeholder="Lead Time (hari)" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-map-marker"></i></span>
                            <input type="text" class="form-control" name="loc_id" placeholder="Lokasi Gudang" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="glyphicon glyphicon-qrcode"></i></span>
                            <input type="text" class="form-control" name="barcode-id" placeholder="Barcode ID" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <select class="form-control" name="coa-kode" required>
                            <option value="">Pilih Kode COA</option>
                            <?php foreach ($coas as $coa): ?>
                                <option value="<?php echo htmlspecialchars($coa['kode']); ?>" <?php if ($coa['kode'] == $default_coa_kode) echo 'selected'; ?>>
                                    <?php echo htmlspecialchars($coa['kode']); ?> - <?php echo htmlspecialchars($coa['akun']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <button type="submit" name="add_product" class="btn btn-danger">Tambah Produk</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-import"></span>
                    <span>Impor dari Excel</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="add_product.php" enctype="multipart/form-data" class="clearfix">
                    <div class="form-group">
                        <label>File Excel</label>
                        <input type="file" name="excel_file" class="form-control" required accept=".xlsx,.xls">
                        <small class="help-block">Hanya file .xlsx atau .xls yang diizinkan</small>
                    </div>
                    <div class="form-group">
                        <a href="templates/product_import_template.xlsx" class="btn btn-default" download>
                            <i class="glyphicon glyphicon-download-alt"></i> Unduh Format Excel
                        </a>
                    </div>
                    <div class="form-group">
                        <label>Format Excel:</label>
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Nama Produk</th>
                                    <th>Part Number</th>
                                    <th>Category ID</th>
                                    <th>Quantity</th>
                                    <th>Harga Beli</th>
                                    <th>UoM</th>
                                    <th>Lead Time</th>
                                    <th>Lokasi</th>
                                    <th>Barcode ID</th>
                                    <th>Kode COA</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    <button type="submit" name="import_excel" class="btn btn-primary">Impor Produk</button>
                </form>
            </div>
        </div>
    </div>
</div>

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