set('isRemoteEnabled', true); $dompdf = new Dompdf($options); // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ // include PHP Mailer+++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require dirname(__FILE__).'/lib/mail/PHPMailer.php'; require dirname(__FILE__).'/lib/mail/SMTP.php'; require dirname(__FILE__).'/lib/mail/Exception.php'; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Send Mail via PHPMailer++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ function send_mail_by_PHPMailer($to, $subject, $message, $attachment, $attachment_name){ // Log email attempt debuglog("Attempting to send email to: $to, subject: $subject"); try { // SEND MAIL by PHP MAILER $mail = new PHPMailer(true); $mail->isSMTP(); // Use SMTP $mail->CharSet = 'UTF-8'; $mail->Host = email_host_name; // Specify SMTP server $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Use TLS encryption $mail->SMTPAuth = true; // Auth. SMTP //$mail->SMTPDebug = 3; // To view debug output $mail->Username = email; // Mail who send by PHPMailer $mail->Password = email_outgoing_pw; // your pass mail box $mail->SMTPSecure = email_outgoing_security; // Accept SSL $mail->Port = email_outgoing_port; // port of your out server debuglog("SMTP Config - Host: " . email_host_name . ", Port: " . email_outgoing_port . ", Security: " . email_outgoing_security); $mail->setFrom(email, mail_from); // Mail to send at $mail->addAddress($to); // Add sender $mail->addReplyTo(email_reply_to); // Adress to reply $mail->isHTML(true); // use HTML message $mail->Subject = $subject; $mail->Body = $message; if (!empty($attachment) || $attachment != ''){ $mail->AddStringAttachment($attachment, $attachment_name, 'base64', 'application/pdf'); debuglog("Attachment added: $attachment_name"); } // SEND if( !$mail->send() ){ // render error if it is $tab = array('error' => 'Mailer Error: '.$mail->ErrorInfo ); debuglog("Email send failed: " . json_encode($tab)); return false; } else{ // return true if message is send debuglog("Email sent successfully to: $to"); return true; } } catch (Exception $e) { debuglog("PHPMailer Exception: " . $e->getMessage()); return false; } } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Generated PDF ++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++ function generatedPDF($input,$filename){ $options = new Options(); $options->set('isRemoteEnabled', true); $dompdf = new Dompdf($options); $dompdf->loadHtml($input); // (Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); ob_end_clean(); $dompdf->stream($filename.'.pdf', array("Attachment" => false)); } // Function that will connect to the MySQL database function pdo_connect_mysql() { try { // Connect to the MySQL database using the PDO interface $pdo = new PDO('mysql:host=' . db_host . ';dbname=' . db_name . ';charset=utf8', db_user, db_pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } catch (PDOException $exception) { // Could not connect to the MySQL database! If you encounter this error, ensure your db settings are correct in the config file! exit('Failed to connect to database!'); } } // Function to retrieve a product from cart by the ID and options string function &get_cart_product($id, $options) { $p = null; if (isset($_SESSION['cart'])) { foreach ($_SESSION['cart'] as &$product) { if ($product['id'] == $id && $product['options'] == $options) { $p = &$product; return $p; } } } return $p; } // Populate categories function function populate_categories($categories, $selected = 0, $parent_id = 0, $n = 0) { $html = ''; foreach ($categories as $category) { if ($parent_id == $category['parent_id'] && $category['status'] == 1) { $html .= ''; $html .= populate_categories($categories, $selected, $category['id'], $n+1); } } return $html; } // Send order details email function function send_order_details_email($email, $products, $first_name, $last_name, $address_street, $address_city, $address_state, $address_zip, $address_country, $subtotal, $discounttotal,$shippingtotal,$taxtotal,$total, $order_id) { include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; // Send payment notification to webmaster $address_name = htmlspecialchars($first_name ?? '', ENT_QUOTES).' '.htmlspecialchars($last_name ?? '', ENT_QUOTES); if (email_notifications) { $subject = $subject_order_notification; $headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n"; ob_start(); include './custom/email/order-notification-template.php'; $order_notification_template = ob_get_clean(); send_mail_by_PHPMailer(email, $subject, $order_notification_template, '', ''); } if (!mail_enabled) { return; } $subject = $subject_new_order; //$headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . mail_from . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n"; ob_start(); include './custom/email/order-details-template.php'; $order_details_template = ob_get_clean(); send_mail_by_PHPMailer($email, $subject, $order_details_template, '', ''); } //Send email to administrator for out of stock notification // only for registered users function send_product_notification_email($email,$product_details){ include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; $subject = $subject_out_of_stock.' - '.$product_details; //$headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n"; $message = $product_details.' are out of stock. Please notify '.$email.' when available'; //mail(email, $subject, $message, $headers); send_mail_by_PHPMailer(email, $subject, $message, '', ''); } // Template admin header function template_admin_header($title, $selected = 'orders', $selected_child = 'view') { $base_url = 'https://'.$_SERVER['SERVER_NAME'].'/'; $site_name = site_name; $icon_image = icon_image; $admin_links = ' Settings
Countries Settings Language
Email Templates '; // DO NOT INDENT THE BELOW CODE echo << $title
EOT; } // Template admin footer function template_admin_footer($js_script = '') { $js_script = $js_script ? '' : ''; // DO NOT INDENT THE BELOW CODE echo << {$js_script} EOT; } // Determine URL function function url($url) { if (rewrite_url) { $url = preg_replace('/\&(.*?)\=/', '/', str_replace(['index.php?page=', 'index.php'], '', $url)); } return base_url . $url; } // Routeing function function routes($urls) { foreach ($urls as $url => $file_path) { $url = '/' . ltrim($url, '/'); $prefix = dirname($_SERVER['PHP_SELF']); $uri = $_SERVER['REQUEST_URI']; if (substr($uri, 0, strlen($prefix)) == $prefix) { $uri = substr($uri, strlen($prefix)); } $uri = '/' . ltrim($uri, '/'); $path = explode('/', parse_url($uri)['path']); $routes = explode('/', $url); $values = []; foreach ($path as $pk => $pv) { if (isset($routes[$pk]) && preg_match('/{(.*?)}/', $routes[$pk])) { $var = str_replace(['{','}'], '', $routes[$pk]); $routes[$pk] = preg_replace('/{(.*?)}/', $pv, $routes[$pk]); $values[$var] = $pv; } } if ($routes === $path && rewrite_url) { foreach ($values as $k => $v) { $_GET[$k] = $v; } return file_exists($file_path) ? $file_path : 'home.php'; } } if (rewrite_url) { header('Location: ' . url('index.php')); exit; } return null; } // Format bytes to human-readable format function format_bytes($bytes) { $i = floor(log($bytes, 1024)); return round($bytes / pow(1024, $i), [0,0,2,2,3][$i]).['B','KB','MB','GB','TB'][$i]; } function getAccessoiries($clientsecret, $categoryID){ include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; //GET CATALOG DATA $additional_products = ioAPIv2('/v2/catalog/category='.$categoryID,'',$clientsecret); $additional_products = json_decode($additional_products,true); $output ='

