<?php
if (!file_exists('../../../' . TENANT_URL . '/output/reports/' . $_REQUEST['clientnumber'])) {
    mkdir('../../../' . TENANT_URL . '/output/reports/' . $_REQUEST['clientnumber']);
}
require "../../packages/phpqrcode/qrlib.php";
QRcode::png(getCompanyDetails('web') . '/preview.php?repnumber=' . $_REQUEST['repnumber'], '../../../' . TENANT_URL . '/images/repQR.png', 'L', 4, 2);
if (empty($_REQUEST['mode'])) {
    $_REQUEST['mode'] = '';
}
$header = '';
$body = '';
$footer = '';
$header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="packages/bootstrap/bootstrap.gen.css" rel="stylesheet">
</head> 
<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="font-size:10px!important">
';
////////////////////////////////////
if (!empty($generic)) {

    $body .= '<htmlpageheader name="GenericPageHeaderPage">';
    if ($_REQUEST['mode'] == "split") {
        $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header_generic_split.php');
    } else {
        $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header_generic.php');
    }
    $body .= '</htmlpageheader>';

    $body .= '<htmlpagefooter name="GenericPageFooterPage">';
    if ($cover == "yes") {
        $body .= '<table width="100%" style="font-family: serif; font-size: 8pt; color: #000000; font-weight: bold; font-style: italic; border-top:1px solid #2a3f54">
        <tr>
        <td width="25%" align="center" style="background-color:#e96152; color:#ffffff">URGENT</td>
        <td width="25%" align="center" style="background-color:#F4AA09; color:#ffffff">DEFECTS</td>
        <td width="25%" align="center" style="background-color:#333333; color:#ffffff">OBS</td>
        <td width="25%" align="center" style="background-color:#007E33; color:#ffffff">PASS</td>
        <td width="25%" align="center" style="background-color:#cccccc; color:#ffffff">PNA</td>
        </tr>
        <tr>
        <td align="center">DEFECTS REQUIRING URGENT ATTENTION</td>
        <td align="center">OTHER DEFECTS</td>
        <td align="center">OBSERVATIONS</td>
        <td align="center">NO ACTION REQUIRED</td>
        <td align="center">PLANT NOT AVAILABLE</td>
        </tr>
        </table>';
    }
    $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/footer_generic.php');
    $body .= '</htmlpagefooter>';
    $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/style_generic.php');
} else {

    if (!empty($multirow)) {

        $body .= '<htmlpageheader name="MultiPageHeader">';
        if ($_REQUEST['mode'] == "split") {
            $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header_split.php');
        } else {
            $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header.php');
        }
        $body .= $post;
        $body .= $multirow;
        $body .= '</htmlpageheader>

    <htmlpageheader name="MultiPageHeaderPage">';
        if ($_REQUEST['mode'] == "split") {
            $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header_split.php');
        } else {
            $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header.php');
        }
        $body .= $multirow;
        $body .= '</htmlpageheader>';

        $body .= '<htmlpagefooter name="MultiPageFooterPage">';
        $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/footer_multi.php');
        $body .= '</htmlpagefooter>';

        if (!$default_header) {
            $header .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header.php');
        } else {
            $header .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header_generic.php');
        }
        $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/style_multi.php');

        if (!$default_footer) {
            $footer = file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/footer_multi.php');
        } else {
            $footer = file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/footer_generic.php');
        }
    } else {
        $body .= '<htmlpageheader name="repPageHeader">';
        if ($_REQUEST['mode'] == "split") {
            $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header_split.php');
        } else {
            $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/header.php');
        }
        if (!empty($post)) {
            $body .= $post;
        }
        if (!empty($inst)) {
            $body .= $inst;
        }
        $body .= '</htmlpageheader>';

        $body .= '<htmlpagefooter name="PageFooterPage">';
        $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/' . $footerTemplate);
        $body .= '</htmlpagefooter>';


        $body .= file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/style.php');

        if (!$default_footer) {
            $footer = file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/' . $footerTemplate);
        } else {
            $footer = file_get_contents('../../../' . TENANT_URL . '/engines/pdf_structure/footer_generic.php');
        }
    }
    $sdata = explode("|", getSurveyorDetails($_REQUEST['repnumber'], 'REPDATA'));
    if (empty($multipath)) {
        $rdata = explode("|", getItemReportDetails($_REQUEST['repnumber'], 'REPDATA'));
    }
    $cdata = explode("|", getCompanyDetails('REPDATA'));
}

