<?php
$page_title = 'Search Invoice';
require_once('includes/load.php');

page_require_level(8);

$errors = [];
$invoices = [];

// Function to search invoice in the database
function search_invoice($invoice_numbers) {
    global $db;
    $placeholders = implode(',', array_fill(0, count($invoice_numbers), '?'));
    $sql = "SELECT id, tanggal_pesenan_dibuat, invoice, resi, nama_toko, part_number, quantity, kurir, date_scan, batas_pengiriman 
            FROM awb 
            WHERE invoice IN ($placeholders)";
    return find_by_sql_with_params($sql, $invoice_numbers);
}

// Function to import CSV and search invoices
function import_csv_and_search($file) {
    global $errors;
    $invoices_to_search = [];

    // Open CSV file
    if (($handle = fopen($file, "r")) !== FALSE) {
        // Skip the header row
        fgetcsv($handle);

        // Loop through each row
        while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
            // Assume the invoice number is in the first column
            if (!empty($row[0])) {
                $invoices_to_search[] = trim($row[0]);
            }
        }
        fclose($handle);

        if (!empty($invoices_to_search)) {
            return search_invoice($invoices_to_search);
        }
    } else {
        $errors[] = "Unable to open CSV file.";
    }
    return [];
}

// Handle CSV upload and search
if (isset($_POST['import'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        $csv_file = $_FILES['csv_file']['tmp_name'];
        $invoices = import_csv_and_search($csv_file);

        if (empty($invoices) && empty($errors)) {
            $errors[] = "No matching records found for the imported invoices.";
        }
    } else {
        $errors[] = "Failed to upload CSV file.";
    }
}

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

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <ul>
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <h4>Import CSV to Search Invoice</h4>
        <form method="post" action="search_invoice.php" enctype="multipart/form-data">
            <div class="input-group">
                <input type="file" name="csv_file" class="form-control" accept=".csv">
                <span class="input-group-btn">
                    <button type="submit" name="import" class="btn btn-primary">Import CSV</button>
                </span>
            </div>
        </form>
    </div>
</div>

<?php if (!empty($invoices)): ?>
    <div class="row">
        <div class="col-md-12">
            <h4>Search Results</h4>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th class="text-center">#</th>
                        <th>Invoice</th>
                        <th>Tanggal Pesanan Dibuat</th>
                        <th>Nama Toko</th>
                        <th>Part Number</th>
                        <th>Qty</th>
                        <th>Kurir</th>
                        <th>Resi</th>
                        <th>Date Scan</th>
                        <th>Batas Pengiriman</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($invoices as $invoice): ?>
                        <tr>
                            <td class="text-center"><?php echo count_id(); ?></td>
                            <td><?php echo htmlspecialchars($invoice['invoice']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['tanggal_pesenan_dibuat']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['nama_toko']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['part_number']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['quantity']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['kurir']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['resi']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['date_scan']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['batas_pengiriman']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php else: ?>
    <div class="alert alert-info">No invoices found or no CSV uploaded.</div>
<?php endif; ?>

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