<?php
require_once '../../../resources/base_path_include.php';

require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . 'lib/export/pdf/transaction_template/template_1/header.php';
require_once $base_path . "vendor/autoload.php";
require_once $base_path_to_resources . "lib/currency_functions.php";

//valdation file
require_once $base_path . 'modules/accounting/stock_management/functions/stock_function.php';
require_once $base_path . 'modules/accounting/stock_management/inventory_regions/region_functions.php';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
require_once $base_path . 'modules/accounting/reports/valuation_methods/closing_stock_summary/fifo_summary_function.php';
require_once $base_path . 'modules/accounting/functions/basic_balance_function.php';

//stock table
require_once $base_path . 'modules/accounting/transaction_management/export/manage_transactions/pdf/sales/stocks_pdf.php';

require_once $base_path_to_resources . 'lib/bucket_functions/bucket_functions.php';

require_once $base_path_to_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

use \Spipu\Html2Pdf\Html2Pdf;
use \Spipu\Html2Pdf\Exception\Html2PdfException;
use \Spipu\Html2Pdf\Exception\ExceptionFormatter;

$book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
$currencySystem = $book_info['book_basic_info']['currency_format'];
$number_of_decimal_places = $book_info['book_basic_info']['number_of_decimal_places'];
$base_currency_symbol = $book_info['book_basic_info']['base_currency_symbol'];
$sql = "SELECT * FROM act_book_settings WHERE workspace_id = ? AND company_id = ? AND branch_id = ? AND book_id = ?";
$stmt = $specific_db_conn->prepare($sql);
$stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id));
$result = $stmt->fetchAll();

if (count($result) == 1) {

    $report_print_company_name = $result[0]['report_print_company_name'];
    $report_print_branch_name = $result[0]['report_print_branch_name'];
    $report_print_book_name = $result[0]['report_print_book_name'];
    $logo = $result[0]['logo'];
    $print_bank_details_1 = $result[0]['print_bank_details_1'];
    $print_bank_details_2 = $result[0]['print_bank_details_2'];
    $print_logo_bool = $result[0]['print_logo_bool'];
    if ($print_logo_bool == 1) {
    if ($result[0]['logo'] !=  null) {
            $keyName = $logo;
            
            $file = displayFileFromS3($GLOBALS['s3_finware_bucket'], $GLOBALS['finware_bucketName'], $keyName);
            
        }
    } else {

        $file =  null;
    }
    if ($report_print_company_name == 1) {
        $company_name = $book_info['book_basic_info']['company_name'];
        $company_address = $book_info['book_basic_info']['company_address'];
    } else {

        $company_name =  null;
        $company_address =  null;
    }

    if ($report_print_branch_name == 1) {
        $branch_name = $book_info['book_basic_info']['branch_name'];
          $email = $book_info['book_basic_info']['email'];
          $contact_number = $book_info['book_basic_info']['contact_number'];
          $branch_gst = $book_info['book_basic_info']['branch_gst'];
          $branch_address = $book_info['book_basic_info']['branch_address'];
           $adl_email = $book_info['book_basic_info']['adl_email'];
        $adl_contact_number = $book_info['book_basic_info']['adl_contact_number'];
        $website = $book_info['book_basic_info']['website'];
        
    } else {

        $branch_name =  null;
        $email =  null;
        $contact_number =  null;
        $branch_gst =  null;
        $branch_address=  null;
         $adl_email =  null;
        $adl_contact_number =  null;
        $website=  null;
        
    }

    if ($report_print_book_name == 1) {
        $book_name = $book_info['book_basic_info']['book_name'];
        $book_opening_date = $book_info['book_basic_info']['book_opening_date'];
        $book_closing_date = $book_info['book_basic_info']['book_closing_date'];
    } else {

        $book_name =  null;
        $book_opening_date =  null;
        $book_closing_date =  null;
    }

    if ($print_bank_details_1 == 1) {
        if ($result[0]['bank_details_1'] !=  null) {
            $bank_details_1 = $result[0]['bank_details_1'];
            $unserializedbank1 = unserialize($bank_details_1);
            $data = json_decode($unserializedbank1, true);
           
            $bank_name= $data['bank_name'];
            $account_number=$data['account_number'];
             $ifsc_code=$data['ifsc_code'];
            
            // print_r($unserializedbank1);
        } else {
            $bank_details_1 =  null;
            
        }
    }else{
        
         $bank_name=null;
            $account_number=null;
             $ifsc_code=null;
    }

    if ($print_bank_details_2 == 1) {
        if ($result[0]['bank_details_2'] !=  null) {
            $bank_details_2 = $result[0]['bank_details_2'];
            $unserializedbank2 = unserialize($bank_details_2);
            $data = json_decode($unserializedbank2, true);
             $bank_name=$data['bank_name'];
            $account_number=$data['account_number'];
             $ifsc_code=$data['ifsc_code'];
             
        } else {
            $bank_details_2 =  null;
             
        }
    }else{
        
         $bank_name=null;
            $account_number=null;
             $ifsc_code=null;
    }
    if($result[0]['terms_conditions'] !=  null){
        
        $terms_conditions = $result[0]['terms_conditions'];
    }else{
           
        $terms_conditions =  null;
    }
} else {
    errorreturn('Branch or company not found.');
}