'.($h2_cart_suggestions ?? 'Suggestions').'

'; foreach ($additional_products as $additional_product){ if (!empty($additional_product['full_path'])){ $url_contents = 'index.php?page=product&id='; $url_contents .= $additional_product['url_slug'] ? $additional_product['url_slug'] : $additional_product['rowID']; $additional_product_url = url($url_contents); $output .=' '; } } $output .='
'; return $output; } function getSamples($clientsecret, $categoryID){ include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; //GET CATALOG DATA $additional_products = ioAPIv2('/v2/catalog/category='.$categoryID,'',$clientsecret); $additional_products = json_decode($additional_products,true); // Generate unique ID for this samples carousel $samples_id = 'samples_' . $categoryID . '_' . time() . '_' . rand(1000, 9999); $output ='

'.($h2_cart_samples ?? 'Samples').'

'; foreach ($additional_products as $additional_product){ if (!empty($additional_product['full_path'])){ //Pricing override for samples if (sample_pricing_override){ $additional_product['price'] = sample_pricing_override_price; // Price override for free sample! Remove for standard price } $url_contents = 'index.php?page=product&id='; $url_contents .= $additional_product['url_slug'] ? $additional_product['url_slug'] : $additional_product['rowID']; $additional_product_url = url($url_contents); $output .=' '; } } $output .='
'; return $output; } function createGiftCart($pdo, $orderID){ $giftcard_ID = giftcard_id; //Check if Giftcard is ordered $stmt = $pdo->prepare('SELECT t.payer_email as email, ti.id as id, ti.txn_id as txn, ti.item_price as item_price, ti.item_quantity as item_quantity FROM transactions t INNER JOIN transactions_items ti ON t.id = ti.txn_id INNER JOIN products_categories p ON ti.item_id = p.product_id WHERE p.category_id = ? AND t.txn_id = ?'); $stmt->execute([$giftcard_ID,$orderID]); $giftcards = $stmt->fetchAll(PDO::FETCH_ASSOC); if ($giftcards) { foreach ($giftcards as $giftcard) { //For each quantity $x = 0; while ($x < $giftcard['item_quantity']){ //Generate discount code = TXN/ID/X $discount_code = $giftcard['txn'].'#'.$giftcard['id'].'#'.$x; $value = $giftcard['item_price']; // Get the current date $start_date = date("Y-m-d H:i:s"); $end_date = date("Y-m-d H:i:s", strtotime("+5 years"));; //Check if Giftcard already exists $stmt = $pdo->prepare('SELECT * from discounts WHERE discount_code = ?'); $stmt->execute([$discount_code]); $discount_exist = $stmt->fetchAll(PDO::FETCH_ASSOC); if (empty($discount_exist) || $discount_exist == '') { //Insert Giftcard //SQL Insert $stmt = $pdo->prepare('INSERT INTO discounts (discount_code,discount_type,discount_value,start_date,end_date) VALUES (?,?,?,?,?)'); $stmt->execute([$discount_code, 'Fixed', $value, $start_date, $end_date]); } $x++; } } } } function useGiftCart($pdo, $giftcard){ $discount_code = $giftcard; // Get the current date $end_date = date("Y-m-d H:i:s"); //Check if Giftcard already exists $stmt = $pdo->prepare('SELECT * from discounts WHERE discount_code = ?'); $stmt->execute([$discount_code]); $discount_exist = $stmt->fetchAll(PDO::FETCH_ASSOC); //Dump parameters //$stmt->debugDumpParams(); if (!empty($discount_exist) || $discount_exist != '') { //Update Giftcard end data $stmt = $pdo->prepare('UPDATE discounts SET end_date = ? WHERE discount_code = ?'); $stmt->execute([$end_date,$discount_code]); } } function removeGiftCart($pdo, $orderID){ $discount_code = $orderID.'#%#%'; //Check if Giftcard already exists $stmt = $pdo->prepare('SELECT * from discounts WHERE discount_code like ?'); $stmt->execute([$discount_code]); $discount_exist = $stmt->fetchAll(PDO::FETCH_ASSOC); if (!empty($discount_exist) || $discount_exist != '') { //Remove all Giftcards related to order $stmt = $pdo->prepare('DELETE FROM discounts WHERE discount_code like ?'); $stmt->execute([$discount_code]); } } function generateInvoice($invoice_cust,$orderID,$user_language){ //Variables $invoice_customer_email = htmlspecialchars($invoice_cust['customer']['email'] ?? '', ENT_QUOTES); //Generate invoice ob_start(); include dirname(__FILE__).'/custom/email/order-invoice-template.php'; $order_invoice_template = ob_get_clean(); return array($order_invoice_template,$invoice_customer_email,$orderID); } function freeShipment($price, $type){ include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; //Free delivery indicator $delivery_status = ($price >= free_shipment_price) ? $free_delivery : $non_free_delivery.currency_code.free_shipment_price.',-'; $style = ($delivery_status == $free_delivery) ? 'style="color:green;font-weight: bold;"' : 'style="color:gray;font-weight: lighter;"'; $shipment = ' <'.$type.' class="delivery">