$body .= $postData;
$body .= $pdf;
$imagePath = '../../../' . TENANT_URL . '/images/signatures/' . $sdata[2] . '.jpg';
if (file_exists($imagePath)) {
    // Read the image file
    $imageData = file_get_contents($imagePath);

    // Encode the image data to base64
    $base64Image = base64_encode($imageData);

    // Create the base64 image source string
    $base64ImageSrc = 'data:image/jpeg;base64,' . $base64Image;
}
//// CONTENT REPLACEMENT
$body = str_replace('[SURVEYOR_NAME]', $sdata[0], $body);
$body = str_replace('[SURVEYOR_QUAL]', $sdata[1], $body);
$body = str_replace('[SURVEYOR_SIGNITURE]', $base64ImageSrc, $body);
$body = str_replace('[GARY_QUAL]', 'IEng MSOE MIPlantE MBES', $body);
$body = str_replace('[GARY_SIGNITURE]', '2', $body);
$body = str_replace('[REPNO]', $rdata[0], $body);
$body = str_replace('[EXAM_DATE]', $rdata[1], $body);
$body = str_replace('[EXAM_PREVDATE]', $rdata[2], $body);
$body = str_replace('[EXAM_NEXTDATE]', $rdata[3], $body);
$body = str_replace('[REPORT_DATE]', date('d-m-Y'), $body);
//$body=str_replace('[REPORT_DATE]','01-03-2022',$body);
$body = str_replace('[REP]', $_REQUEST['repnumber'], $body);
$body = str_replace('[ITE]', $cx['itemnumber'], $body);
$body = str_replace('[ADDRESS]', getCompanyDetails('addressLong'), $body);
$body = str_replace('[CONTACT]', getCompanyDetails('contact'), $body);
$body = str_replace('[TEL]', getCompanyDetails('tel'), $body);
$body = str_replace('[QR]', '<td><img src="../../../' . TENANT_URL . '/images/repQR.png" height="40px"></td>', $body);

$footer = str_replace('[SURVEYOR_NAME]', $sdata[0], $footer);
$footer = str_replace('[SURVEYOR_QUAL]', $sdata[1], $footer);
$footer = str_replace('[SURVEYOR_SIGNITURE]', $sdata[2], $footer);
$footer = str_replace('[GARY_QUAL]', 'IEng MSOE MIPlantE MBES', $footer);
$footer = str_replace('[GARY_SIGNITURE]', '2', $footer);
$footer = str_replace('[REPNO]', $rdata[0], $footer);
$footer = str_replace('[EXAM_DATE]', $rdata[1], $footer);
$footer = str_replace('[EXAM_PREVDATE]', $rdata[2], $footer);
$footer = str_replace('[EXAM_NEXTDATE]', $rdata[3], $footer);
$footer = str_replace('[REPORT_DATE]', date('d-m-Y'), $footer);
//$footer=str_replace('[REPORT_DATE]','01-03-2022',$footer);
$footer = str_replace('[REP]', $_REQUEST['repnumber'], $footer);
$footer = str_replace('[ITE]', $cx['itemnumber'], $footer);
$footer = str_replace('[ADDRESS]', getCompanyDetails('addressLong'), $footer);
$footer = str_replace('[CONTACT]', getCompanyDetails('contact'), $footer);
$footer = str_replace('[TEL]', getCompanyDetails('tel'), $footer);

$footer = str_replace('[QR]', '<td><img src="../../../' . TENANT_URL . '/images/repQR.png" height="40px"></td>', $footer);


$body = str_replace('[REPORT_PATH]', getCompanyDetails('web'), $body);

if (file_exists('../../../' . TENANT_URL . '/images/company/logo.jpg')) {
    $body = str_replace('[LGO]', '<img src="' . '../../../' . TENANT_URL . '/images/company/logo.jpg" height="70px" />', $body);
} else {
    $body = str_replace('[AF1]', '', $body);
}
if (file_exists('../../../' . TENANT_URL . '/images/client/' . $_REQUEST['clientnumber'] . '.jpg')) {
    $body = str_replace('[CL1]', '<td align="center"><img src="' . '../../../' . TENANT_URL . '/images/client/' . $_REQUEST['clientnumber'] . '.jpg" height="70px" /></td>', $body);
} else {
    $body = str_replace('[CL1]', '', $body);
}