$result = ([
    'transaction_info' => [
        'transactiondata' => $transactiondata,
        'transactionrecord' => $transactionrows,
        'stock_items' => $stocktransaction_rows,
        'stock_ledger_entries' => $ledgerrecord_rows
    ]
]);
$data = $result['transaction_info'];
$transaction_data = $data['transactiondata'];
$transaction_record = $data['transactionrecord'];
if ($transaction_data['reference_number'] != null) {

    $transaction_number = $transaction_data['reference_number'];
} else {

    $transaction_number =  null;
}
$stocks = $data['stock_items'];
$ledgerrecord = $data['stock_ledger_entries'];
foreach ($transaction_record as $transactionrows) {
    if ($transactionrows['balancetype'] == 'dr') {
        $ledger_name = $transactionrows['ledger_name'];
    }
}
if($transaction_data['dispatch_info'] != null){
    $doc_no = $transaction_data['dispatch_info']['doc_no'];
    $carrier_name = $transaction_data['dispatch_info']['carrier_name'];
    $bill_of_lading =  $transaction_data['dispatch_info']['bill_of_lading'];
    $dispatch_date =  date('d-m-Y', strtotime($transaction_data['dispatch_info']['dispatch_date']));
    $delivery_note = $transaction_data['dispatch_info']['delivery_note'];
    $motor = $transaction_data['dispatch_info']['motor'];
    $destination = $transaction_data['dispatch_info']['destination'];
}else{
     $doc_no = null;
    $carrier_name =  null;
    $bill_of_lading =  null;
    $dispatch_date =  null;
    $delivery_note = null;
    $motor =  null;
    $destination = null;
}

if($transaction_data['billing_address'] !=  null){
    
   $label = $transaction_data['billing_address']['label'];
  $billing_address_1 =  $transaction_data['billing_address']['address_ln_1'];
  $billing_address_2 =  $transaction_data['billing_address']['address_ln_2'];
  $billing_ledger_gst =  $transaction_data['billing_address']['ledger_gst'];
  $billing_state =   $transaction_data['billing_address']['state']['label'];
  $billing_country =  $transaction_data['billing_address']['country']['label'];
  $billing_mobile =  $transaction_data['billing_address']['mobile'];
  $billing_email =  $transaction_data['billing_address']['email'];
}else{
    $label =  null;
    $billing_address_1 =  null;
    $billing_address_2 =  null;
    $billing_ledger_gst =  null;
    $billing_state =  null;
    $billing_country = null;
    $billing_mobile=  null;
    $billing_email =  null;
}

