<?php
require_once('../../../common/lib.php');
require_once('../../../common/define.php');


function pms_format_gmt_date($format, $timestamp = null) # BINARIQUE EDITED
{
    if ($timestamp === null) {
        $timestamp = time();
    }

    // For PHP 8.1+ where strftime is deprecated
    if (function_exists('datefmt_format_object')) {
        $map = [
            '%a' => 'EEE',    // Abbreviated weekday name
            '%A' => 'EEEE',   // Full weekday name
            '%b' => 'MMM',    // Abbreviated month name
            '%B' => 'MMMM',   // Full month name
            '%c' => 'yyyy-MM-dd HH:mm:ss', // Preferred date and time representation
            '%C' => 'yy',     // Century number (year/100)
            '%d' => 'dd',     // Day of the month (01-31)
            '%D' => 'MM/dd/yy', // Short MM/DD/YY date
            '%e' => 'd',      // Day of the month (1-31) with single digits preceded by space
            '%F' => 'yyyy-MM-dd', // ISO 8601 date
            '%g' => 'yy',     // Two-digit year (ISO 8601)
            '%G' => 'yyyy',   // Four-digit year (ISO 8601)
            '%h' => 'MMM',   // Abbreviated month name (same as %b)
            '%H' => 'HH',     // Hour in 24h format (00-23)
            '%I' => 'hh',     // Hour in 12h format (01-12)
            '%j' => 'D',      // Day of the year (001-366)
            '%k' => 'H',      // Hour in 24h format (0-23) with single digits preceded by space
            '%l' => 'h',      // Hour in 12h format (1-12) with single digits preceded by space
            '%m' => 'MM',     // Month as decimal number (01-12)
            '%M' => 'mm',     // Minute (00-59)
            '%n' => "\n",     // Newline character
            '%p' => 'a',      // AM or PM
            '%P' => 'a',      // am or pm (lowercase)
            '%r' => 'hh:mm:ss a', // 12-hour time with AM/PM
            '%R' => 'HH:mm',  // 24-hour time without seconds
            '%S' => 'ss',     // Second (00-61)
            '%t' => "\t",     // Tab character
            '%T' => 'HH:mm:ss', // 24-hour time with seconds
            '%u' => 'e',      // ISO 8601 weekday as number (1-7, Monday is 1)
            '%U' => 'w',      // Week number with Sunday as first day (00-53)
            '%V' => 'ww',     // ISO 8601 week number (01-53)
            '%w' => 'e',     // Weekday as decimal (0-6, Sunday is 0)
            '%W' => 'w',      // Week number with Monday as first day (00-53)
            '%x' => 'yyyy-MM-dd', // Preferred date representation
            '%X' => 'HH:mm:ss', // Preferred time representation
            '%y' => 'yy',     // Two-digit year (00-99)
            '%Y' => 'yyyy',   // Four-digit year
            '%z' => 'xx',    // Timezone offset
            '%Z' => 'zzz',    // Timezone name or abbreviation
            '%%' => '%'       // Literal % character
        ];

        $intlFormat = strtr($format, $map);

        try {
            $date = new DateTime('@' . $timestamp);
            $date->setTimezone(new DateTimeZone('UTC'));

            $formatter = new IntlDateFormatter(
                'en_US',
                IntlDateFormatter::FULL,
                IntlDateFormatter::FULL,
                'UTC',
                IntlDateFormatter::GREGORIAN,
                $intlFormat
            );

            // Handle special cases that IntlDateFormatter doesn't support directly
            $result = $formatter->format($date);

            // Post-processing for formats that don't map perfectly
            if (strpos($format, '%P') !== false) {
                $result = strtolower($result);
            }
            if (strpos($format, '%e') !== false) {
                $result = str_replace(' 1', ' 1', $result); // Space-padded day
            }

            return $result;
        } catch (Exception $e) {
            return false;
        }
    }

    // For older PHP versions where strftime is available
    if (function_exists('gmstrftime')) {
        error_reporting(0);
        return gmstrftime($format, $timestamp);
    }

    // Fallback for very old PHP versions (shouldn't be needed in practice)
    return date($format, $timestamp);
}


