<?php
include '../../../class/mysql.php';
include '../../../class/site.php';
require_once '../../../functions.php';
$owner = addslashes($_GET['order']);
$order = $mysql->get_array($mysql->query("*", "fs_shop_orderdata", "owner = '$owner' AND temp = 'n' LIMIT 1"));
$tax = $site->shop_settings('home_country');
//PDF invoice
$taxRate = $site->shop_settings('tax_rate');
$invoiceTitle = ($taxRate['tax_rate'] > 0) ? 'Tax Invoice' : 'Invoice';
$noTaxMsg = ($taxRate['tax_rate'] > 0 && $order['country'] == $tax['home_country']) ? 'Total price includes GST<br>' : 'No GST has been charged<br>';
$logo = '';
//has logo
$settings = settings('logo_width');
$settings['logo_width'] = ($settings['logo_width'] > 200 || $settings['logo_width'] == '') ? 200 : $settings['logo_width'];
$logowidth = ' width="'.$settings['logo_width'].'"';
if (file_exists('../../../images/logo/logo.jpg'))
{
    $logo = '<img src="'.httpOrHttps().'://'.$_SERVER['HTTP_HOST'].'/images/logo/logo.jpg"'.$logowidth.' />';
}
if (file_exists('../../../images/logo/logo.jpeg'))
{
    $logo = '<img src="'.httpOrHttps().'://'.$_SERVER['HTTP_HOST'].'/images/logo/logo.jpeg"'.$logowidth.' />';
}
if (file_exists('../../../images/logo/logo.gif'))
{
    $logo = '<img src="'.httpOrHttps().'://'.$_SERVER['HTTP_HOST'].'/images/logo/logo.gif"'.$logowidth.' />';
}
$shopSetting = $site->shop_settings('show_logo_on_invoice');
if ($logo != '' && $shopSetting['show_logo_on_invoice'] == 'y')
{
    $buffer = '<h1>'.$invoiceTitle.'</h1><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td align="left" valign="top">{my_company_name}<br>{shop_address}</td><td align="center" valign="middle">'.$logo.'</td></tr></table>';
}
else //no logo
{
    $buffer = '<h1>'.$invoiceTitle.'</h1><b>{my_company_name}</b><br>{shop_address}';
}
$buffer .= '<hr width="100%" size="1" noshade="noshade" align="center">
<table width="100%" border="0" cellspacing="0" cellpadding="5"><tr><td>';
$val = $mysql->get_array($mysql->query("value", "fs_shop_settings", "`name` = 'hide_delivery_section' LIMIT 1"));
if ($val['value'] == 'n')
{
    $buffer .= '<strong>Ship To</strong>';
}
$buffer .= '</td>
<td><strong>Buyer</strong><br></td>
<td valign="top"><strong>Order Information</strong></td>
</tr>
<tr><td>';
if ($val['value'] == 'n')
{
    $buffer .= '{company_name}<br>{dev_firstname} {dev_lastname}<br>{address_line1}{address_line2}<br>{town}, {state}, {postcode}<br>{country}{phoneNumber}';
}
$buffer .= '</td>
<td valign="top">{first_name} {last_name}<br>{email_address}</td><td valign="top">Order #: {owner}<br>Date: {date}<br>Paid via {paymentMethod}{shiping_type}<br>Heard about us: {where_heard}</td>
</tr>
</table>';
//show custom field value
if (!empty($order['cardmsg']))
{
    $m = $site->shop_settings('custom_msg_field_lbl');
    $buffer .= '<p>'.$m['custom_msg_field_lbl'].': '.$order['cardmsg'].'</p>';
}
else
{
    $buffer .= '<br>';
}
$buffer .= '<table width="100%" border="1" cellpadding="0" cellspacing="0"><tr><td align="center"><b>Description</b></td><td align="center" valign="middle"><b>QTY</b></td><td align="center" valign="middle"><b>Unit</b></td><td align="center" valign="middle"><b>Total</b></td></tr><!--row--><tr><td width="60%">{item}<br>{option}</td><td align="center" valign="middle">{qty}</td><td align="center" valign="middle">{currency_symbol}{each} {paypal_currency}</td><td align="center" valign="middle">{currency_symbol}{price} {paypal_currency}</td></tr><!--row--></table><br>

<table width="50%" border="1" align="right" cellpadding="1" cellspacing="0">
<tr>
<td align="left" valign="middle"><b>Shipping</b></td>
<td align="left" valign="middle"><b>{currency_symbol}{shipping} {paypal_currency}</b></td>
</tr>

<tr>
<td align="left" valign="middle"><b>Discount</b></td>
<td align="left" valign="middle"><b>{currency_symbol}{discount} {paypal_currency}{discountCode}</b></td>
</tr>

<tr>
<td align="left" valign="middle"><b>Total</b></td>
<td align="left" valign="middle"><b>{currency_symbol}{total} {paypal_currency}</b></td>
</tr>';

