<?php
$page_title = 'Add Outgoing';
require_once('includes/sql.php');
page_require_level(3);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    $transactionDate = $_POST['transactionDate'];
    $file = $_FILES['csv_file']['tmp_name'];

    // Validate file type and size (example accepts only CSV files)
    if ($_FILES['csv_file']['type'] !== 'text/csv') {
        $session->msg('d', 'Invalid file type. Please upload a CSV file.');
        redirect('add_sale.php');
    }

    // Read CSV file
    $handle = fopen($file, "r");
    if ($handle === false) {
        $session->msg('d', 'Error opening file.');
        redirect('add_sale.php');
    }

    // Prepare to insert data into database
    $sql = "INSERT INTO sales (product_id, part_number, qty, date, categorie_id, remark, loc) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $db->prepare($sql);

    // Function to update product quantity
    function update_product_qty($quantity, $productId) {
        global $db;
        $sql = "UPDATE products SET qty = qty - ? WHERE id = ?";
        $stmt = $db->prepare($sql);
        $stmt->bind_param("ii", $quantity, $productId);
        return $stmt->execute();
    }

    $successCount = 0;
    $failureCount = 0;

    // Process each row in CSV
    while (($data = fgetcsv($handle, 1000, ";")) !== false) {
        // Assuming CSV columns: part_number, quantity, remark, loc
        $partNumber = $data[0];
        $quantity = (int)$data[1];
        $remark = $db->escape($data[2]);
        $loc = $db->escape($data[3]);

        // Find product by part number
        $product = find_product_by_part_number($partNumber);

        if ($product) {
            // Insert into sales table
            $productId = $product['id'];
            $categorieId = $product['categorie_id'];
            $stmt->bind_param("issiiss", $productId, $partNumber, $quantity, $transactionDate, $categorieId, $remark, $loc);
            
            if ($stmt->execute()) {
                // Update product quantity in stock
                if (update_product_qty($quantity, $productId)) {
                    $successCount++;
                } else {
                    $failureCount++;
                }
            } else {
                $failureCount++;
            }
        } else {
            $failureCount++;
        }
    }

    fclose($handle);

    // Provide feedback to user
    if ($successCount > 0) {
        $session->msg('s', "{$successCount} sales added successfully!");
    }
    if ($failureCount > 0) {
        $session->msg('d', "{$failureCount} sales failed to add.");
    }

    redirect('add_sale.php');
}

include_once('layouts/header.php');
echo display_msg($msg);
?>

<div class="row">
    <div class="col-md-12">
        <h2>Add Outgoing Goods</h2>
        <form id="goods-form" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="transaction-date">Transaction Date:</label>
                <input type="date" id="transaction-date" name="transactionDate" required>
            </div>
            <div class="form-group">
                <label for="csv-file">Import CSV:</label>
                <input type="file" class="form-control-file" id="csv-file" name="csv_file" accept=".csv" required>
            </div>
            <button type="submit" class="btn btn-primary">Import and Add Outgoing Goods</button>
        </form>
    </div>
</div>

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