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

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use classs\MYPDF;
/* use Dompdf\Dompdf;
use Dompdf\Options;
// use TCPDF\TCPDF;
use Mpdf\Mpdf; */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['data']) && isset($_POST['downloadType'])) {
        $dataString = $_POST['data'];
        $dataArray = json_decode($dataString, true);
        $downloadType = $_POST['downloadType'];
        $nameReport = $_POST['namereport'];

        if ($downloadType === 'excel') {
            downloadExcel($dataArray, $nameReport);
        } elseif ($downloadType === 'pdf') {
            downloadPDF($dataArray, $nameReport);
        } elseif ($downloadType === 'pdfP') {
            downloadPDF($dataArray, $nameReport, "print");
        } elseif ($downloadType === 'invoicepdf') {
            $htmlBank = $_POST['dataBankPDFP'];
            $htmlvo = $_POST['datavoPDFP'];
            $dataArrayBank = json_decode($htmlBank, true);
            $htmlvo = json_decode($htmlvo, true);
            invoicePDF($dataArray, $nameReport, $dataArrayBank, $htmlvo);
        } elseif ($downloadType === 'invoicepdfP') {
            $htmlBank = $_POST['dataBankPDFP'];
            $htmlvo = $_POST['datavoPDFP'];
            $dataArrayBank = json_decode($htmlBank, true);
            $htmlvo = json_decode($htmlvo, true);
            invoicePDF($dataArray, $nameReport, $dataArrayBank, $htmlvo, "print");
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid download type']);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Invalid data or download type']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}

function downloadExcel($dataArray, $nameReport) {
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->fromArray($dataArray, null, 'A1');

    // تحديد حجم ثابت لكل الخلايا في الصف
    foreach ($sheet->getRowIterator() as $row) {
        foreach ($row->getCellIterator() as $cell) {
            $column = $cell->getColumn();
            $sheet->getColumnDimension($column)->setWidth(20); // حد أقصى للعرض
        }
    }

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="'.$nameReport.'_'.date('d-m-Y h-i-s').'.xlsx"');
    header('Cache-Control: max-age=0');
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
}

function downloadPDF($dataArray, $nameReport, $print = NULL) {
    // Create a new TCPDF instance
    // $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

    // Set document information
    $pdf->SetCreator('E-ZAKI TECH');
    $pdf->SetAuthor('E-ZAKI TECH');
    $pdf->SetTitle($nameReport.' من برنامج E-ZAKI TECH');

    // Set font
    $pdf->SetFont('dejavusans', '', 12);
    // Add a page
    $pdf->AddPage();
    /* $htmlContent = '<table border="1">';
    foreach ($dataArray as $row) {
        $htmlContent .= '<tr>';
        foreach ($row as $cell) {
            $htmlContent .= '<td>' . $cell . '</td>';
        }
        $htmlContent .= '</tr>';
    }
    $htmlContent .= '</table>'; */
    // HTML content for the PDF
    $html = '<html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <style>
                body { direction: ltr; }
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid #000; padding: 8px; text-align: center; }
                .panel-primary>.panel-heading {
                    color: #fff;
                    background-color: #2194e5;
                    background: -webkit-linear-gradient(top, #3993ba 0%,#067ead 100%);
                    border-color: #337ab7;
                }
                .panel-heading {
                    padding: 10px 15px;
                    border-bottom: 1px solid transparent;
                    border-top-left-radius: 3px;
                    border-top-right-radius: 3px;
                    text-align: center;
                }
            </style>
        </head>
        <body>
            '.$dataArray.'
        </body>
    </html>';

    // Write the HTML content to the PDF
    $pdf->writeHTML($html, true, false, true, false, '');
    // $pdf->writeHTMLCell($html, true, false, true, false, '');

    // Output the PDF as a download
    /*
     * The method first calls Close() if necessary to terminate the document.
    * @param $name: The name of the file when saved
    * @param $dest: Destination where to send the document.
    * It can take one of the following values:
    * I: send the file inline to the browser (default). The plug-in is used if available.
    * The name given by name is used when one selects the "Save as" option on the link generating the PDF.
    * D: send to the browser and force a file download with the name given by name.
    * F: save to a local server file with the name given by name.
    * S: return the document as a string (name is ignored).
    * FI: equivalent to F + I option
    * FD: equivalent to F + D option
    * E: return the document as base64 mime multi-part email attachment (RFC 2045)
    */
    if ($print === NULL) {
        # code...
        $pdf->Output($nameReport.'_'.date('d-m-Y h-i-s').'.pdf', 'D');
    } else {
        $pdf->Output($nameReport.'_'.date('d-m-Y h-i-s').'.pdf', 'I');
    }
}
function invoicePDF($dataArray, $nameReport, $dataArrayBank, $htmlvo, $print = NULL) {
// Create a new TCPDF instance
// $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf = new MYPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->titlear = ('إكسبلور ناسا ترافل');
$pdf->titleen = ('Explore Nasa Travel');

$pdf->address = ('<span >21 Qait Bay ST. Port of Omar Ibn EL Khatab, Ismailia Square, Heliopolis Cairo - EGYPT</span>');

// Set document information
$pdf->SetCreator('E-ZAKI TECH');
$pdf->SetAuthor('E-ZAKI TECH');
$pdf->SetTitle($nameReport.' من برنامج E-ZAKI TECH');

// set default header data

$pdf->SetHeaderData('', 10, 'Invoice', '');
$pdf->setFooterData(array(0,64,0), array(0,64,128));

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, 50, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(20);
$pdf->SetFooterMargin(0);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// Set font
// $pdf->SetFont('dejavusans', '', 12);
$pdf->SetFont('aealarabiya', '', 12);


// Add a page
// $pdf->AddPage('L','A4');
$pdf->AddPage('P','A4');

$pdf->SetLineStyle( array( 'width' => 15, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0,0,0)));
$pdf->Line(0,0,$pdf->getPageWidth(),0); 
$pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,0,0,$pdf->getPageHeight());
$pdf->SetLineStyle( array( 'width' => 14, 'color' => array(255,255,255)));
$pdf->Line(0,0,$pdf->getPageWidth(),0); 
$pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,0,0,$pdf->getPageHeight());
// $pdf->MultiCell(60, 4, $pdf->getPageWidth(), 1, 'C', 1, 0);

