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

$errors = [];
$search_results = [];

// Fungsi untuk mengimpor CSV dan memeriksa data invoice secara kolektif
function import_csv($file) {
    global $db, $errors, $search_results;
    
    if (($handle = fopen($file, 'r')) !== false) {
        fgetcsv($handle); // Lewati baris header
        
        $invoices = [];
        while (($row = fgetcsv($handle, 1000, ',')) !== false) {
            $invoice = $db->escape($row[0]); // Ambil kolom pertama sebagai invoice
            $invoices[] = $invoice;
        }
        
        fclose($handle);
        
        if (!empty($invoices)) {
            $invoices_string = "'" . implode("','", $invoices) . "'";
            $sql = "SELECT * FROM awb WHERE invoice IN ($invoices_string)";
            $search_results = find_by_sql($sql);
        } else {
            $errors[] = "File CSV kosong atau tidak ada data valid.";
        }
    } else {
        $errors[] = "Gagal membuka file CSV.";
    }
}

// Proses pengunggahan file CSV
if (isset($_POST['import'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        $csv_file = $_FILES['csv_file']['tmp_name'];
        import_csv($csv_file);
        if (empty($errors) && !empty($search_results)) {
            $session->msg('s', "Data invoice berhasil diperiksa.");

            // Export otomatis ke Excel
            if (ob_get_length()) {
                ob_end_clean();
            }
            
            header("Content-Type: application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename=hasil_pencarian_invoice.xls");
            header("Pragma: no-cache");
            header("Expires: 0");
            
            // Tulis header kolom
            echo "Tanggal Pesanan Dibuat\tInvoice\tNama Toko\tPart Number\tQty\tUnit Price\tTotal Price\tKurir\tResi\tDate Scan\tBatas Pengiriman\tScan In\tScan Out\tPacker No\tLoc\n";
            
            // Tulis data hasil pencarian
            foreach ($search_results as $result) {
                echo htmlspecialchars($result['tanggal_pesenan_dibuat']) . "\t" .
                     htmlspecialchars($result['invoice']) . "\t" .
                     htmlspecialchars($result['nama_toko']) . "\t" .
                     htmlspecialchars($result['part_number']) . "\t" .
                     htmlspecialchars($result['quantity']) . "\t" .
                     htmlspecialchars($result['unit_price']) . "\t" .
                     htmlspecialchars($result['total_price']) . "\t" .
                     htmlspecialchars($result['kurir']) . "\t" .
                     htmlspecialchars($result['resi']) . "\t" .
                     htmlspecialchars($result['date_scan']) . "\t" .
                     htmlspecialchars($result['batas_pengiriman']) . "\t" .
                     htmlspecialchars($result['scan_in']) . "\t" .
                     htmlspecialchars($result['scan_status']) . "\t" .
                     htmlspecialchars($result['packer_no']) . "\t" .
                     htmlspecialchars($result['loc']) . "\n";
            }
            exit;
        } elseif (empty($search_results)) {
            $session->msg('w', "Tidak ada data invoice yang cocok ditemukan.");
        }
    } else {
        $errors[] = "Gagal mengunggah file CSV.";
    }
}

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-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <h3 class="panel-title">Import dan Cek Invoice</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="import_invoice.php" enctype="multipart/form-data" class="form-inline">
                    <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>
    </div>
</div>

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