$form = $_REQUEST['form']; // The form key, e.g., 600
$customImages = is_array($customImages) ? $customImages : [];
if (array_key_exists($form, $customImages)) {
    $excludeImage = $customImages[$form]; // The image to exclude for this form

    for ($i = 1; $i <= 6; $i++) {
        $imageKey = "afl_$i";
        $imagePath = '../../../' . TENANT_URL . "/images/company/$imageKey.jpg";

        if ($excludeImage == $i) {
            // Skip displaying the excluded image
            $body = str_replace("[AF$i]", '', $body);
            continue;
        }

        // Check if the image file exists and replace the placeholder
        if (file_exists($imagePath)) {
            $body = str_replace("[AF$i]", '<td><img src="' . $imagePath . '" height="40px" /></td>', $body);
        } else {
            $body = str_replace("[AF$i]", '', $body);
        }
    }
} else {
    // If the form is not in the array, process all images normally
    for ($i = 1; $i <= 6; $i++) {
        $imageKey = "afl_$i";
        $imagePath = '../../../' . TENANT_URL . "/images/company/$imageKey.jpg";

        if (file_exists($imagePath)) {
            $body = str_replace("[AF$i]", '<td><img src="' . $imagePath . '" height="40px" /></td>', $body);
        } else {
            $body = str_replace("[AF$i]", '', $body);
        }
    }
}

if (file_exists('../../../' . TENANT_URL . '/images/company/logo.jpg')) {
    $body = str_replace('[LGO]', '<img src="' . '../../../' . TENANT_URL . '/images/company/logo.jpg" height="70px" />', $body);
} else {
    $header = str_replace('[LGO]', '', $header);
}
if (file_exists('../../../' . TENANT_URL . '/images/client/' . $_REQUEST['clientnumber'] . '.jpg')) {
    $header = str_replace('[CL1]', '<td align="center"><img src="' . '../../../' . TENANT_URL . '/images/client/' . $_REQUEST['clientnumber'] . '.jpg" height="70px" /></td>', $header);
} else {
    $header = str_replace('[CL1]', '', $header);
}


$form = $_REQUEST['form']; // The form key, e.g., 600

if (array_key_exists($form, $customImages)) {
    $excludeImage = $customImages[$form]; // The image to exclude for this form

    for ($i = 1; $i <= 6; $i++) {
        $imageKey = "afl_$i";
        $imagePath = '../../../' . TENANT_URL . "/images/company/$imageKey.jpg";

        if ($excludeImage == $i) {
            // Skip displaying the excluded image
            $header = str_replace("[AF$i]", '', $header);
            continue;
        }

        // Check if the image file exists and replace the placeholder
        if (file_exists($imagePath)) {
            $header = str_replace("[AF$i]", '<td><img src="' . $imagePath . '" height="40px" /></td>', $header);
        } else {
            $header = str_replace("[AF$i]", '', $header);
        }
    }
} else {
    // If the form is not in the array, process all images normally
    for ($i = 1; $i <= 6; $i++) {
        $imageKey = "afl_$i";
        $imagePath = '../../../' . TENANT_URL . "/images/company/$imageKey.jpg";

        if (file_exists($imagePath)) {
            $header = str_replace("[AF$i]", '<td><img src="' . $imagePath . '" height="40px" /></td>', $header);
        } else {
            $header = str_replace("[AF$i]", '', $header);
        }
    }
}

if ($orientation == '') {
    if ($_REQUEST['orientation'] == "1" || empty($_REQUEST['orientation'])) {
        $orientation = "P";
    }
    if ($_REQUEST['orientation'] == "0") {
        $orientation = "L";
    }
}

if ($_REQUEST['mode'] == "split") {
} else {
    require_once '../../packages/mpd/vendor/autoload.php';
}


$mpdf = new \Mpdf\Mpdf([
    'mode' => 'utf-8',
    'format' => 'A4',
    'orientation' => $orientation,
    'margin_top' => 10,
    'margin_header' => 3,
    'margin_footer' => 3,
    'margin_left' => 10,
    'margin_right' => 10,
    'margin_bottom' => 6,
    'setAutoTopMargin' => 'stretch',
    'setAutoBottomMargin' => 'stretch',
]);

$header = mb_convert_encoding($header, 'UTF-8', 'UTF-8');
$footer = mb_convert_encoding($footer, 'UTF-8', 'UTF-8');
$body = mb_convert_encoding($body, 'UTF-8', 'UTF-8');
$mpdf->shrink_tables_to_fit = 1;
$mpdf->SetHTMLHeader($header, 0, true);
$mpdf->SetHTMLFooter($footer, 0, true);
$mpdf->WriteHTML($body);
$mpdf->Output($filestore);