/* $htmlContent = '<table border="1">';
foreach ($dataArray as $row) {
    $htmlContent .= '<tr>';
    foreach ($row as $cell) {
        $htmlContent .= '<td>' . $cell . '</td>';
    }
    $htmlContent .= '</tr>';
}
$htmlContent .= '</table>'; */
// HTML content for the PDF
$html = '<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style>
            
        </style>
    </head>
    <body>
        '.$dataArray.'
    </body>
</html>';

// Write the HTML content to the PDF
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->writeHTML($dataArrayBank, true, false, false, false, '');
/* $style = array(
    'border' => 2,
    'vpadding' => 'auto',
    'hpadding' => 'auto',
    'fgcolor' => array(0,0,0),
    'bgcolor' => false, //array(255,255,255)
    'module_width' => 1, // width of a single module in points
    'module_height' => 1 // height of a single module in points
); */
// $pdf->write2DBarcode('$pdf->writeHTML($html, true, false, true, false, "")', 'QRCODE,H', '', '', 50, 50, $style, 'N');
// $pdf->Footer();
// $pdf->AddPage('P','A4');
$pdf->AddPage();
$pdf->SetLineStyle( array( 'width' => 15, 'color' => array(0,0,0)));
$pdf->Line(0,0,$pdf->getPageWidth(),0); 
$pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,0,0,$pdf->getPageHeight());

$pdf->SetLineStyle( array( 'width' => 14, 'color' => array(255,255,255)));
$pdf->Line(0,0,$pdf->getPageWidth(),0); 
$pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,0,0,$pdf->getPageHeight());
$pdf->writeHTML($htmlvo, true, false, true, false, '');

/* $pdf->AddPage();
$pdf->SetLineStyle( array( 'width' => 15, 'color' => array(0,0,0)));
$pdf->Line(0,0,$pdf->getPageWidth(),0); 
$pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,0,0,$pdf->getPageHeight());

$pdf->SetLineStyle( array( 'width' => 14, 'color' => array(255,255,255)));
$pdf->Line(0,0,$pdf->getPageWidth(),0); 
$pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
$pdf->Line(0,0,0,$pdf->getPageHeight()); */


// $pdf->writeHTMLCell($html, true, false, true, false, '');

// Output the PDF as a download
/**
 * The method first calls Close() if necessary to terminate the document.
* @param $name: The name of the file when saved
* @param $dest: Destination where to send the document.
* It can take one of the following values:
* I: send the file inline to the browser (default). The plug-in is used if available.
* The name given by name is used when one selects the "Save as" option on the link generating the PDF.
* D: send to the browser and force a file download with the name given by name.
* F: save to a local server file with the name given by name.
* S: return the document as a string (name is ignored).
* FI: equivalent to F + I option
* FD: equivalent to F + D option
* E: return the document as base64 mime multi-part email attachment (RFC 2045)
 */
if ($print === NULL) {
    # code...
    $pdf->Output($nameReport.'_'.date('d-m-Y h-i-s').'.pdf', 'D');
} else {
    $pdf->Output($nameReport.'_'.date('d-m-Y h-i-s').'.pdf', 'I');
}
}
?>