'.$delivery_status.'

'; return $shipment; } function consent() { include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; $age_consent = ' '; return $age_consent; } function banner() { include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; $banner = ' '; return $banner; } function maintenanceMode() { include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; $maintenanceMode = ' '; return $maintenanceMode; } //++++++++++++++++++++++++++++++++++++++++ //HomePage Products //++++++++++++++++++++++++++++++++++++++++ function getPictureID($pdo,$id,$config){ $stmt = $pdo->prepare('SELECT * FROM products_media where product_id = :product_id ORDER BY position ASC'); $stmt->bindValue(':product_id', $id, PDO::PARAM_INT); $stmt->execute(); $product_media = $stmt->fetchAll(PDO::FETCH_ASSOC); //Search for option_id $option_profile = json_decode($config,true) ?? ''; if (!empty($option_profile) && $option_profile !=''){ foreach ($option_profile as $option){ if ($option['IMG_large_id'] == $product_media[0]['media_id']){ return $option['option_id']; } } } } //++++++++++++++++++++++++++++++++++++++++ //HomePage Products //++++++++++++++++++++++++++++++++++++++++ function sortProducts(array $products, string $field, string $direction = 'asc'): array { if ($field === 'random') { shuffle($products); return $products; } usort($products, function($a, $b) use ($field, $direction) { $result = $a[$field] <=> $b[$field]; return $direction === 'desc' ? -$result : $result; }); return $products; } function highlightedProducts($categoryID, $range, $subtitle, $catalog, $categories){ include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; //GET CATALOG DATA FROM CACHE // Build product IDs that belong to this category $product_ids_in_category = []; foreach ($categories as $cat) { if ($cat['rowID'] == $categoryID && isset($cat['product_id'])) { $product_ids_in_category[] = $cat['product_id']; } } // Filter products by category $products = array_filter($catalog, function($product) use ($product_ids_in_category) { return in_array($product['rowID'], $product_ids_in_category); }); //RANDOM SORT $products = sortProducts($products, 'random'); // Generate unique ID for this carousel $carousel_id = 'carousel_' . $categoryID . '_' . time() . '_' . rand(1000, 9999); $section = '

'.(!empty($range) ? $range : 'Featured Timepieces').'