if(isset($_POST['id']) && isset($_SESSION['user']['id'])){
    $id_booking = (int)$_POST['id'];
    if(is_numeric($id_booking)){ ?>
        <script>
            function printElem(elem){
                var popup = window.open('', 'print', 'height=800,width=600');
                popup.document.write('<html><head><title>'+document.title+'</title><link rel="stylesheet" href="<?php echo pms_getFromTemplate('css/print.css'); ?>"/></head><body>'+document.getElementById(elem).innerHTML+'</body></html>');
                setTimeout(function(){ 
                    popup.document.close();
                    popup.focus();
                    popup.print();
                    popup.close();    
                }, 600);
                return true;
            }
        </script>
        <div class="white-popup-block" id="popup-booking-<?php echo $id_booking; ?>">
            <?php
            $result_booking = $pms_db->query('SELECT * FROM pm_booking WHERE id = '.$id_booking.' AND id_user = '.$pms_db->quote($_SESSION['user']['id']));
            if($result_booking !== false && $pms_db->last_row_count() > 0){
                
                $row = $result_booking->fetch();
            
                echo '
                <h2>'.$pms_texts['BOOKING_SUMMARY'].'</h2>
                <a href="#" onclick="javascript:printElem(\'popup-booking-'.$id_booking.'\');return false;" class="pull-right print-btn"><i class="fa fa-print"></i></a>
                
                <table class="table table-responsive table-bordered">
                    <tr>
                        <th width="50%">'.$pms_texts['BOOKING_DETAILS'].'</th>
                        <th width="50%">'.$pms_texts['BILLING_ADDRESS'].'</th>
                    </tr>
                    <tr>
                        <td>';
							if(!is_null($row['from_date'])){
								echo $pms_texts['CHECK_IN'].' <strong>'.pms_format_gmt_date(PMS_DATE_FORMAT, $row['from_date']).'</strong><br>
								'.$pms_texts['CHECK_OUT'].' <strong>'.pms_format_gmt_date(PMS_DATE_FORMAT, $row['to_date']).'</strong><br>
								<strong>'.$row['nights'].'</strong> '.$pms_texts['NIGHTS'].'<br>
								<strong>'.($row['adults']+$row['children']).'</strong> '.$pms_texts['PERSONS'].' - 
								'.$pms_texts['ADULTS'].': <strong>'.$row['adults'].'</strong> / 
								'.$pms_texts['CHILDREN'].': <strong>'.$row['children'].'</strong>';
								if($row['comments'] != '') echo '<p><b>'.$pms_texts['COMMENTS'].'</b><br>'.nl2br($row['comments']).'</p>';
							}
							echo '
                        </td>
                        <td>
                            '.$row['firstname'].' '.$row['lastname'].'<br>';
                            if($row['company'] != '') echo $pms_texts['COMPANY'].' : '.$row['company'].'<br>';
                            echo nl2br($row['address']).'<br>
                            '.$row['postcode'].' '.$row['city'].'<br>
                            '.$pms_texts['PHONE'].' : '.$row['phone'].'<br>';
                            if($row['mobile'] != '') echo $pms_texts['MOBILE'].' : '.$row['mobile'].'<br>';
                            echo $pms_texts['EMAIL'].' : '.$row['email'].'
                        </td>
                    </tr>
                </table>';
                
                $result_room = $pms_db->query('SELECT * FROM pm_booking_room WHERE id_booking = '.$row['id']);
                if($result_room !== false && $pms_db->last_row_count() > 0){
                    echo '
                    <table class="table table-responsive table-bordered">
                        <tr>
                            <th>'.$pms_texts['ROOM'].'</th>
                            <th>'.$pms_texts['PERSONS'].'</th>
                            <th class="text-center">'.$pms_texts['TOTAL'].'</th>
                        </tr>';
                        foreach($result_room as $room){
                            echo
                            '<tr>
                                <td>'.$room['title'].'</td>
                                <td>
                                    '.($room['adults']+$room['children']).' '.pms_getAltText($pms_texts['PERSON'], $pms_texts['PERSONS'], ($room['adults']+$room['children'])).': ';
                                    if($room['adults'] > 0) echo $room['adults'].' '.pms_getAltText($pms_texts['ADULT'], $pms_texts['ADULTS'], $room['adults']).' ';
                                    if($room['children'] > 0) echo $room['children'].' '.pms_getAltText($pms_texts['CHILD'], $pms_texts['CHILDREN'], $room['children']).' ';
                                    echo '
                                </td>
                                <td class="text-right" width="15%">'.pms_formatPrice($room['amount']*PMS_CURRENCY_RATE).'</td>
                            </tr>';
                        }
                        echo '
                    </table>';
                }
                
                $result_service = $pms_db->query('SELECT * FROM pm_booking_service WHERE id_booking = '.$row['id']);
                if($result_service !== false && $pms_db->last_row_count() > 0){
                    echo '
                    <table class="table table-responsive table-bordered">
                        <tr>
                            <th>'.$pms_texts['SERVICE'].'</th>
                            <th>'.$pms_texts['QUANTITY'].'</th>
                            <th class="text-center">'.$pms_texts['TOTAL'].'</th>
                        </tr>';
                        foreach($result_service as $service){
                            echo
                            '<tr>
                                <td>'.$service['title'].'</td>
                                <td>'.$service['qty'].'</td>
                                <td class="text-right" width="15%">'.pms_formatPrice($service['amount']*PMS_CURRENCY_RATE).'</td>
                            </tr>';
                        }
                        echo '
                    </table>';
                }
                
                $result_activity = $pms_db->query('SELECT * FROM pm_booking_activity WHERE id_booking = '.$row['id']);
                if($result_activity !== false && $pms_db->last_row_count() > 0){
                    echo '
                    <table class="table table-responsive table-bordered">
                        <tr>
                            <th>'.$pms_texts['ACTIVITY'].'</th>
                            <th>'.$pms_texts['DURATION'].'</th>
                            <th>'.$pms_texts['DATE'].'</th>
                            <th>'.$pms_texts['PERSONS'].'</th>
                            <th class="text-center">'.$pms_texts['TOTAL'].'</th>
                        </tr>';
                        foreach($result_activity as $activity){
                            echo
                            '<tr>
                                <td>'.$activity['title'].'</td>
                                <td>'.$activity['duration'].'</td>
                                <td>'.pms_format_gmt_date(PMS_DATE_FORMAT.' '.PMS_TIME_FORMAT, $activity['date']).'</td>
                                <td>
                                    '.($activity['adults']+$activity['children']).' '.pms_getAltText($pms_texts['PERSON'], $pms_texts['PERSONS'], ($activity['adults']+$activity['children'])).': ';
                                    if($activity['adults'] > 0) echo $activity['adults'].' '.pms_getAltText($pms_texts['ADULT'], $pms_texts['ADULTS'], $activity['adults']).' ';
                                    if($activity['children'] > 0) echo $activity['children'].' '.pms_getAltText($pms_texts['CHILD'], $pms_texts['CHILDREN'], $activity['children']).' ';
                                    echo '
                                </td>
                                <td class="text-right" width="15%">'.pms_formatPrice($activity['amount']*PMS_CURRENCY_RATE).'</td>
                            </tr>';
                        }
                        echo '
                    </table>';
                }
                echo '
                <table class="table table-responsive table-bordered">';
                    
                    if(isset($row['discount_amount']) && $row['discount_amount'] > 0){
                        echo '
                        <tr>
                            <th class="text-right">'.$pms_texts['DISCOUNT'].'</th>
                            <td class="text-right">- '.pms_formatPrice($row['discount_amount']*PMS_CURRENCY_RATE).'</td>
                        </tr>';
                    }
                    
                    $result_tax = $pms_db->query('SELECT * FROM pm_booking_tax WHERE id_booking = '.$row['id']);
                    if($result_tax !== false && $pms_db->last_row_count() > 0){
                        foreach($result_tax as $tax){
                            echo '
                            <tr>
                                <th class="text-right">'.$tax['name'].'</th>
                                <td class="text-right">'.pms_formatPrice($tax['amount']*PMS_CURRENCY_RATE).'</td>
                            </tr>';
                        }
                    }
                    
                    echo '
                    <tr>
                        <th class="text-right">'.$pms_texts['TOTAL'].' ('.$pms_texts['INCL_TAX'].')</th>
                        <td class="text-right" width="15%"><b>'.pms_formatPrice($row['total']*PMS_CURRENCY_RATE).'</b></td>
                    </tr>';
                    
                    if(PMS_ENABLE_DOWN_PAYMENT == 1 && $row['down_payment'] > 0){
                        echo '
                        <tr>
                            <th class="text-right">'.$pms_texts['DOWN_PAYMENT'].' ('.$pms_texts['INCL_TAX'].')</th>
                            <td class="text-right" width="15%"><b>'.pms_formatPrice($row['down_payment']*PMS_CURRENCY_RATE).'</b></td>
                        </tr>';
                    }
                    echo '
                </table>';
                    
                echo '<p><strong>'.$pms_texts['PAYMENT'].'</strong><p>';
                
                echo '<p>'.$pms_texts['PAYMENT_METHOD'].' : '.$row['payment_option'].'<br>';
                echo $pms_texts['STATUS'].': ';
                switch($row['status']){
                    case 1: echo $pms_texts['AWAITING']; break;
                    case 2: echo $pms_texts['CANCELLED']; break;
                    case 3: echo $pms_texts['REJECTED_PAYMENT']; break;
                    case 4: echo $pms_texts['PAYED']; break;
                    default: echo $pms_texts['AWAITING']; break;
                }
                echo '<br>';
                
                $result_payment = $pms_db->query('SELECT * FROM pm_booking_payment WHERE id_booking = '.$row['id']);
				if($result_payment !== false && $pms_db->last_row_count() > 0){
					echo '
					<table class="table table-responsive table-bordered">
						<tr>
							<th>'.$pms_texts['DATE'].'</th>
							<th>'.$pms_texts['PAYMENT_METHOD'].'</th>
							<th class="text-center">'.$pms_texts['AMOUNT'].'</th>
						</tr>';
						foreach($result_payment as $payment){
							echo
							'<tr>
								<td>'.pms_format_gmt_date(PMS_DATE_FORMAT.' '.PMS_TIME_FORMAT, $payment['date']).'</td>
								<td>'.$payment['method'].'</td>
								<td class="text-right" width="15%">'.pms_formatPrice($payment['amount']*PMS_CURRENCY_RATE).'</td>
							</tr>';
						}
						echo '
					</table>';
				}
				
                if($row['status'] == 4){
                    echo $pms_texts['PAYMENT_DATE'].' : '.pms_format_gmt_date(PMS_DATE_FORMAT.' '.PMS_TIME_FORMAT, $row['payment_date']).'<br>';
                    if(!empty($row['down_payment'])) echo $pms_texts['DOWN_PAYMENT'].' : '.pms_formatPrice($row['down_payment']*PMS_CURRENCY_RATE).'<br>';
                    if(!empty($row['trans'])) echo $pms_texts['NUM_TRANSACTION'].' : '.$row['trans'];
                }
                echo '</p>';
            } ?>
        </div>
        <?php
    }
} ?>
