<?php
$page_title = 'Stock Taking';
require_once('includes/load.php');
page_require_level(3); // Memerlukan tingkat akses minimal 3 untuk mengakses halaman ini

// Memuat autoloader untuk PHPSpreadsheet
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

// Fungsi untuk menyisipkan data stock taking ke dalam database
function insert_stock_taking($part_number, $actual_quantity, $date, $notes, $warehouse_table) {
    global $db;

    // Mengambil kuantitas produk saat ini dari tabel gudang yang dipilih
    $query = "SELECT quantity FROM {$warehouse_table} WHERE part_number = '{$part_number}'";
    $result = $db->query($query);

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $current_quantity = (int) $row['quantity'];

        // Menghitung difference
        $difference = $actual_quantity - $current_quantity;

        // Membuat pernyataan SQL untuk menyisipkan data
        $sql_insert = "INSERT INTO stock_taking (part_number, date, actual_quantity, difference, notes, warehouse, created_at, updated_at)
                VALUES ('{$part_number}', '{$date}', '{$actual_quantity}', '{$difference}', '{$notes}', '{$warehouse_table}', now(), now())";

        // Menjalankan pernyataan SQL penyisipan
        $insert_result = $db->query($sql_insert);

        // Update quantity di tabel gudang yang dipilih
        $sql_update = "UPDATE {$warehouse_table} SET quantity = '{$actual_quantity}' WHERE part_number = '{$part_number}'";
        $update_result = $db->query($sql_update);

        return $insert_result && $update_result;
    } else {
        return false; // Jika part_number tidak ditemukan di tabel gudang
    }
}

// Fungsi untuk memproses file Excel yang diunggah
function process_excel_upload($file, $warehouse_table) {
    global $db;

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

        $success_count = 0;
        $error_count = 0;
        $error_messages = [];

        for ($i = 1; $i < count($rows); $i++) {
            $row = $rows[$i];
            
            if (empty(array_filter($row))) {
                continue;
            }

            $part_number = isset($row[0]) ? trim($row[0]) : '';
            $actual_quantity = isset($row[1]) ? (int) trim($row[1]) : 0;
            $date = isset($row[2]) ? trim($row[2]) : '';
            $notes = isset($row[3]) ? trim($row[3]) : '';

            if (empty($part_number) || empty($date)) {
                $error_count++;
                $error_messages[] = "Baris " . ($i + 1) . ": Part number dan tanggal harus diisi";
                continue;
            }

            if ($actual_quantity < 0) {
                $error_count++;
                $error_messages[] = "Baris " . ($i + 1) . ": Quantity tidak boleh negatif";
                continue;
            }

            if (is_numeric($date)) {
                $date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($date)->format('Y-m-d');
            }

            $insert_success = insert_stock_taking($part_number, $actual_quantity, $date, $notes, $warehouse_table);

            if ($insert_success) {
                $success_count++;
            } else {
                $error_count++;
                $error_messages[] = "Baris " . ($i + 1) . ": Gagal memproses part number " . $part_number . " di gudang " . $warehouse_table;
            }
        }

        return [
            'success' => $success_count,
            'error' => $error_count,
            'messages' => $error_messages
        ];
    } catch (Exception $e) {
        return [
            'success' => 0,
            'error' => 0,
            'messages' => ['Error processing file: ' . $e->getMessage()]
        ];
    }
}

// Inisialisasi pesan untuk tampilan
$msg = '';

// Proses form submit untuk menambahkan entri stock taking baru
if (isset($_POST['submit_single'])) {
    $part_number = $_POST['part_number'];
    $actual_quantity = (int) $_POST['actual_quantity'];
    $date = $_POST['date'];
    $notes = $_POST['notes'];
    $warehouse_table = $_POST['warehouse'];

    if ($actual_quantity < 0) {
        $msg = '<div class="alert alert-danger">Quantity tidak boleh negatif.</div>';
    } elseif (empty($part_number) || empty($date)) {
        $msg = '<div class="alert alert-danger">Part number dan tanggal wajib diisi.</div>';
    } else {
        $insert_stock = insert_stock_taking($part_number, $actual_quantity, $date, $notes, $warehouse_table);

        if ($insert_stock) {
            $msg = '<div class="alert alert-success">Data stock taking berhasil ditambahkan di gudang ' . $warehouse_table . '.</div>';
        } else {
            $msg = '<div class="alert alert-danger">Gagal menambahkan data. Part number tidak ditemukan di gudang ' . $warehouse_table . '.</div>';
        }
    }
}

