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

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

    // Mengambil kuantitas produk saat ini dari tabel online_products
    $query = "SELECT quantity FROM online_products 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_online (part_number, date, actual_quantity, difference, notes, created_at, updated_at)
                VALUES ('{$part_number}', '{$date}', '{$actual_quantity}', '{$difference}', '{$notes}', now(), now())";

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

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

        // Mengembalikan nilai true jika penyisipan dan pembaruan berhasil, false jika gagal
        return $insert_result && $update_result;
    } else {
        return false; // Jika part_number tidak ditemukan di tabel online_products
    }
}

// Fungsi untuk memproses file CSV yang diunggah
function process_csv_upload($file) {
    global $db;

    $handle = fopen($file, "r");
    if ($handle !== false) {
        $success_count = 0;
        $error_count = 0;

        // Skip header row jika ada
        fgetcsv($handle, 1000, ";");

        while (($data = fgetcsv($handle, 1000, ";")) !== false) {
            $part_number = trim($data[0]);
            $actual_quantity = (int) trim($data[1]);
            $date = trim($data[2]);
            $notes = isset($data[3]) ? trim($data[3]) : '';

            // Memanggil fungsi insert_stock_taking_online untuk setiap baris dalam CSV
            $insert_success = insert_stock_taking_online($part_number, $actual_quantity, $date, $notes);

            if ($insert_success) {
                $success_count++;
            } else {
                $error_count++;
            }
        }

        fclose($handle);

        if ($error_count === 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// 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'];

    if (empty($part_number) || empty($actual_quantity) || empty($date)) {
        $msg = '<div class="alert alert-danger">All fields are required.</div>';
    } else {
        $insert_stock = insert_stock_taking_online($part_number, $actual_quantity, $date, $notes);

        if ($insert_stock) {
            $msg = '<div class="alert alert-success">Stock taking entry added successfully.</div>';
        } else {
            $msg = '<div class="alert alert-danger">Failed to add stock taking entry. Part number may not exist in online_products.</div>';
        }
    }
}

// Proses upload CSV file
if (isset($_POST['submit_csv'])) {
    if ($_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $csv_file = $_FILES['csv_file']['tmp_name'];
        $upload_success = process_csv_upload($csv_file);

        if ($upload_success) {
            $msg = '<div class="alert alert-success">CSV file uploaded and processed successfully.</div>';
        } else {
            $msg = '<div class="alert alert-danger">Failed to process CSV file. Please check the format and content.</div>';
        }
    } else {
        $msg = '<div class="alert alert-danger">Error uploading CSV file: ' . $_FILES['csv_file']['error'] . '</div>';
    }
}
?>

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

<div class="row">
    <div class="col-md-6">
        <?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">Add Stock Taking Entry</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="stock_taking_product_online.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="Enter 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" required>
                    </div>
                    <div class="form-group">
                        <label for="date">Date:</label>
                        <input type="date" class="form-control" name="date" id="date" required>
                    </div>
                    <div class="form-group">
                        <label for="notes">Notes:</label>
                        <textarea class="form-control" name="notes" id="notes"></textarea>
                    </div>
                    <button type="submit" name="submit_single" class="btn btn-primary">Add Entry</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 from CSV</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="stock_taking_product_online.php" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="csv_file">Choose CSV File:</label>
                        <input type="file" name="csv_file" id="csv_file" accept=".csv" required>
                    </div>
                    <button type="submit" name="submit_csv" class="btn btn-primary">Upload CSV</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <a href="view_stock_taking_online.php" class="btn btn-success">View Stock Taking Results</a>
    </div>
</div>

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