<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

ob_start(); // Start output buffering

require_once('includes/load.php');
page_require_level(3);

require 'vendor/autoload.php'; // Memastikan autoload untuk PHPExcel tersedia

use PhpOffice\PhpSpreadsheet\IOFactory;

// Handle AJAX request for product details
if (isset($_POST['part_number']) && !empty($_POST['part_number'])) {
    $part_number = $db->escape($_POST['part_number']);
    $sql = "SELECT name, uom FROM products WHERE part_number = '{$part_number}'";
    $result = $db->query($sql);

    if ($result && $db->num_rows($result) > 0) {
        $product = $db->fetch_assoc($result);
        echo json_encode(['name' => $product['name'], 'uom' => $product['uom']]);
    } else {
        echo json_encode(['name' => '', 'uom' => '']);
    }
    exit;
}

// Function to generate a new request number
function generate_request_number() {
    global $db;
    $sql = "SELECT MAX(request_number) as max_request_number FROM purchase_requests";
    $result = $db->query($sql);
    if ($result) {
        $row = $db->fetch_assoc($result);
        $max_number = $row['max_request_number'] ?? 'REQ00000';
        $number = intval(substr($max_number, 3)) + 1;
        return 'REQ' . str_pad($number, 5, '0', STR_PAD_LEFT);
    } else {
        echo "Query failed: " . $db->error;
        return null;
    }
}

// Function to create a purchase request
function create_purchase_request($request_number, $request_date, $items) {
    global $db;

    $request_number = $db->escape($request_number);
    $request_date = $db->escape($request_date);

    $sql = "INSERT INTO purchase_requests (request_number, request_date)
            VALUES ('{$request_number}', '{$request_date}')";

    if (!$db->query($sql)) {
        return false;
    }

    foreach ($items as $item) {
        $part_number = $db->escape($item['part_number']);
        $product_name = $db->escape($item['product_name']);
        $quantity_needed = intval($item['quantity_needed']);
        $due_date = $db->escape($item['due_date']);
        $uom = $db->escape($item['uom']);
        $remark = $db->escape($item['remark']); // Added remark

        $sql = "INSERT INTO purchase_request_items (request_number, part_number, product_name, quantity_needed, due_date, uom, remark)
                VALUES ('{$request_number}', '{$part_number}', '{$product_name}', {$quantity_needed}, '{$due_date}', '{$uom}', '{$remark}')";

        if (!$db->query($sql)) {
            return false;
        }
    }

    return true;
}

// Function to import data from Excel
function import_excel($file_path) {
    $spreadsheet = IOFactory::load($file_path);
    $sheet = $spreadsheet->getActiveSheet();
    $rows = [];

    foreach ($sheet->getRowIterator() as $row) {
        $cells = $row->getCellIterator();
        $cells->setIterateOnlyExistingCells(false);

        $row_data = [];
        foreach ($cells as $cell) {
            $value = $cell->getValue();
            
            // Jika cell merupakan tanggal dalam format numerik, ubah menjadi format tanggal
            if (\PhpOffice\PhpSpreadsheet\Shared\Date::isDateTime($cell) && is_numeric($value)) {
                $value = date('Y-m-d', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($value));
            }

            $row_data[] = $value;
        }
        if (!empty(array_filter($row_data))) {
            $rows[] = [
                'part_number' => $row_data[0],
                'product_name' => $row_data[1],
                'quantity_needed' => intval($row_data[2]),
                'due_date' => date('Y-m-d', strtotime($row_data[3])),
                'uom' => $row_data[4],
            ];
        }
    }

    return $rows;
}

// Process form submission
if (isset($_POST['create_request'])) {
    $request_number = generate_request_number();
    if ($request_number) {
        $request_date = isset($_POST['request_date']) ? $db->escape($_POST['request_date']) : date('Y-m-d');
        $items = [];

        if (!empty($_FILES['excel_file']['tmp_name'])) {
            $file_path = $_FILES['excel_file']['tmp_name'];
            $items = import_excel($file_path);
        } else {
            foreach ($_POST['items'] as $item) {
                $items[] = [
                    'part_number' => $item['part_number'],
                    'product_name' => $item['product_name'],
                    'quantity_needed' => intval($item['quantity_needed']),
                    'due_date' => $item['due_date'],
                    'uom' => $item['uom'],
                    'remark' => $item['remark'] // Added remark
                ];
            }
        }

        if (create_purchase_request($request_number, $request_date, $items)) {
            $session->msg('s', "Purchase request created successfully with number {$request_number}.");
        } else {
            $session->msg('d', "Failed to create purchase request.");
        }
    } else {
        $session->msg('d', "Failed to generate request number.");
    }
    header('Location: purchase_requests.php');
    exit();
}