// Proses upload Excel file
if (isset($_POST['submit_excel'])) {
    if ($_FILES['excel_file']['error'] === UPLOAD_ERR_OK) {
        $excel_file = $_FILES['excel_file']['tmp_name'];
        $warehouse_table = $_POST['warehouse'];
        
        $upload_result = process_excel_upload($excel_file, $warehouse_table);

        if ($upload_result['error'] === 0) {
            $msg = '<div class="alert alert-success">File Excel berhasil diproses. ' . $upload_result['success'] . ' data ditambahkan di gudang ' . $warehouse_table . '.</div>';
        } else {
            $error_msg = '<div class="alert alert-danger">Proses dengan error. Berhasil: ' . $upload_result['success'] . ', Gagal: ' . $upload_result['error'] . '.<br>';
            $error_msg .= implode('<br>', $upload_result['messages']);
            $error_msg .= '</div>';
            $msg = $error_msg;
        }
    } else {
        $msg = '<div class="alert alert-danger">Error upload file. Error code: ' . $_FILES['excel_file']['error'] . '</div>';
    }
}
?>

<?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-6">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Tambah Stock Taking Manual</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="stock_taking.php">
                    <div class="form-group">
                        <label for="part_number">Part Number:</label>
                        <input type="text" class="form-control" name="part_number" id="part_number" placeholder="Masukkan part number" required>
                    </div>
                    <div class="form-group">
                        <label for="actual_quantity">Actual Quantity:</label>
                        <input type="number" class="form-control" name="actual_quantity" id="actual_quantity" value="0" min="0">
                    </div>
                    <div class="form-group">
                        <label for="date">Tanggal:</label>
                        <input type="date" class="form-control" name="date" id="date" required>
                    </div>
                    <div class="form-group">
                        <label for="warehouse">Pilih Gudang:</label>
                        <select class="form-control" name="warehouse" id="warehouse" required>
                            <option value="products">Surabaya</option>
                            <option value="wh_jakarta">Jakarta</option>
                            <option value="wh_makassar">Makassar</option>
                            <option value="wh_semarang">Semarang</option>
                            <option value="wh_bali">Bali</option>
                            <option value="wh_bandung">Bandung</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="notes">Catatan:</label>
                        <textarea class="form-control" name="notes" id="notes"></textarea>
                    </div>
                    <button type="submit" name="submit_single" class="btn btn-primary">Simpan</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Import Stock Taking dari Excel</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="stock_taking.php" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="excel_file">Pilih File Excel (XLSX):</label>
                        <input type="file" name="excel_file" id="excel_file" accept=".xlsx, .xls" required>
                        <p class="help-block">Format file harus Excel (.xlsx atau .xls)</p>
                    </div>
                    <div class="form-group">
                        <label for="warehouse">Pilih Gudang:</label>
                        <select class="form-control" name="warehouse" id="warehouse" required>
                            <option value="products">Surabaya</option>
                            <option value="wh_jakarta">Jakarta</option>
                            <option value="wh_makassar">Makassar</option>
                            <option value="wh_semarang">Semarang</option>
                            <option value="wh_bali">Bali</option>
                            <option value="wh_bandung">Bandung</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <a href="format_stock_taking.xlsx" class="btn btn-info">Download Template</a>
                        <button type="submit" name="submit_excel" class="btn btn-primary">Upload Excel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Panduan Format Excel</h3>
            </div>
            <div class="panel-body">
                <p>Format file Excel harus mengikuti struktur berikut:</p>
                <ol>
                    <li>Baris pertama adalah header (akan diabaikan)</li>
                    <li>Kolom A: Part Number (wajib diisi)</li>
                    <li>Kolom B: Actual Quantity (wajib diisi, angka)</li>
                    <li>Kolom C: Tanggal (wajib diisi, format tanggal)</li>
                    <li>Kolom D: Catatan (opsional)</li>
                </ol>
                <p>Contoh format:</p>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Part Number</th>
                            <th>Actual Quantity</th>
                            <th>Tanggal</th>
                            <th>Catatan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>PN001</td>
                            <td>10</td>
                            <td>2023-05-15</td>
                            <td>Stock opname bulanan</td>
                        </tr>
                        <tr>
                            <td>PN002</td>
                            <td>5</td>
                            <td>2023-05-15</td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <a href="hasil_stock_taking.php" class="btn btn-success">Lihat Hasil Stock Taking</a>
    </div>
</div>

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