<?php

use Dompdf\Dompdf;
use Dompdf\Options;
use chillerlan\QRCode\{QRCode, QROptions};
use chillerlan\QRCode\Data\QRMatrix;
use chillerlan\QRCode\Output\QRMarkupHTML;

require_once 'vendor/autoload.php';

include_once '../casafari.class.php';

//$client_url = 'https://crmapi.proppydev.com';
//$client_secret = 'ZXh0ZXJuYWxkZXY6Rml0aDVmQmRmZ3NkeEhWTUF4aXpkNW9yNjhn';
$client_url = 'https://crmapi.casafaricrm.com';
$client_secret = 'dGVuIEhvb3BlbiAtIENyZWF0aW9uIE1lZGlhOnRlbkhvb3BlbjIwMjQq';

$casafari_api = new CasafariAPI($client_url, $client_secret);

$lang = isset($_GET['lang']) ? $_GET['lang'] : 'en';

$params = [
    'PropertyIncludes' => [
        'IncludeFeatures' => true,
        'IncludeBrokers' => true,
        'IncludeAgency' => true,
        'UseHtmlDescription' => false
    ],
    'PropertyId' => ($_GET['id'] ?: null),
    'Reference' => ($_GET['reference'] ?: null),
    'BusinessTypeIds' => [
        'Sale'
    ],
    'PropertyTypeIds' => [],
    'VisibleOnWebsite' => true,
    'PriceFrom' => ($_GET['price_from'] ?: null),
    'PriceTo' => ($_GET['price_to'] ?: null),
    'MinBedrooms' => ($_GET['bedrooms'] == 'Studio' ? null : $_GET['bedrooms']),
    'MaxBedrooms' => ($_GET['bedrooms'] != 6 ? ($_GET['bedrooms'] == 'Studio' ? 0 : $_GET['bedrooms']) : null),
    'Lang' => $lang,
    'PropertyListSorts' => [
        'SortBy' => 'DateDesc'
    ],
    'InnertLocations' => [
        'RegionIds' => [],
        'CityIds' => [],
        'LocalityIds' => [],
        'Zonenames' => []
    ],
    'CorrelationId' => 'string',
    'EchoToken' => 'string',
    'PrimaryLangId' => 0,
    'RetransmissionIndicator' => true,
    'TimeStamp' => 'string',
    'Version' => 0
];

$properties_json = $casafari_api->getProperties($params);

$property = $properties_json->PropertyList[0];

//Prepare Property Vido
$video_id = null;
if ($property->video) $video_id = explode('?v=', $property->video)[1];

//Prepare Property Features
$features_list = $property->features_list;
$features_list = array_chunk($features_list, ceil(count($features_list) / 2));

$property_title = $property->locale[0]->title;
$main_image = get_final_url($property->photos[0]->Url);
$second_image = get_final_url($property->photos[1]->Url);
$third_image = get_final_url($property->photos[2]->Url);
$fourth_image = get_final_url($property->photos[3]->Url);
$location = $property->location->zone . ', ' . $property->location->City;
$price = $property->price ? number_format($property->price, 0, ',', ' ') . ' ' . $property->currency : 'P. O. A.';

$energy_class_image = $property->energy_rating && $property->energy_rating != 'InProgress' ? '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/energy/'.$property->energy_rating.'.png" /> ' : '';

$main_features_array = [];
$main_features_array[] = '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/bedrooms.svg" /> ' . ($property->bedrooms ? $property->bedrooms : 0);
$main_features_array[] = '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/bathrooms.svg" /> ' . ($property->bathrooms ? $property->bathrooms : 0);
$main_features_array[] = '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/pool.svg" /> ' . (in_array('Pool', $property->features_list_enum) ? '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/check.png" style="width:3mm;height:inherit;" />' : '-');
$main_features_array[] = '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/garage.svg" /> ' . (in_array('Garage', $property->features_list_enum) ? '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/check.png" style="width:3mm;height:inherit;" />' : '-');
$main_features_array[] = '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/construction-size.svg" /> ' . ($property->total_area ? $property->total_area . ' m2' : '-');
$main_features_array[] = '<img src="https://new.tenhoopenrealty.com/casafari/pdf/images/icons/plot-size.svg" /> ' . ($property->plot_area ? $property->plot_area . ' m2' : '-');
$main_features_array[] = $energy_class_image;

