<?php
include "../../root.class.php";
require '../../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$call = new call_functions();
$db = new db_safeguard();

$dispatch_res = $db->query('order_trans', "SELECT * FROM stock_take_stock LEFT JOIN stock ON stock_take_stock.item_id = stock.record_id WHERE stock_take_id = 2 ORDER BY stock.description ASC");

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Add headers
$sheet->fromArray(['Item', 'Amount (System)', 'Amount (Counted)'], NULL, 'A1');

// Fetch data and add to spreadsheet
$row = 2;
while ($dispatch = $dispatch_res->fetch_assoc()) {
    $sheet->fromArray([
        $dispatch['description'],
        $dispatch['amount_in_stock'],
        $dispatch['amount_counted']
     
    ], NULL, 'A' . $row++);
}

// Output as Excel file
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="stock_take.xlsx"');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