'.(!empty($subtitle) ? $subtitle: 'Explore our most popular and exquisite watch collections.').'

'; foreach ($products as $product){ $product_price = isset($product['price']) && $product['price'] > 0 ? floatval($product['price']) : 0.00; $section .= ' '; } $section .= '
'; return $section ; } function highlightedProducts2($categoryID, $range, $subtitle, $catalog, $categories){ include './custom/translations/translations_'.strtoupper($_SESSION['country_code']).'.php'; //GET CATALOG DATA FROM CACHE // Build product IDs that belong to this category $product_ids_in_category = []; foreach ($categories as $cat) { if ($cat['rowID'] == $categoryID && isset($cat['product_id'])) { $product_ids_in_category[] = $cat['product_id']; } } // Filter products by category $products = array_filter($catalog, function($product) use ($product_ids_in_category) { return in_array($product['rowID'], $product_ids_in_category); }); //RANDOM SORT $products = sortProducts($products, 'random'); // Generate unique ID for this carousel $carousel_id = 'carousel_' . $categoryID . '_' . time() . '_' . rand(1000, 9999); $section = '

'.(!empty($range) ? $range : 'Featured Timepieces').'

'.(!empty($subtitle) ? $subtitle: 'Explore our most popular and exquisite watch collections.').'

'; foreach ($products as $product){ $product_price = isset($product['price']) && $product['price'] > 0 ? floatval($product['price']) : 0.00; $section .= ' '; } $section .= '
'; return $section ; } //--------------------------- //debuglog //--------------------------- function debuglog($error){ $test = $error.PHP_EOL; $filelocation = './log/log_'.date('m').'.txt'; error_log($test, 3, $filelocation); } //------------------------------------------ // Get Cached Data from File (24-hour refresh) //------------------------------------------ function getCachedData($api_endpoint, $cache_filename, $token){ $cache_file = './cache/' . $cache_filename; $cache_age_limit = 24 * 60 * 60; // 24 hours in seconds // Check if cache file exists and is fresh (less than 24 hours old) if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_age_limit) { // Return cached data from JSON file $json_data = file_get_contents($cache_file); return json_decode($json_data, true); } // Cache is stale or doesn't exist - attempt to refresh try { $response = ioAPIv2($api_endpoint, '', $token); $data = json_decode($response, true); if (!empty($data) && is_array($data)) { // Successfully fetched new data - write to cache file as JSON $cache_content = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); // Ensure cache directory exists if (!is_dir('./cache')) { mkdir('./cache', 0755, true); } // Attempt to write cache file if (@file_put_contents($cache_file, $cache_content, LOCK_EX) === false) { // Write failed - log error and fall back to existing cache debuglog('Cache write failed for ' . $cache_filename . ' - using existing cache'); if (file_exists($cache_file)) { $json_data = file_get_contents($cache_file); return json_decode($json_data, true); } // No existing cache - return fresh data anyway return $data; } return $data; } else { // API call failed - log error and fall back to existing cache debuglog('API call failed for ' . $api_endpoint . ' - using existing cache'); if (file_exists($cache_file)) { $json_data = file_get_contents($cache_file); return json_decode($json_data, true); } // No existing cache and API failed - return empty array return []; } } catch (Exception $e) { // Exception occurred - log and fall back to existing cache debuglog('Exception in getCachedData for ' . $cache_filename . ': ' . $e->getMessage()); if (file_exists($cache_file)) { $json_data = file_get_contents($cache_file); return json_decode($json_data, true); } return []; } } //------------------------------------------ // Retrieve all $_GET from URL //------------------------------------------ function urlGETdetails($input){ //GET Details from URL if(isset($input) && !empty($input)){ $GET_VALUES = ''; foreach ($input as $KEY => $VALUE){ $GET_VALUES .= $KEY.'='.$VALUE; $GET_VALUES .= '&'; } return $GET_VALUES = rtrim($GET_VALUES, "&"); } else { return $GET_VALUES = ''; } } //------------------------------------------ // API TO API version 2 //------------------------------------------ function ioAPIv2($api_call, $data, $token){ $url = api_url.$api_call; $curl = curl_init($url); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //SEND BEARER CODE WHEN TOKEN PROVIDED if ($token != ''){ $headers = array( "Authorization: Bearer $token", "Content-Type: application/json", ); } else { $headers = array( "Content-Type: application/json", ); } curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); //IF DATA PROVIDED CONSIDER POST if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } $resp = curl_exec($curl); $http_status = curl_getinfo($curl) ?? '200'; curl_close($curl); //Check If errorcode is returned if($http_status['http_code'] == '403' || $http_status['http_code'] == '400') {$resp = json_encode('NOK');} if (debug){ $message = date('Y-m-d H:i:s').';'.$api_call; debuglog($message); } //Response return $resp; } ?>