$main_features = '';
if(sizeof($main_features_array) > 0) $main_features = implode('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $main_features_array);

$short_description = $property->locale[0]->short;

$property_features1 = '<ul>';
foreach ($features_list[0] as $feature) {
    $property_features1 .= '<li>' . $feature . '</li>';
}
$property_features1 .= '</ul>';

$property_features2 = '<ul>';
foreach ($features_list[1] as $feature) {
    $property_features2 .= '<li>' . $feature . '</li>';
}
$property_features2 .= '</ul>';


//header('Content-type: application/json; charset=utf-8');
//echo json_encode($property);
//echo '<pre>' . print_r($property, true) . '</pre>';

//Generate QR Code
$qr_code = 'https://new.tenhoopenrealty.com/property-details?reference=' . $property->reference . '&property_id=' . $property->id;
$options = new QROptions;
$options->version         = 5;
$options->outputInterface = QRMarkupHTML::class;
$options->cssClass        = 'qrcode';
$out = (new QRCode($options))->render($qr_code);

$language = [
    'en' => [
        'property_features' => 'Property Features',
    ],
    'pt' => [
        'property_features' => 'Características da Propriedade',
    ],
    'nl' => [
        'property_features' => 'Eigenschappen van het eigendom',
    ],
];
$property_features_title = $language[$lang]['property_features'];

// instantiate and use the dompdf class
$dompdf = new Dompdf();

// load HTML content
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="https://new.tenhoopenrealty.com/casafari/pdf/fonts/stylesheet.css" rel="stylesheet" />
<style>

    @page {
        size: 21cm 29.7cm;
        margin: 10mm;
    }

    body {
        font-family: 'Arquitecta';
        margin: 27.5mm 0;
        text-align: left;
        color: #212c4f;
    }

    #header,
    #footer {
        position: fixed;
        left: 0;
        right: 0;
        color: #212c4f;
        font-size: 14px;
    }

    #header {
        top: 0;
    }

    #footer {
        bottom: 0;
        height: 7mm;
        border-top: 0.1pt solid #b09769;
        padding-top:3mm;
    }
    #footer table {
        width: 100%;
    }
    #footer table td {
        padding: 0;
        vertical-align: top;
        text-align: center;
    }
    #footer table td.border-r {
        border-right: 0.1pt solid #212c4f;
    }

    .page-number {
        text-align: center;
    }

    .page-number:before {
        content: "Page " counter(page);
    }

    hr {
        page-break-after: always;
        border: 0;
    }

    .logo {
        position: absolute;
        top: 0mm;
        left: 0mm;
        width:44.5mm;
    }

    .qrcode {
        position: absolute;
        top: -4mm;
        right: -4mm;
        width: 27.5mm;
    }

    .title {
        font-family: 'Butler';
        font-size: 23px;
        text-align: center;
    }

    .main-image {
        width: 190mm;
        height: 119.5mm;
        position: absolute;
        top: 52mm;
    }
    .second-image {
        width: 56.6666667mm;
        height: 37.433mm;
        position: absolute;
        top: 181.5mm;
        left: 0mm;
    }
    .third-image {
        width: 56.6666667mm;
        height: 37.433mm;
        position: absolute;
        top: 181.5mm;
        left: 66.6666667mm;
    }
    .fourth-image {
        width: 56.6666667mm;
        height: 37.433mm;
        position: absolute;
        top: 181.5mm;
        right: 0mm;
    }

    .main-features {
        position: absolute;
        top: 228.933mm;
        left: 0;
        width: 180mm;
        height: 22mm;
        background-color: #212c4f;
        color: #fff;
        font-family: 'Arquitecta';
        font-weight: 900;
        font-size: 25px;
        text-align: center;
        padding: 5mm;
    }
    .main-features .main-features-list {
        line-height: 8.75mm;
        vertical-align: top;
        font-size: 20px;
        margin-top: 3mm;
    }
    .main-features .main-features-list img {
        width: 8.75mm;
        height: 8.75mm;
        vertical-align: middle;
    }

    .short-description {
        position: absolute;
        top: 52mm;
        height: 43.53mm;
        overflow: hidden;
    }

    .property-features-title {
        position: absolute;
        top: 95.43mm;
        width: 100%;
        font-family: 'Butler';
        font-size: 26px;
        border-bottom: 0.1pt solid #b09769;
    }

    .property-features1 {
        position: absolute;
        top: 110mm;
        left: 0;
        width: 95mm;
        height: 150mm;
        overflow: hidden;
        font-family: 'Arquitecta Book';
        font-size: 16px;
    }
    .property-features2 {
        position: absolute;
        top: 110mm;
        left: 95mm;
        width: 95mm;
        height: 150mm;
        overflow: hidden;
        font-family: 'Arquitecta Book';
        font-size: 16px;
    }
    .property-features1 ul, .property-features2 ul {
        margin: 0;
        list-style-position: outside;
    }
    .property-features1 ul li, .property-features2 ul li {
        margin: 0;
        padding: 0mm;
        line-height: 1.5;
    }

