<?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['message_type']) && $_POST['message_type'] == 'ORDER_CREATED') {

    $insMessage = array();
    foreach ($_POST as $k => $v) $insMessage[$k] = $v;

    $hashSecretWord = PMS_SECRET_WORD;
    $hashSid = PMS_VENDOR_ID;
    $hashOrder = $insMessage['sale_id'];
    $hashInvoice = $insMessage['invoice_id'];
    $StringToHash = strtoupper(md5($hashOrder . $hashSid . $hashInvoice . $hashSecretWord));

    if ($StringToHash != $insMessage['md5_hash']) die('Hash Incorrect');

    $payment_amount = $_POST['invoice_list_amount'];
    $payment_currency = $_POST['list_currency'];
    $vendor_id = $_POST['vendor_id'];
    $id_booking = $_POST['vendor_order_id'];
    $txn_id = $_POST['invoice_id'];

    $result_booking = $pms_db->query('SELECT * FROM pm_booking WHERE id = ' . $id_booking . ' AND status = 1 AND (trans IS NULL OR trans = \'\')');
    if ($result_booking !== false && $pms_db->last_row_count() > 0) {

        $row = $result_booking->fetch();

        $expected_amount = (PMS_ENABLE_DOWN_PAYMENT == 1) ? $row['down_payment'] : $row['total'];

        if ($vendor_id == PMS_VENDOR_ID && $payment_currency == PMS_DEFAULT_CURRENCY_CODE && $payment_amount == $expected_amount) {

            $data = array();
            $data['id'] = $id_booking;
            $data['status'] = 4;
            $data['paid'] = $payment_amount;
            $data['balance'] = $row['total'] - $payment_amount;

            $result_booking = pms_db_prepareUpdate($pms_db, 'pm_booking', $data);
            if ($result_booking->execute() !== false) {

                $data = array();
                $data['id'] = null;
                $data['id_booking'] = $id_booking;
                $data['date'] = time();
                $data['trans'] = $txn_id;
                $data['method'] = '2checkout';
                $data['amount'] = $payment_amount;

                $result_payment = pms_db_prepareInsert($pms_db, 'pm_booking_payment', $data);
                $result_payment->execute();

                $service_content = '';
                $result_service = $pms_db->query('SELECT * FROM pm_booking_service WHERE id_booking = ' . $id_booking);
                if ($result_service !== false && $pms_db->last_row_count() > 0) {
                    foreach ($result_service as $service)
                        $service_content .= $service['title'] . ' x ' . $service['qty'] . ' : ' . pms_formatPrice($service['amount'] * PMS_CURRENCY_RATE) . ' ' . $pms_texts['INCL_VAT'] . '<br>';
                }

                $room_content = '';
                $result_room = $pms_db->query('SELECT * FROM pm_booking_room WHERE id_booking = ' . $id_booking);
                if ($result_room !== false && $pms_db->last_row_count() > 0) {
                    foreach ($result_room as $room) {
                        $room_content .= '<p><b>' . $room['title'] . '</b><br>
                        ' . ($room['adults'] + $room['children']) . ' ' . pms_getAltText($pms_texts['PERSON'], $pms_texts['PERSONS'], ($room['adults'] + $room['children'])) . ': ';
                        if ($room['adults'] > 0) $room_content .= $room['adults'] . ' ' . pms_getAltText($pms_texts['ADULT'], $pms_texts['ADULTS'], $room['adults']) . ' ';
                        if ($room['children'] > 0) {
                            $room_content .= $room['children'] . ' ' . pms_getAltText($pms_texts['CHILD'], $pms_texts['CHILDREN'], $room['children']) . ' ';
                            if (isset($room['child_age'])) {
                                $room_content .= '(' . implode(' ' . $pms_texts['YO'] . ', ', $room['child_age']) . ' ' . $pms_texts['YO'] . ')';
                            }
                        }
                        $room_content .= '<br>' . $pms_texts['PRICE'] . ' : ' . pms_formatPrice($room['amount'] * PMS_CURRENCY_RATE) . '</p>';
                    }
                }

                $activity_content = '';
                $result_activity = $pms_db->query('SELECT * FROM pm_booking_activity WHERE id_booking = ' . $id_booking);
                if ($result_activity !== false && $pms_db->last_row_count() > 0) {
                    foreach ($result_activity as $activity) {
                        $activity_content .= '<p><b>' . $activity['title'] . '</b> - ' . $activity['duration'] . ' - ' . strftime(PMS_DATE_FORMAT . ' ' . PMS_TIME_FORMAT, $activity['date']) . '<br>
                        ' . ($activity['adults'] + $activity['children']) . ' ' . pms_getAltText($pms_texts['PERSON'], $pms_texts['PERSONS'], ($activity['adults'] + $activity['children'])) . ': ';
                        if ($activity['adults'] > 0) $activity_content .= $activity['adults'] . ' ' . pms_getAltText($pms_texts['ADULT'], $pms_texts['ADULTS'], $activity['adults']) . ' ';
                        if ($activity['children'] > 0) $activity_content .= $activity['children'] . ' ' . pms_getAltText($pms_texts['CHILD'], $pms_texts['CHILDREN'], $activity['children']) . ' ';
                        $activity_content .= $pms_texts['PRICE'] . ' : ' . pms_formatPrice($activity['amount'] * PMS_CURRENCY_RATE) . '</p>';
                    }
                }

                $tax_content = '';
                $result_tax = $pms_db->query('SELECT * FROM pm_booking_tax WHERE id_booking = ' . $id_booking);
                if ($result_tax !== false && $pms_db->last_row_count() > 0) {
                    foreach ($result_tax as $tax) {
                        $tax_content .= $tax['name'] . ': ' . pms_formatPrice($tax['amount'] * PMS_CURRENCY_RATE) . '<br>';
                    }
                }

                $mail = pms_getMail($pms_db, 'BOOKING_CONFIRMATION', array(
                    '{firstname}' => $row['firstname'],
                    '{lastname}' => $row['lastname'],
                    '{company}' => $row['company'],
                    '{address}' => $row['address'],
                    '{postcode}' => $row['postcode'],
                    '{city}' => $row['city'],
                    '{country}' => $row['country'],
                    '{phone}' => $row['phone'],
                    '{mobile}' => $row['mobile'],
                    '{email}' => $row['email'],
                    '{Check_in}' => pms_format_gmt_date(PMS_DATE_FORMAT, $row['from_date']),
                    '{Check_out}' => pms_format_gmt_date(PMS_DATE_FORMAT, $row['to_date']),
                    '{num_nights}' => $row['nights'],
                    '{num_guests}' => ($row['adults'] + $row['children']),
                    '{num_adults}' => $row['adults'],
                    '{num_children}' => $row['children'],
                    '{rooms}' => $room_content,
                    '{extra_services}' => $service_content,
                    '{activities}' => $activity_content,
                    '{comments}' => nl2br($row['comments']),
                    '{tourist_tax}' => pms_formatPrice($row['tourist_tax'] * PMS_CURRENCY_RATE),
                    '{discount}' => '- ' . pms_formatPrice($row['discount'] * PMS_CURRENCY_RATE),
                    '{taxes}' => $tax_content,
                    '{down_payment}' => pms_formatPrice($row['down_payment'] * PMS_CURRENCY_RATE),
                    '{total}' => pms_formatPrice($row['total'] * PMS_CURRENCY_RATE),
                    '{payment_notice}' => ''
                ));

                if ($mail !== false) {
                    pms_sendMail(PMS_EMAIL, PMS_OWNER, $mail['subject'], $mail['content'], $row['email'], $row['firstname'] . ' ' . $row['lastname']);
                    pms_sendMail($row['email'], $row['firstname'] . ' ' . $row['lastname'], $mail['subject'], $mail['content']);
                }
            }
        }
    }
}