// Display form with imported data if file is uploaded
$imported_items = [];
if (!empty($_FILES['excel_file']['tmp_name'])) {
    $file_path = $_FILES['excel_file']['tmp_name'];
    $imported_items = import_excel($file_path);
}

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="card">
            <div class="card-header bg-primary text-white">
                <h4 class="card-title">Create Purchase Request</h4>
            </div>
            <div class="card-body">
                <form action="purchase_requests.php" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="request_date">Request Date:</label>
                        <input type="date" name="request_date" id="request_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="excel_file">Import from Excel:</label>
                        <input type="file" name="excel_file" id="excel_file" class="form-control-file" onchange="this.form.submit()">
                    </div>
                    <table class="table table-bordered">
                        <thead class="thead-dark">
                            <tr>
                                <th>Part Number</th>
                                <th>Product Name</th>
                                <th>Quantity Needed</th>
                                <th>Due Date</th>
                                <th>UOM</th>
                                <th>Remark</th> <!-- Added remark column -->
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="items-container">
                            <?php foreach ($imported_items as $index => $item): ?>
                            <tr class="item">
                                <td>
                                    <input type="text" name="items[<?php echo $index; ?>][part_number]" class="form-control part-number" value="<?php echo htmlspecialchars($item['part_number']); ?>" required>
                                </td>
                                <td>
                                    <input type="text" name="items[<?php echo $index; ?>][product_name]" class="form-control product-name" value="<?php echo htmlspecialchars($item['product_name']); ?>" required readonly>
                                </td>
                                <td>
                                    <input type="number" name="items[<?php echo $index; ?>][quantity_needed]" class="form-control" value="<?php echo htmlspecialchars($item['quantity_needed']); ?>" required>
                                </td>
                                <td>
                                    <input type="date" name="items[<?php echo $index; ?>][due_date]" class="form-control" value="<?php echo htmlspecialchars($item['due_date']); ?>" required>
                                </td>
                                <td>
                                    <input type="text" name="items[<?php echo $index; ?>][uom]" class="form-control uom" value="<?php echo htmlspecialchars($item['uom']); ?>" required readonly>
                                </td>
                                <td>
                                    <input type="text" name="items[<?php echo $index; ?>][remark]" class="form-control" placeholder="Enter remark">
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger remove-item">&times;</button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <div class="text-right">
                        <button type="button" id="add-item" class="btn btn-success">Add Item</button>
                    </div>
                    <br>
                    <button type="submit" name="create_request" class="btn btn-primary">Create Request</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Function to handle adding new rows
    document.getElementById('add-item').addEventListener('click', function() {
        const itemsContainer = document.getElementById('items-container');
        const index = itemsContainer.children.length;
        const row = document.createElement('tr');
        row.classList.add('item');
        row.innerHTML = `
            <td><input type="text" name="items[${index}][part_number]" class="form-control part-number" required></td>
            <td><input type="text" name="items[${index}][product_name]" class="form-control product-name" required readonly></td>
            <td><input type="number" name="items[${index}][quantity_needed]" class="form-control" required></td>
            <td><input type="date" name="items[${index}][due_date]" class="form-control" required></td>
            <td><input type="text" name="items[${index}][uom]" class="form-control uom" required readonly></td>
            <td><input type="text" name="items[${index}][remark]" class="form-control" placeholder="Enter remark"></td>
            <td><button type="button" class="btn btn-danger remove-item">&times;</button></td>
        `;
        itemsContainer.appendChild(row);

        // Attach event listeners to new row
        row.querySelector('.part-number').addEventListener('change', handlePartNumberChange);
        row.querySelector('.remove-item').addEventListener('click', function() {
            itemsContainer.removeChild(row);
        });
    });

    // Function to handle removing rows
    document.querySelectorAll('.remove-item').forEach(function(button) {
        button.addEventListener('click', function() {
            const row = button.closest('tr');
            row.parentNode.removeChild(row);
        });
    });

    // Handle part number change to fetch product details
    function handlePartNumberChange(event) {
        const partNumber = event.target.value;
        const row = event.target.closest('tr');
        fetch('purchase_request.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `part_number=${encodeURIComponent(partNumber)}`
        })
        .then(response => response.json())
        .then(data => {
            row.querySelector('.product-name').value = data.name;
            row.querySelector('.uom').value = data.uom;
        })
        .catch(error => console.error('Error:', error));
    }

    // Attach event listeners to existing rows
    document.querySelectorAll('.part-number').forEach(function(input) {
        input.addEventListener('change', handlePartNumberChange);
    });
});
</script>


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