if ($taxRate['tax_rate'] > 0)
{
    $word = ($order['country'] == $tax['home_country']) ? 'included' : 'deducted';
    $buffer .= '<tr>
<td align="left" valign="middle"><b>GST '.$word.'</b></td>
<td align="left" valign="middle"><b>{currency_symbol}{sales_gst} {paypal_currency}</b></td>
</tr>';
}
$buffer .= '</table>';
//if bank transfer, add bank account details to the invoice
if ($order['payment_method'] == 'bank')
{
    $bank = $site->shop_settings('bankpaymentmethod_bankname,bankpaymentmethod_accountname,bankpaymentmethod_accountnumber,bankpaymentmethod_bsb');
    $buffer .= '<p align="left">You have selected to pay via bank transfer, our bank account details are listed below:</p>';
    $buffer .= "Bank Name: {$bank['bankpaymentmethod_bankname']}<br>";
    $buffer .= "Account Name: {$bank['bankpaymentmethod_accountname']}<br>";
    $buffer .= "BSB: {$bank['bankpaymentmethod_bsb']}<br>";
    $buffer .= "Account Number: {$bank['bankpaymentmethod_accountnumber']}<br>";
    $buffer .= "Ref: $owner";
}
//end
$buffer .= '<p align="center">'.$noTaxMsg.'Thank you for shopping with us!</p>';
//parse values into the html
$order['address_line2'] = (!empty($order['address_line2'])) ? '<br>'.$order['address_line2'] : '';
$order['shipping'] = number_format($order['shipping'], 2);
$order['shiping_type'] = ($order['shiping_type'] != '') ? '<br>Shipping type: '.$order['shiping_type'] : '';
$order['sales_tax'] = number_format($order['sales_tax'], 2);
$order['company_name'] = (empty($order['company_name'])) ? '' : $order['company_name'];
$order['dev_firstname'] = (empty($order['dev_firstname'])) ? $order['first_name'] : $order['dev_firstname'];
$order['dev_lastname'] = (empty($order['dev_lastname'])) ? $order['last_name'] : $order['dev_lastname'];
foreach ($order as $key => $value)
{
    if (!is_numeric($key))
    {
        $buffer = str_replace('{'.$key.'}', $value, $buffer);
    }
}
$array['date'] = date("d F Y", $order['stamp']);
foreach ($array as $key => $value)
{
    $buffer = str_replace('{'.$key.'}', $value, $buffer);
}
//cart contents
$gst = 0;
$html = explode("<!--row-->", $buffer);
$buffer = $html[0];
$query = $mysql->query("pid,qty,price,item_name,`option`,custom_field_val,extra_info,(price*qty) AS rowTotal", "fs_shop_cart", "owner = '$owner' AND temp = 'n'");
while ($data = $mysql->get_array($query))
{
    $item = $site->productInfo($data['pid']);
    $temp = $html[1];
    $temp = str_replace("{each}", number_format($data['price'], 2), $temp);
    $temp = str_replace("{price}", number_format($data['rowTotal'], 2), $temp);
    $temp = str_replace("{qty}", number_format($data['qty']), $temp);
    $temp = (empty($item['name'])) ? str_replace("{item}", $data['item_name'], $temp) : str_replace("{item}", $item['name'], $temp);
    $option = $data['option'];
    $option .= (!empty($data['custom_field_val'])) ? '<br>'.stripslashes($item['custom_field_lbl'].': '.$data['custom_field_val']) : '';
    $extraInfo = explode('<!--edit-->', $data['extra_info']);
    $option .= (!empty($extraInfo[0])) ? '<br>'.stripslashes($extraInfo[0]) : '';
    $temp = str_replace("{option}", $option, $temp);
    $buffer .= $temp;
    $total += $data['rowTotal'];
}
$buffer .= $html[2];
//discount
$order['discount_value'] = (empty($order['discount_value'])) ? 0 : $order['discount_value'];
$buffer = str_replace('{discount}', number_format($order['discount_value'], 2), $buffer);
$discount_code = ($order['discount_code'] == '') ? '' : ' ('.$order['discount_code'].')';
$buffer = str_replace('{discountCode}', $discount_code, $buffer);
//sales tax
$sales_tax = 0;
if ($taxRate['tax_rate'] > 0)
{
    $t = ($total + $order['shipping'] - $order['discount_value']);
    $sales_tax = number_format($t / ($taxRate['tax_rate'] + 1), 2, '.', '');
    $buffer = str_replace('{sales_gst}', number_format($sales_tax, 2), $buffer);
}
//total
$total = ($order['country'] == $tax['home_country']) ? ($total + $order['shipping'] - $order['discount_value']) : ($total + $order['shipping'] - $sales_tax - $order['discount_value']);
$buffer = str_replace('{total}', number_format($total, 2), $buffer);
//payment method
$payment_method = 'PAYPAL';
if ($order['payment_method'] == 'bank')
{
    $payment_method = 'BANK DEPOSIT / TRANSFER';
}
if ($order['payment_method'] == 'cod')
{
    $payment_method = 'CASH ON DELIVERY';
}
if ($order['payment_method'] == 'pickup')
{
    $payment_method = 'PICK UP FROM STORE';
}
if ($order['payment_method'] == 'phonePay')
{
    $payment_method = 'PAY BY PHONE';
}
$buffer = str_replace('{paymentMethod}', $payment_method, $buffer);
//phone number
$order['phone_number'] = (!empty($order['phone_number'])) ? '<br>PH: '.$order['phone_number'] : '';
$buffer = str_replace('{phoneNumber}', $order['phone_number'], $buffer);
//misc
$settings = $site->shop_settings('shop_address,currency_symbol,paypal_currency');
$settings['shop_address'] = nl2br($settings['shop_address']);
$settings['shop_address'] = str_replace("\n ", "\n", $settings['shop_address']);
$buffer = str_replace('{shop_address}', $settings['shop_address'], $buffer);
$buffer = str_replace('{currency_symbol}', $settings['currency_symbol'], $buffer);
$buffer = str_replace('{paypal_currency}', $settings['paypal_currency'], $buffer);
$n = $mysql->get_array($mysql->query("value", "fs_settings", "name = 'company_name' LIMIT 1"));
$buffer = str_replace('{my_company_name}', $n['value'], $buffer);
$buffer = stripslashes($buffer);
//download PDF
include "pdf/html2fpdf.php";
$pdf = new HTML2FPDF();
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output($owner.'.pdf', "D");
