<?php

use api\classes\API_office_travel_reimburse;
use bin\php\Classes\mailBuilder;
use Dompdf\Dompdf;
use Dompdf\Options;

session_start();

require_once "{$_SERVER['DOCUMENT_ROOT']}/../vendor/autoload.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_office_travel_reimburse.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_companies.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/mailBuilder.php";

$API_office_travel_reimburse = new API_office_travel_reimburse();

if (!$GLOBALS['modules_enabled']['office']) {
    echo '405 Not Allowed';
    exit;
}

if ($API_office_travel_reimburse->request_method === 'POST') {
    $API_office_travel_reimburse->checkPermissions('office-travel-reimburse', 'RO');
    $portal_settings = $GLOBALS['conn']->query("SELECT * FROM system_settings")->fetch_assoc();
    $month = $_POST['calender_month'];
    $firstDay = $month . '-01';
    $lastDay = date('Y-m-t', strtotime($firstDay));

    $_GET['builder'] = [
            1 => [
                    'where' => [
                            0 => 'user_uuid',
                            1 => $_SESSION['user']['user_uuid']
                    ],
                    'between' => [
                            0 => 'travel_date',
                            1 => $firstDay,
                            2 => $lastDay
                    ],
                    'orderBy' => [
                            0 => 'travel_date',
                            1 => 'ASC'
                    ]
            ]
    ];

    $travel_reimbursements = $API_office_travel_reimburse->getTravelReimburse();

    // format is this: 2026-07
    $month = $_POST['calender_month'];

    $lastDay = date('Y-m-t', strtotime($month . '-01'));
    $invoiceNumber = 'D-' . date('nY', strtotime($month . '-01'));

    $totalBusinessKm = 0;
    $totalHomeworkKm = 0;

    foreach ($travel_reimbursements as $trip) {
        if ($trip['homework']) {
            $totalHomeworkKm += $trip['travel_distance'];
        } else {
            $totalBusinessKm += $trip['travel_distance'];
        }
    }

    $totalKm = $totalBusinessKm + $totalHomeworkKm;

    $amountExcl =
            ($totalBusinessKm * $portal_settings['office_travelreimburse_cents_business_excl']) +
            ($totalHomeworkKm * $portal_settings['office_travelreimburse_cents_homework_excl']);

    $amountIncl =
            ($totalBusinessKm * $portal_settings['office_travelreimburse_cents_business_incl']) +
            ($totalHomeworkKm * $portal_settings['office_travelreimburse_cents_homework_incl']);

    // cents -> euros
    $amountExcl /= 100;
    $amountIncl /= 100;

    ob_start();
    ?>

    <h2><?= __('travelReimburse') ?></h2>

    <table border="0" cellpadding="4">
        <tr>
            <td>
                <strong><?= __('date') ?>:</strong>
            </td>
            <td><?= date('d/m/Y', strtotime($lastDay)); ?></td>
        </tr>
        <tr>
            <td>
                <strong><?= __('full_name') ?>:</strong>
            </td>
            <td><?= htmlspecialchars($_SESSION['user']['user_full_name']); ?></td>
        </tr>
        <tr>
            <td>
                <strong><?= __('invoice_number') ?>:</strong>
            </td>
            <td><?= $invoiceNumber; ?></td>
        </tr>
        <tr>
            <td>
                <strong><?= __('total_travel_excl') ?>:</strong>
            </td>
            <td>€ <?= number_format($amountExcl, 2, ',', '.'); ?></td>
        </tr>
        <tr>
            <td>
                <strong><?= __('total_travel_incl') ?>:</strong>
            </td>
            <td>€ <?= number_format($amountIncl, 2, ',', '.'); ?></td>
        </tr>
    </table>

    <br>

    <table border="1" cellpadding="5" cellspacing="0">
        <thead>
        <tr>
            <th><?= __('date') ?></th>
            <th><?= __('from') ?></th>
            <th><?= __('to') ?></th>
            <th><?= __('company') ?></th>
            <th>KM <?= __('homework') ?></th>
            <th>KM <?= __('business') ?></th>
            <th><?= __('description') ?></th>

        </tr>
        </thead>

        <tbody>

        <?php foreach ($travel_reimbursements as $trip) { ?>

            <tr>
                <td><?= date('d-m-Y', strtotime($trip['travel_date'])); ?></td>
                <td><?= htmlspecialchars($trip['departure_postcode']); ?></td>
                <td><?= htmlspecialchars($trip['destination_postcode']); ?></td>
                <td><?= htmlspecialchars($trip['office_travelreimburse_company_name']); ?></td>
                <td><?= ($trip['homework'] ? $trip['travel_distance'] : '') ?></td>
                <td><?= ($trip['homework'] ? '' : $trip['travel_distance']) ?></td>
                <td><?= $trip['travel_description']; ?></td>
            </tr>

        <?php } ?>
        <tr>
            <td colspan="5" align="right">
                <strong><?= __('total') . ' ' . __('business') ?> km</strong>
            </td>
            <td>
                <strong><?= $totalBusinessKm; ?></strong>
            </td>
            <td></td>
        </tr>
        <tr>
            <td colspan="5" align="right">
                <strong><?= __('total') . ' ' . __('homework') ?> km</strong>
            </td>
            <td>
                <strong><?= $totalHomeworkKm; ?></strong>
            </td>
            <td></td>
        </tr>
        <tr>
            <td colspan="5" align="right">
                <strong><?= __('total') ?></strong>
            </td>
            <td>
                <strong><?= $totalKm; ?></strong>
            </td>
            <td></td>
        </tr>
        </tbody>
    </table>
    <?php

    $html = ob_get_clean();

    $options = new Options();
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);

    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $pdfFile = sys_get_temp_dir() . '/travel_reimburse.pdf';

    file_put_contents(
            $pdfFile,
            $dompdf->output()
    );

    $mail = new mailBuilder();

    $mail->addAddress($_SESSION['user']['user_email'], $_SESSION['user']['user_full_name']);
    $mail->subject = 'Travel reimbursement ' . $_SESSION['user']['user_full_name'] . ' - ' . $invoiceNumber;
    $mail->mailText = 'Your travel reimbursement is attached.';

    try {
        $mail->addAttachment($pdfFile, 'travel_reimbursement.pdf');
    } catch (\PHPMailer\PHPMailer\Exception $e) {

    }

    $mail->sendMail();

    unlink($pdfFile);

    $API_office_travel_reimburse->apiOutput(200, ['success' => 'Message send.']);
}