if($transaction_data['shipping_address'] !=  null){
    
   $label = $transaction_data['shipping_address']['label'];
  $shipping_address_1 =  $transaction_data['shipping_address']['address_ln_1'];
  $shipping_address_2 =  $transaction_data['shipping_address']['address_ln_2'];
  $shipping_ledger_gst =  $transaction_data['shipping_address']['ledger_gst'];
  $shipping_state =   $transaction_data['shipping_address']['state']['label'];
  $shipping_country =  $transaction_data['shipping_address']['country']['label'];
  $shipping_mobile =  $transaction_data['shipping_address']['mobile'];
  $shipping_email =  $transaction_data['shipping_address']['email'];
}else{
    $label =  null;
    $shipping_address_1 =  null;
    $shipping_address_2 =  null;
    $shipping_ledger_gst =  null;
    $shipping_state =  null;
    $shipping_country = null;
    $shipping_mobile=  null;
   $shipping_email =  null;
}
$billing_info = '';
if (!empty($billing_mobile) && !empty($billing_email)) {
    $billing_info = $billing_mobile . '&nbsp;&nbsp;|&nbsp;&nbsp;' . $billing_email;
} elseif (!empty($billing_mobile)) {
    $billing_info = $billing_mobile;
} elseif (!empty($billing_email)) {
    $billing_info = $billing_email;
}

$shipping_info = '';
if (!empty($shipping_mobile) && !empty($shipping_email)) {
    $shipping_info = $shipping_mobile . '&nbsp;&nbsp;|&nbsp;&nbsp;' . $shipping_email;
} elseif (!empty($shipping_mobile)) {
    $shipping_info = $shipping_mobile;
} elseif (!empty($shipping_email)) {
    $shipping_info = $shipping_email;
}

