<?php

require '/../vendor/autoload.php';



use PhpOffice\PhpSpreadsheet\Spreadsheet;

use PhpOffice\PhpSpreadsheet\Writer\Xlsx;



// Assumendo che $conn sia già stato configurato e che $idtrf sia già definito e sanificato per evitare SQL Injection

require_once('../Connections/cmctrfdb.php');

$conn = new mysqli($servername, $username, $password, $dbname);



$idtrf = isset($_GET['idtrf']) ? $conn->real_escape_string($_GET['idtrf']) : die('IDTRF non specificato.');





// Preparazione della query

$query = "

    SELECT

        identificationparts.description_identificationparts,

        identificationparts.article_identificationparts,

        identificationparts.color_identificationparts,

        identificationparts.component_identificationparts,

        identificationparts.material_identificationparts,

        identificationparts.cmcreportnumber_identificationparts,

        identificationparts.cmcreportdate_identificationparts,

        identificationparts.reportof,

        identificationparts.partsidnumber

    FROM identificationparts

    LEFT JOIN partsordercimac ON partsordercimac.arttypeid = identificationparts.arttypeid

                              AND partsordercimac.partsidpicture = identificationparts.partsidnumber

    WHERE identificationparts.idtrfdetails = '$idtrf'

    ORDER BY 

      CASE

        WHEN partsordercimac.partsidcimac IS NULL THEN 9999

        ELSE partsordercimac.partsidcimac

      END

";



$result = $conn->query($query);



if (!$result) {

    die("Errore nell'esecuzione della query: " . $conn->error);

}



$spreadsheet = new Spreadsheet();

$sheet = $spreadsheet->getActiveSheet();



// Intestazioni delle colonne

$colonne = [

    'description_identificationparts',

    'article_identificationparts',

    'color_identificationparts',

    'component_identificationparts',

    'material_identificationparts',

    'cmcreportnumber_identificationparts',

    'cmcreportdate_identificationparts',

    'reportof',

    'partsidnumber'

];



// Imposta le intestazioni delle colonne nel foglio di lavoro

$columnIndex = 'A';

foreach ($colonne as $colonna) {

    $sheet->setCellValue($columnIndex . '1', $colonna);

    $columnIndex++;

}



// Inserimento dei dati nel foglio di lavoro

$rowCount = 2;

while ($row = $result->fetch_assoc()) {

    $columnIndex = 'A';

    foreach ($colonne as $colonna) {

        $sheet->setCellValue($columnIndex . $rowCount, $row[$colonna]);

        $columnIndex++;

    }

    $rowCount++;

}



// Impostazioni per il download del file XLSX

$writer = new Xlsx($spreadsheet);

$fileName = 'lista_parti.xlsx';



header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

header('Content-Disposition: attachment; filename="' . urlencode($fileName) . '"');

$writer->save('php://output');

$conn->close();

exit;