</style>
</head>
<body>
    
    <div id="header">
        <img src="https://new.tenhoopenrealty.com/casafari/pdf/images/logo.png" class="logo" />
        <img src="$out" class="qrcode" />
    </div>

    <div id="footer">
        <table>
            <tr>
                <td class="border-r">Tel: +351 963 766 261</td>
                <td class="border-r">Tel: +351 914 564 506</td>
                <td class="border-r">Email: sales@tenhoopenrealty.com</td>
                <td class="border-r">www.tenhoopenrealty.com</td>
                <td>AMI: 19855</td>
            </tr>
            <tr>
                <td><span style="color: #b09769;font-size:10px;">(Call to national mobile network)</span></td>
                <td><span style="color: #b09769;font-size:10px;">(Call to national mobile network)</td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </table>
    </div>

    <div class="title">$property_title</div>

    <img src="$main_image" class="main-image" />
    <img src="$second_image" class="second-image" />
    <img src="$third_image" class="third-image" />
    <img src="$fourth_image" class="fourth-image" />

    <div class="main-features">
        Ref.: $property->reference&nbsp;&nbsp;&nbsp;<span style="color: #b09769;">|</span>&nbsp;&nbsp;&nbsp;$location&nbsp;&nbsp;&nbsp;<span style="color: #b09769;">|</span>&nbsp;&nbsp;&nbsp;$price<br />
        <div class="main-features-list">$main_features</div>
    </div>

    <hr>

    <div class="title">$property_title</div>

    <div class="short-description">$short_description</div>

    <div class="property-features-title">$property_features_title</div>

    <div class="property-features1">$property_features1</div>
    <div class="property-features2">$property_features2</div>

</body>
</html>
HTML
;
$dompdf->loadHtml($html);
//echo $html;

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'portrait');

//$_dompdf_show_warnings = true;
//$_dompdf_debug = true;

$tmp = sys_get_temp_dir();

$options = new Options();
$options->set('isRemoteEnabled', TRUE);
$options->set('tempDir', $tmp);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html); //load an html
$dompdf->render();
$dompdf->stream('brochure.pdf', ['compress' => true, 'Attachment' => false,]);

function get_final_url($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true); // true to include the header in the output.
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true true to follow any "Location: " header that the server sends as part of the HTTP header.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // true to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.
    curl_exec($ch); // $a will contain all headers
    $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
    return $finalUrl;
}

?>