try {
    // ob_start();
    $html = ob_get_clean();
    $html2pdf = new Html2Pdf('P', 'A4', 'fr');
    // $html2pdf = new Html2Pdf('P', 'A4', 'en', true, 'UTF-8', array(5, 5, 5, 5)); // Change the margin values as needed

    $html2pdf->pdf->SetDisplayMode('fullpage');


    //add html design
    $table = '
    <style>
    /* Define the font family */
    body {
        font-family: Calibri, sans-serif; /* Use Calibri font */
        //  margin: 20px;
    }
</style>
    <div style="border: 1px solid #000;">
    <table border="0" style="width: 100%;">
        <tr>
            <td style="border-right: 1px solid #000; width: 50%;">
                <table border="0" style="width: 100%;">
                    <tr><td>Invoice No:</td><td>' . $transaction_data['transaction_unique_id'] . '</td></tr>
                    <tr><td>Date:</td><td>' . date('d-m-Y', strtotime($transaction_data['date'])) . '</td></tr>
                    <tr><td>Reference No:</td><td> ' . $transaction_number . '</td></tr>
                    <tr><td>Document No.:</td><td>' . $doc_no . '</td></tr>
                    <tr><td>Transport: </td><td>' . $delivery_note . '</td></tr>
                    <tr><td>Carrier Name:</td><td>' . $carrier_name . '</td></tr>
                </table>
            </td>
            <td style="width: 49%;">
                <table border="0" style="width: 100%;">
                    <tr><td>Bill of lading: </td><td> ' . $bill_of_lading . '</td></tr>
                     <tr><td>Station:</td><td> ' . $destination . '</td></tr>
                      <tr><td>Dispatch Date: </td><td> ' . $dispatch_date . '</td></tr>
                    <tr><td>Motor No:</td><td> ' . $motor . '</td></tr>
                    <tr><td>E-Way Bill No.: </td><td>' . $transaction_data['e_way_bill'] . '</td></tr>
                </table>
            </td>
        </tr>
    </table>
</div>

<div style="border: 1px solid #000;">
    <table border="0" style="width: 100%;">
        <tr>
            <td style="border-right: 1px solid #000; width: 50%;">
                <p style="font-style: italic;padding-left: 3px;margin:0px;padding:0px;">Billed to:</p>';
        
                if ($ledger_name === $label) {
                    $table .= ' <p style="text-align: left;margin:0px;padding-left: 3px">' . $ledger_name. '</p>';
                } else {
                    $table .= '<p style="text-align: left;margin:0px;padding-left: 3px">' .$ledger_name. '</p>';
                    $table .= '<p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' . $label. '</p>';
                }
                $table .= '<p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' . $billing_address_1 .'</p>
                <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' . $billing_address_2 . '</p>
		    
			    <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' .$billing_state . '&nbsp;' . $billing_country . '</p>
                <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' .$billing_info . '</p>
			   

				<p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">GSTIN  : '.$billing_ledger_gst.'</p>
            </td>
            <td style="width: 49%;">
                <div style="margin-bottom: 5px;">
                     <p style="font-style: italic;;padding-left: 3px;margin:0px;padding:0px;">Shipped to:</p>';
                     if ($ledger_name === $label) {
                        $table .= ' <p style="text-align: left;margin:0px;padding-left: 3px">' . $ledger_name. '</p>';
                    } else {
                        $table .= '<p style="text-align: left;margin:0px;padding-left: 3px">' .$ledger_name. '</p>';
                        $table .= '<p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' . $label. '</p>';
                    }
                $table .= '<p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' . $shipping_address_1.  '</p>
                <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' . $shipping_address_2 . '</p>
                <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">' .$shipping_state . '&nbsp;' . $shipping_country . '</p>
                <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">'.$shipping_info.'</p>
				 <p style="text-align: left;margin:0px;padding:0px;padding-left: 3px">GSTIN : '.$shipping_ledger_gst.'</p>

                </div>
            </td>
           
        </tr>
    </table>
</div>';

$table =  createStockTable($stocks,$ledgerrecord,$table,$currencySystem,$number_of_decimal_places);

if($bank_name != null and $account_number !=  null and $ifsc_code != null){
$table .= '<div style="border: 1px solid #000;padding:10px">';
 $table .= '<table border="0" style="width: 100%;" cellspacing="0" cellpadding="0">';
                $table .= "<tr><td>Bank Details:&nbsp;&nbsp;&nbsp;</td><td> $bank_name &nbsp;&nbsp;&nbsp;</td>";
                $table .= "<td>A/C No.:&nbsp;&nbsp;&nbsp;</td><td> $account_number &nbsp;&nbsp;&nbsp;</td>";
                  $table .= "<td>IFSC:&nbsp;&nbsp;&nbsp;</td><td> $ifsc_code &nbsp;&nbsp;&nbsp;</td></tr>";
    $table .= ' </table>';
$table .= '</div>';
}
$table .= '<div style="border: 1px solid #000;  ">
    <table border="0" style="width: 100%;">
        <tr>
            <td style="border-right: 1px solid #000; width: 50%;font-size: 12px">
                <h5><strong>Terms & Conditions</strong></h5>
                  <p>'.nl2br($terms_conditions).'</p>
		
            </td>
            <td style="width: 49%;">
                <div>
                   <p style= "text-align:right"><strong> For '.ucwords($company_name).'</strong></p>
                   <h5 style= "text-align:right"><strong>Authorised Signatory</strong></h5>
                   
                   
                </div>
            </td>
        </tr>
    </table>
    </div>';
    
    $book_template = createPdfHeaderTemplate($specific_db_conn, $book_name, $company_name, $branch_name, $book_opening_date, $book_closing_date, $report_print_company_name, $report_print_branch_name, $report_print_book_name, $file, $function_code,$company_address,$branch_gst,$email,$contact_number,$branch_address,$adl_email,$adl_contact_number,$website);

    $html = '
            <div>
        ' . $book_template . '
         ' . $table . '
         </div>
        ';
    //  print_R($book_template);die();

    $html2pdf->WriteHTML($html); // in $content you put your content to have in pdf
    $html2pdf->Output('Transaction Report - Rejoice Finware.pdf');
} catch (Html2PdfException $e) {
    $html2pdf->clean();
    $formatter = new ExceptionFormatter($e);
    echo $formatter->getHtmlMessage();
}



