<?php
/**
 * Manage Quotation Payment
 *
 * PHP version 5.6
 *
 * @category  Quotation_Payment
 * @package   Production_Hub
 * @author    Debashri Bhakat <debashrib@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 */

namespace App\Modules\Quotations\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Quotations\Controllers\QuotationController as QuotationController;
use App\Modules\Quotations\Models\QuotationPayment;
use App\Modules\Quotations\Models\Quotations;
use App\Modules\Quotations\Models\ProductionStatus;
use App\Modules\Quotations\Models\CustomerAdditionalInfo;
use App\Modules\Orders\Controllers\OrdersController;
/**
 * Quotations Controller
 *
 * @category Quotations
 * @package  Production_Hub
 * @author   Debashri Bhakat <debashrib@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */
class QuotationPaymentController extends QuotationController
{
    /**
     * POST: Quotation payment request
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   31 Mar 2019
     * @return json response
     */
    public function createPaymentLink($request, $response)
  {
    $serverStatusCode = OPERATION_OKAY;
    $jsonResponse = [
      'status' => 0,
      'message' => message('Payment', 'error'),
    ];
    $allPostPutVars = $request->getParsedBody();
    $getStoreDetails = get_store_details($request);
    // Save Quotation Status Data
    if (isset($allPostPutVars['data']) && $allPostPutVars['data'] != "") {
      $getAllFormData = json_clean_decode($allPostPutVars['data'], true);
      $quotationInit = new Quotations();
      $quotationId = to_int($getAllFormData['quote_id']);
      //Check for quotation
      $quotation = $quotationInit->select('quote_total', 'quote_id', 'currency_id')->where('xe_id', $quotationId);
      $quotationDetails = $quotation->first()->toArray();

      //Check payment amount should not greater then total amount
      if (!empty($quotationDetails) && ($quotationDetails['quote_total'] >= $getAllFormData['request_payment'])) {
        $updateData = [
          'request_payment' => $getAllFormData['request_payment'],
          'invoice_id' => $quotationDetails['quote_id'],
          'request_date' => date_time(
            'today',
            [],
            'string'
          )
        ];

        if ($quotationInit->where('xe_id', $quotationId)->update($updateData)) {
          //Adding to quote log
          //Get currency from global setting
          $currencyId = $quotationDetails['currency_id'];
          $currencyData = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
          $logData = [
            'quote_id' => $getAllFormData['quote_id'],
            'title' => 'Payment requested',
            'description' => 'Payment request is sent for ' . $currencyData['value'] . $getAllFormData['request_payment'],
            'user_type' => $getAllFormData['user_type'],
            'user_id' => $getAllFormData['user_id'],
            'created_date' => date_time(
              'today',
              [],
              'string'
            )
          ];
          $this->addingQuotationLog($logData);
          $jsonResponse = [
            'status' => 1,
            'message' => message('Payment', 'saved')
          ];
        }
      }
    }
    return response(
      $response,
      ['data' => $jsonResponse, 'status' => $serverStatusCode]
    );
  }

    /**
     * Send payment link to customer
     *
     * @param $mailData  Mail data Array
     * @param $url Payment URL
     *
     * @author debashrib@riaxe.com
     * @date   09 Apr 2019
     * @return json response
     */

    public function sendPaymentlink($mailData, $url)
    {
        $emailBody = 'Payment Link : <a href="'.$url.'" target="_blank">'.$url.'</a>';
        $mailContaint = [
            'from'=>['email'=> $mailData['from_email'],
                'name'=> $mailData['from_name']],
            'recipients'=> ['to'=>['email'=> $mailData['customer_email'],
                'name'=>$mailData['customer_name']],
                'reply_to'=>['email'=> $mailData['from_email'],
                    'name'=> $mailData['from_name']],
            ],
            'attachments'=>[$mailData['invoice_file']],
            'subject'=>'Quotation (#'.$mailData['quote_id'].') Payment Link',
            'body'=> $emailBody,
        ];
        $mailResponse = mail($mailContaint);
        return $mailResponse;
    }

    /**
     * Generate Invoice
     *
     * @param $paymentId  Payment Id 
     * @param $request  Slim's Argument parameters
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   09 Apr 2019
     * @return json response
     */

    public function generateInvoice($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Invoice Download', 'error')
        ];
        $result = false;
        if (!empty($args['id']) && $args['id'] > 0) {
            $quotationId = $args['id'];
            $quotationInit = new Quotations();
            //Check for quotation
            $quotation = $quotationInit
                ->where('xe_id', $quotationId);
            if ($quotation->count() > 0) {
                $quotationData = $quotation->select('quote_id')->first()->toArray();
                $updateData = [
                    'invoice_id' => $quotationData['quote_id']
                ];
                $quotationInit->where('xe_id', $quotationId)->update($updateData);
            }
            $quotationDetails = $this->getQuotationDetails($request, $response, $args, 1);
            $itemsList = $this->getQuoteItems($request, $response, $args, 1);
            if ($dir= $this->createInvoicePdf($request, $response, $quotationId, $quotationDetails, $itemsList)) {
                //Download file in local system
                if (file_download($dir)) {
                    $result = true;
                    $serverStatusCode = OPERATION_OKAY;
                    $jsonResponse = [
                        'status' => 1
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );

    }

    /**
     * Create Quotation pdf
     *
     * @param $quotationId     Quotation Id
     * @param $quotationDetails    Quotation Details
     * @param $itemsList    Quotation Item List
     *
     * @author debashrib@riaxe.com
     * @date   15 Apr 2019
     * @return pdf file path
     */

    private function createInvoicePdf($request, $response, $quotationId, $quotationDetails, $itemsList) 
    {
        if (!empty($quotationId) && $quotationId > 0) { 
          $getStoreDetails = get_store_details($request);
          $languageData = $this->getQuotationDefaultLang($request, $response, 1);
          $toolLang = $languageData['default']['name'];
          $ordersInit = new OrdersController($toolLang);
          $pdfLanguage = $ordersInit->languageContent['quotation-pdf-and-public-link'];
          //Get currency from global setting
          $globalSettingData = $this->readSettingJsonFile($getStoreDetails['store_id']);
          $separator = $globalSettingData['currency']['separator'];
          $currency = $quotationDetails['currency']['code'];//$quotationDetails['currency']['unicode_character'];
          //Get email setting data for sending email
          $emailSettingData = $this->getProductionSetting($request, $response, ['module_id' => 1, 'return_type' => 1]);
          $emailSettingData = $emailSettingData['data'];
          $customerName = ($quotationDetails['customer']['name'] != '') ? $quotationDetails['customer']['name'] : $quotationDetails['customer']['email'];
          $billingAddressArr = $quotationDetails['customer']['billing_address'];
          $billingAddress = $billingAddressArr['address_1'] != '' ? $billingAddressArr['address_1'].', '. $billingAddressArr['address_2'].'<br/>'.$billingAddressArr['country'].', '.$billingAddressArr['state'].',<br/>'.$billingAddressArr['city'].'-'.$billingAddressArr['postcode'] : '';

          $finalShippingArr = $quotationDetails['customer']['shipping_address'][0];
          $shippingAddress = $finalShippingArr['address_1'] != '' ? $finalShippingArr['address_1'].', '. $finalShippingArr['address_2'].'<br/>'.$finalShippingArr['country'].', '.$finalShippingArr['state'].',<br/>'.$finalShippingArr['city'].'-'.$finalShippingArr['postcode'] : '';
          $paid_image = path('read', 'common').'paid.png';
          /** get font for default language */
          $languageFont =  $this->getDefaultLanguageFont($getStoreDetails['store_id'], "tool", $toolLang);
          if (strtolower($toolLang) == "japanese" || strtolower($toolLang) == "chinese") {
              $fontFamily = "simsun";
              $fontAll = "simsun";
              $fontUrl = "";
          } else {
              $fontFamily = "DejaVuSans";
              $fontAll = "DejaVuSans";
              $fontUrl = "";
          }
          $fontStyle = $languageFont['font_style'];
          $fontWeight = $languageFont['font_weight'];
          $trueType = $languageFont['true_type'];

          $rtlLeftAlign = "right";
          $rtlRightAlign = "left";
          if (strtolower($toolLang) == 'arabic') {
            $rtlLeftAlign = "left";
            $rtlRightAlign = "right";
          }
          $html = '<!doctype html>
          <html lang="en-US">

          <head>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                <style>@media print {
                            body {-webkit-print-color-adjust: exact;}
                        }
                        @font-face {
                          font-family: "'.$fontFamily.'";
                          font-style: '.$fontStyle.';
                          font-weight: '.$fontWeight.';
                          src: url('.$fontUrl.') format("'.$trueType.'");
                        }
                        * {
                          font-family: '.$fontAll.';
                        }
                    </style>
          </head>
          <body style="margin: 0; padding: 0;">
            <table cellpadding="5" style="margin: 0px; padding: 0px; -webkit-box-shadow: 0px 2px 20px 0px rgba(0, 0, 0, 0.06); box-shadow: 0px 2px 20px 0px rgba(0, 0, 0, 0.06); background: #fff; position: relative; box-sizing: border-box; font-family: '.$fontFamily.';">
          
              <table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%;">
                <tr>
                  <td width="50%" style="vertical-align: top;"><br/>
                    <span style="font-size: 24px;" class="title mb-3"><strong>'.$pdfLanguage['invoice'].'</strong></span><br/><br/>
                    <table width="100%" cellspacing="0" cellpadding="0" border="0" style="font-size: 12px;">
                      <tr>
                        <td style="margin: 0 20px 4px 0px;"><strong>'.$pdfLanguage['invoice-no'].'</strong></td>
                        <td style="margin: 0 20px 4px 0px;">
                          : '.$quotationDetails['invoice_id'].'
                        </td>
                      </tr>
                      <tr>
                        <td style="margin: 0 20px 4px 0px;"><strong>'.$pdfLanguage['created-on'].'</strong></td>
                        <td style="margin: 0 20px 4px 0px;">
                          : '.date("dS F, Y", strtotime($quotationDetails['created_at'])).'
                        </td>
                      </tr>
                      <tr>
                        <td style="margin: 0 20px 4px 0px;"><strong>'.$pdfLanguage['shipping-date'].'</strong></td>
                        <td style="margin: 0 20px 4px 0px;">
                          : '.date("dS F, Y", strtotime($quotationDetails['ship_by_date'])).'
                        </td>
                      </tr>
                      <tr>
                        <td style="margin: 0 20px 4px 0px;"><strong>'.$pdfLanguage['delivery-date'].'</strong></td>
                        <td style="margin: 0 20px 4px 0px;">
                          : '.date("dS F, Y", strtotime($quotationDetails['exp_delivery_date'])).'
                        </td>
                      </tr>
                    </table>
                  </td>
                  <td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top; font-size: 12px;">';
                  if ($emailSettingData['company_logo'] != ''){
                    $html .= '<span style="margin: 0 0 0 auto; width: 120px; align:'.$rtlLeftAlign.'">
                      <img alt="logo" src="'.$emailSettingData['company_logo'].'" style="width: auto; height:120px;" />
                    </span><br/>';
                  }
                  $html .= '<span style="font-size: 14px; line-height: 22px;">
                      '.$emailSettingData['address'].',<br/>
                      '.$emailSettingData['country'].','.$emailSettingData['state'].','.$emailSettingData['city'].'-'.$emailSettingData['zip_code'].',<br/>
                      '.$emailSettingData['sender_email'].'<br/>
                      '.$emailSettingData['phone_number'].'
                    </span>
                  </td>
                </tr>
                <tr>
                  <td colspan="2" width="100%">
                    <hr style="margin: 30px 0 0 0;">
                  </td>
                </tr>
              </table>
              <table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%; margin-bottom: 30px;">
                <tr>';
                if (!empty($quotationDetails['customer'])) {
                  $html .= '<td width="50%" style="vertical-align: top; padding-right:20px;"><br/>
                    <span style="font-size: 14px;"><strong>'.$pdfLanguage['quotation-for'].'</strong></span><br/>
                    <span style="margin: 0 0 10px 0; font-size: 12px;">'.$customerName.'<br/>
                      '.$quotationDetails['customer']['email'].'<br/>
                      '.$quotationDetails['customer']['phone'].'
                    </span>
                  </td>';
                }
                  if ($quotationDetails['due_amount'] > 0) {
                  $html .='<td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top;">
                    <span style="font-size: 14px;"><strong>'.$pdfLanguage['balance-due'].'</strong></span><br/>
                    <span style="margin: 7px 0; font-size: 12px;"><span> '.$currency.'</span>'.number_format($quotationDetails['due_amount'], 2, $separator, '').'</span>
                  </td>';
                  } else {
                  $html .= '<td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top;">
                  <span style="font-size: 12px;">'.$pdfLanguage['balance-due'].' (<span> '.$currency.'</span>)</span>
                    <span style="margin: 0 0 0 auto; width: 120px;">
                      <img alt="logo" src="'.$paid_image.'" style="width: auto; height: 120px;" />
                    </span>
                  </td>';
                 }
                  
                $html .='</tr>
              </table>';
              $html .='<table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%; margin-bottom: 30px;">
                <tr>';
                  if ($billingAddress != '') {
                    $html .= '<td width="50%" style="vertical-align: top; line-height: 22px;"><br/>
                      <span style="font-size: 14px;"><strong>'.$pdfLanguage['billing-address'].'</strong></span>
                      <span style="font-size: 12px;"><br/><br/>
                        '.$billingAddress.'
                      </span><br/>
                    </td>';
                  }
                  if ($shippingAddress != '') {
                    $html .= '<td width="50%" align="'.$rtlLeftAlign.'" style="vertical-align: top; line-height: 22px;"><br/>
                      <span style="font-size: 14px;"><strong>'.$pdfLanguage['shipping-address'].'</strong></span>
                      <span style="font-size: 12px;"><br/><br/>
                        '.$shippingAddress.'
                      </span><br/>
                    </td>';
                  }
                $html .='</tr>
              </table>';
          $html .= '<table width="100%" cellpadding="5" cellspacing="0" border="0" style="font-size: 12px; line-height: 20px;">
            <thead>
              <tr>
                <td align="center" bgcolor="#e3e4e6" width="10%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                  '.$pdfLanguage['sno'].'
                </td>
                <td align="center" bgcolor="#e3e4e6" width="20%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                  '.$pdfLanguage['product-name'].'
                </td>
                <td align="center" bgcolor="#e3e4e6" width="20%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                  '.$pdfLanguage['product-details'].'
                </td>
                <td align="center" bgcolor="#e3e4e6" width="10%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                  '.$pdfLanguage['unit-price'].'
                </td>
                <td align="center" bgcolor="#e3e4e6" width="10%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                  '.$pdfLanguage['total-qty'].'
                </td>
                <td align="center" bgcolor="#e3e4e6" width="10%" style="padding: 10px; border: 1px solid #aaa;">
                  <strong>'.$pdfLanguage['design-price'].'</strong>
                </td>
                <td align="center" bgcolor="#e3e4e6" width="20%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">
                  '.$pdfLanguage['total-price'].'
                </td>
              </tr>
            </thead>
            <tbody>';
            $subtotal= 0;
          foreach ($itemsList as $itemKey => $items) {
              $productName = ($items['product_name'] != '') ? $items['product_name'] : 'N/A';
              $slNo = $itemKey+1;
              $backgroundColor = (($itemKey % 2) == 0) ? 'background-color: rgba(0, 0, 0, 0.05);' : '';
              $subtotal = $subtotal + $items['unit_total'];
              if ($items['product_availability']) {
                $html .= '<tr>
                  <td  width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">'.$slNo.'</td>
                  <td  width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">'.$productName.'</td>
                  <td  width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">';
                      if (!empty($items['sticker_data']) && $items['sticker_data']['stickerOption'] == 'sheet' && !empty($items['sticker_data']['sheetInfo'])) {
                        foreach ($items['sticker_data']['sheetInfo'] as $key => $sheetInfo) {
                            $html .= '<span>Sheet - '.$sheetInfo['name'].' : '.$sheetInfo['quantity'].'</span><br/>';
                        }
                      } else {
                        foreach ($items['product_variant'] as $key => $variants) {
                            if (!empty($variants['attribute'])) { 
                                $html .= '<span>(';
                                foreach ($variants['attribute'] as $attribute) {
                                    $html .= $attribute['name'].' / ';
                                }
                                $html .= $variants['quantity'].')</span> <br/>';
                            } else {
                                $html .= 'Simple Product';
                            }
                        }
                    }
                  $html .= '</td>
                  <td width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">';
                      if (!empty($items['sticker_data']) && $items['sticker_data']['stickerOption'] == 'sheet' && !empty($items['sticker_data']['sheetInfo'])) {
                        foreach ($items['sticker_data']['sheetInfo'] as $key => $sheetInfo) {
                            $sheetPriceforSticker = (isset($sheetInfo['updated_price'])) ? $sheetInfo['updated_price'] : $sheetInfo['price'];
                            $html .= '<span> '.$currency.'</span>' . number_format($sheetPriceforSticker, 2, $separator, '') . '<br/>';
                        }
                    } else {
                        foreach ($items['product_variant'] as $key => $variants) {
                           $updatedPrice = (isset($variants['updated_price']) && $variants['updated_price'] > 0) ? $variants['updated_price'] : $variants['unit_price'];
                            $html .= '<span> '.$currency.'</span>'.number_format($updatedPrice, 2, $separator, '').'<br/>';
                        }
                    }
                  $html .= '</td>
                  <td width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">'.$items['quantity'].'</td>
                  <td  width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>'.number_format($items['design_cost'], 2, $separator, '').'</td>
                  <td  width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>'.number_format($items['unit_total'], 2, $separator, '').'</td>
                </tr>';
            } else {
                $html .= '<tr>
                  <td  width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $slNo . '</td>
                  <td width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;" >No product availabe</td>
                  <td width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">The product might be deleted or remove from store.</td>
                  <td width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"></td>
                  <td width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $items['quantity'] . '</td>
                  <td width="10%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>' . number_format($items['design_cost'], 2, $separator, '') . '</td>
                  <td width="20%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>' . number_format($items['unit_total'], 2, $separator, '') . '</td>
                  </tr>';
            }
          }
          $display = ($quotationDetails['note'] == '') ? 'display: none;' : '';
          $html .= '</tbody>
          </table>
          <table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-top: 30px; line-height: 24px;">
            <tr>
              <td width="58%">
                <br/>
                <span style="font-size: 14px; '.$display.'"><strong>'.$pdfLanguage['note'].'</strong></span>
                <span style="font-size: 12px; line-height: 22px; '.$display.'"><br/>
                  '.$quotationDetails['note'].'
                </span>
              </td>
              <td width="42%" align="'.$rtlLeftAlign.'">
                <table width="100%" cellspacing="0" cellpadding="0" border="0" style="font-size: 12px; line-height: 20px;">
                  <tr>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><strong> '.$pdfLanguage['subtotal'].'</strong></td>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>'.number_format($subtotal, 2, $separator, '').'</td>
                  </tr>';
                  if ($quotationDetails['discount_type'] == 'percentage') {
                    $discountType = $pdfLanguage['percentage'];
                  } else {
                    $discountType = $pdfLanguage['flat'];
                  }
                  if ($quotationDetails['discount_type'] == 'percentage') {
                    $discountValue = $subtotal * ($quotationDetails['discount_amount']/100);
                    $decCount = strlen(substr(strrchr($discountValue, "."), 1));
                    if ($decCount <= 2) {
                        $finalDiscount = number_format($discountValue, 2, $separator, '');
                    } else {
                        $finalDiscount = str_replace(".",$separator,floor($discountValue * 100) / 100);
                    }
                    $discountAmount = ' - <span> '.$currency.'</span>'.$finalDiscount;
                    $showDisPercent = ' ('.$quotationDetails['discount_amount'].'%)';
                  } else {
                    $discountValue = $quotationDetails['discount_amount'];
                    $discountAmount = ' - <span> '.$currency.'</span>'.number_format($discountValue, 2, $separator, '');
                    $showDisPercent = '';
                  }
                  if ($quotationDetails['discount_amount'] > 0) {
                  $html .= '<tr>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['discount'].'('.$discountType.')</td>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;">'.$discountAmount.$showDisPercent.'</td>
                  </tr>';
                  }
                  if ($quotationDetails['shipping_amount'] > 0) {
                    $html .= '<tr>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['shipping'].'</td>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>'.number_format($quotationDetails['shipping_amount'], 2, $separator, '').'</td>
                  </tr>';
                  }
                  if ($quotationDetails['is_rush'] == '1') {
                      if ($quotationDetails['rush_type'] == 'percentage') {
                          $rush = $subtotal * ($quotationDetails['rush_amount']/100);
                          $rushAmount = number_format($rush, 2, $separator, '');
                          $showPercent = ' ('.$quotationDetails['rush_amount'].'%)';
                      } else {
                          $rushAmount = number_format($quotationDetails['rush_amount'], 2, $separator, '');
                          $showPercent = '';
                      }
                      $html .= '<tr>
                        <td width="50%" ="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;">'.$pdfLanguage['rush'].'('.ucfirst($quotationDetails['rush_type']).')</td>
                        <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"><span> '.$currency.'</span>'.$rushAmount.$showPercent.'</td>
                      </tr>';
                  }
                  $taxAmount = ($subtotal - $discountValue) * ($quotationDetails['tax_amount'] / 100);
                  $taxAmount = number_format($taxAmount, 2, $separator, ''); //
                  if ($quotationDetails['tax_amount'] > 0) {
                  $html .= '<tr>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['tax'].'(%)</td>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>'.$taxAmount.' ('.$quotationDetails['tax_amount'].'%)</td>
                  </tr>';
                  }
                  $html .= '<tr>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['due'].'</td>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><span> '.$currency.'</span>'.number_format($quotationDetails['due_amount'], 2, $separator, '').'</td>
                  </tr>
                  <tr>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['total'].'</td>
                    <td width="50%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;"><br/>
                      <span> '.$currency.'</span>'.number_format($quotationDetails['quote_total'], 2, $separator, '').'
                    </td>
                  </tr>
                </table>
                <span style="font-size: 10px;"><br/>
                  ('.$pdfLanguage['all-prices'].' '.$currency.')
                </span>
              </td>
            </tr>
            <tr>
              <td colspan="2" width="100%">
                <hr style="margin: 30px 0 0 0;">
              </td>
            </tr>
          </table>
        </table>
      </body></html>';
          $filePath = path('abs', 'quotation').$quotationId.'/';
          $fileNames = create_tcpdf($html, $filePath, 'INVOICE-'.$quotationDetails['quote_id'], $toolLang);
          if ($fileNames) {
              //Download file in local system
              $dir = $filePath.$fileNames;
              return $dir;
          }
        }
         return false;
    }
       


    /**
     * GET: Single Quotation payment Details
     *
     * @param $quotationId  Quotation Id
     *
     * @author debashrib@riaxe.com
     * @date   31 Mar 2019
     * @return json response
     */
    public function getQuotationPayment($quotationId)
    {
        $paymentDetails = [];
        if ($quotationId > 0) {
            $paymentInit = new QuotationPayment();
            //Get if any payment made
            $payment = $paymentInit->where('quote_id', $quotationId);
            if ($payment->count() > 0) {
                $paymentDetails = $payment->get()->toArray();
            }
        }
        return $paymentDetails;
    }

    /**
     * POST: Receive Quotation Payment
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   31 Mar 2019
     * @return json response
     */
    public function receivePayment($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Payment', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $allPostPutVars = $forLogData =  json_clean_decode($allPostPutVars['data'], true);
        if (!empty($allPostPutVars['is_stock_available'])) {
          $isStockAvailable = $allPostPutVars['is_stock_available'];
        } else {
          //This for other then "magento, prestashop" store
          $isStockAvailable = 1;
        }

        if ($allPostPutVars['quote_id'] != '' && $allPostPutVars['quote_id'] > 0) {
            $quoteId = to_int($allPostPutVars['quote_id']);
            unset($allPostPutVars['user_type'], $allPostPutVars['user_id']);
            $paymentInit = new QuotationPayment($allPostPutVars);
            if ($paymentInit->save()) {
                //Empty payment amount form quotation
                $quotationInit = new Quotations();
                $updateData = [
                    'request_payment' => null,
                    'request_date' => null
                ];
                $quotationInit->where('xe_id', $quoteId)
                    ->update($updateData); 
                //Adding to quote log
                //Get currency from global setting
                $quotationDetails = $this->getQuotationDetails($request, $response, ['id' => $quoteId], 1);
                //$globalSettingData = $this->readSettingJsonFile($getStoreDetails['store_id']);
                $currency = $quotationDetails['currency']['value'];
                $logData = [
                    'quote_id' => $forLogData['quote_id'],
                    'title' => 'Payment paid',
                    'description' => 'Payment is made for '.$currency.$forLogData['payment_amount'].' by '.$forLogData['payment_mode'],
                    'user_type' => $forLogData['user_type'],
                    'user_id' => $forLogData['user_id'],
                    'created_date' => date_time(
                        'today', [], 'string'
                    )
                ];
                $this->addingQuotationLog($logData);
                
                //Bind email template
                $templateData = $this->bindEmailTemplate('receive_payment', $quotationDetails, $getStoreDetails);
                $templateData = $templateData[0];
                $mailResponse = $this->sendQuotationEmail($templateData, $quotationDetails['customer'], [], $getStoreDetails);
                //Get minimum pay amount for convert to order from setting
                $settingData = $this->getProductionSetting($request, $response, ['module_id' => 1, 'return_type' => 1]);
                $settingData = $settingData['data'];
                $isMinimumPercent = $settingData['is_minimum_payment'];
                $minimumPaidAmount = $settingData['minimum_payment_percent'];
                //Check the paid percentage
                $comPaidAmount = 0;
                $paymentInit = new QuotationPayment();
                $paymentDataArr =  $paymentInit->where('quote_id', $quoteId);
                if ($paymentDataArr->count() >= 0) {
                  $isConvertToOrder = false;
                  $paymentData = $paymentDataArr->get()->toArray();
                  $completedStatus = array_filter($paymentData, function($item) {
                      return $item['payment_status'] == 'paid';
                  });
                  $comAmountArr = array_column($completedStatus, 'payment_amount');
                  $comPaidAmount = array_sum($comAmountArr);
                  $quoteTotalAmount = $quotationDetails['quote_total'];
                  $paidPercentage = ($comPaidAmount/$quoteTotalAmount)*100;
                  $lastQuotationStatus = $quotationDetails['status_id'];
                  //If minimum amount paid convert it to order
                  //Get Order status id
                  $statusInit = new ProductionStatus();
                  $orderStatusId = 0;
                  $getOrderedStatusData = $statusInit->select('xe_id')->where([
                      'store_id' => $getStoreDetails['store_id'], 
                      'slug' => 'ordered',
                      'module_id' => 1
                  ]);

                  if ($getOrderedStatusData->count() > 0) {
                     $getOrderedStatusDataArr = $getOrderedStatusData->first(); 
                     $getOrderedStatusDataArr = json_clean_decode($getOrderedStatusDataArr, true);
                     $orderStatusId = $getOrderedStatusDataArr['xe_id'];
                  }
                  if ($lastQuotationStatus != $orderStatusId) {
                    if ($isStockAvailable == 1 && ($paidPercentage == 100 || (($paidPercentage >= $minimumPaidAmount) 
                      && $minimumPaidAmount > 0 && $isMinimumPercent == 1))) {
                        $isConvertToOrder = true;
                    }
                  }
                  $jsonResponse = [
                    'status' => 1,
                    'is_convert_to_order' => $isConvertToOrder,
                    'message' => message('Quotation Payment', 'updated')
                  ];
              }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * DELETE: Delete payment
     *
     * @param $request  Slim's Argument parameters
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   08 Apr 2019
     * @return json response wheather data is deleted or not
     */
    public function deletePayment($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Payment', 'error')
        ];
        $getStoreDetails = get_store_details($request);
        $paymentId = $args['id'];
        $userId = $request->getQueryParam('user_id');
        $userType = $request->getQueryParam('user_type');
        if (!empty($paymentId) && $paymentId > 0) {
            $paymentInit = new QuotationPayment();
            $payment = $paymentInit->where(
                ['xe_id' => $paymentId]
            );

            if ($payment->count() > 0) {
                $paymentData = $payment->first()->toArray();
                $paymentAmount = $paymentData['payment_amount'];
                $quoteId = $paymentData['quote_id'];
                $quotationInit = new Quotations();
                $quotation = $quotationInit->select('currency_id')->where('xe_id', $quoteId);
                $quotationDetails = $quotation->first()->toArray();
                //Delete Payment
                if ($payment->delete()) {
                  //Get currency from global setting
                  $currencyId = $quotationDetails['currency_id'];
                  $currencyData = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
                  //Adding to quote log
                  $logData = [
                      'quote_id' => $quoteId,
                      'title' => 'Payment deleted',
                      'description' => 'Payment of '.$currencyData['value'].$paymentAmount.' is deleted',
                      'user_type' => ($userType != '') ? $userType : 'admin',
                      'user_id' => ($userId != '') ? $userId : 1,
                      'created_date' => date_time(
                          'today', [], 'string'
                      )
                  ];
                  $this->addingQuotationLog($logData);
                    $jsonResponse = [
                        'status' => 1,
                        'message' => message('Quotation Payment', 'deleted'),
                    ];
                }
            }
        }

        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * GET: Single Quotation payment Details
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     * @param $args     Slim's Argument parameters
     *
     * @author debashrib@riaxe.com
     * @date   29 May 2019
     * @return json response
     */
    public function getQuotationPaymentLog($request, $response, $args, $returnType = 0)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 1,
            'data' => [],
            'message' => message('Quotation Payment Log', 'not_found'),
        ];
        $getStoreDetails = get_store_details($request);
        $quotationInit = new Quotations();
        if (!empty($args['id'])) {
            $quoteId = to_int($args['id']);
            $quotation = $quotationInit->where(
                [
                'xe_id' => $quoteId,
                'store_id' => $getStoreDetails['store_id']
            ]);
            if ($quotation->count() > 0) {
                $quoteDetails = $quotation->first()->toArray();
                $currencyId = $quoteDetails['currency_id'];
                $currencyData = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);

                $paymentInit = new QuotationPayment();
                $paymentData =  $paymentInit->where('quote_id', $quoteId);
                $paymentLog = [];
                $comPaidAmount = 0;
                if ($paymentData->count() > 0) {
                    $paymentDataArr = $paymentData->get()->toArray();
                    $completedStatus = array_filter($paymentDataArr, function($item) {
                        return $item['payment_status'] == 'paid';
                    });
                    $comAmountArr = array_column($completedStatus, 'payment_amount');
                    $comPaidAmount = array_sum($comAmountArr);
                    foreach ($paymentDataArr as $payments) {
                        $newPayment = $payments;
                        $through = $payments['payment_mode'];
                        if ($payments['txn_id'] != "" && $payments['note'] == '') {
                          $newPayment['note'] = 'Txn Id : '.$payments['txn_id'];
                          //Get payment setting data
                          $paymentSetting = $this->getPaymentMethod();
                          $paymentMethodId = $payments['payment_method_id'];
                          $paymentSettingData = array_filter($paymentSetting, function($item) use ($paymentMethodId){
                                  return $item['xe_id'] == $paymentMethodId;
                              });
                          $paymentSettingData = $paymentSettingData[array_keys($paymentSettingData)[0]];
                          $through = $paymentSettingData['payment_type'];
                        }
                        $newPayment['description'] = "A payment of ".$currencyData['value'].$payments['payment_amount']." is done through ".$through."."; 
                        $newPayment['is_editable'] = $payments['txn_id'] != "" ? 0 : 1 ; 
                        array_push($paymentLog, $newPayment);
                    }
                }
                $jsonResponse = [
                    'status' => 1,
                    'log_data' => $paymentLog,
                    'paid_amount' => $comPaidAmount
                ];
                if ($returnType == 1) {
                    return $jsonResponse;
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Update received payment
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   29 May 2019
     * @return json response
     */
    public function updatePayment($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Quotation Payment', 'error'),
        ];
        $allPostPutVars = $request->getParsedBody();
        $allPostPutVars = $forLogData =  json_clean_decode($allPostPutVars['data'], true);

        if ($allPostPutVars['payment_id'] != '' && $allPostPutVars['payment_id'] > 0) {
            $paymentId = to_int($allPostPutVars['payment_id']);
            unset($allPostPutVars['user_type'], $allPostPutVars['user_id']);
            $paymentInit = new QuotationPayment();
            //Get Old payment data
            $oldPayment = $paymentInit->where('xe_id', $paymentId);
            if ($oldPayment->count() > 0) {
              $oldPaymentData = $oldPayment->get()->toArray();
              $oldPaymentData = $oldPaymentData[0];
              //Update Payment
              unset(
                  $allPostPutVars['payment_id'], 
                  $allPostPutVars['user_type'], 
                  $allPostPutVars['user_id']
              );
              $paymentInit->where('xe_id', $paymentId)
                  ->update($allPostPutVars); 
               //Get quotation details
              $quotationDetails = $this->getQuotationDetails($request, $response, ['id' => $forLogData['quote_id']], 1);
              $currency = $quotationDetails['currency']['value'];
              //Adding to quote log
              $logData = [
                  'quote_id' => $forLogData['quote_id'],
                  'title' => 'Payment updated',
                  'description' => 'Payment is updated from '.$currency.$oldPaymentData['payment_amount'].'  to '.$currency.$forLogData['payment_amount'],
                  'user_type' => $forLogData['user_type'],
                  'user_id' => $forLogData['user_id'],
                  'created_date' => date_time(
                      'today', [], 'string'
                  )
              ];
              $this->addingQuotationLog($logData);
              //Get quotation details
              $quotationDetails = $this->getQuotationDetails($request, $response, ['id' => $forLogData['quote_id']], 1);
              //Get minimum pay amount for convert to order from setting
              $settingData = $this->getProductionSetting($request, $response, ['module_id' => 1, 'return_type' => 1]);
              $settingData = $settingData['data'];
              $isMinimumPercent = $settingData['is_minimum_payment'];
              $minimumPaidAmount = $settingData['minimum_payment_percent'];
              //Check the paid percentage
              $comPaidAmount = 0;
              $paymentInit = new QuotationPayment();
              $paymentDataArr =  $paymentInit->where('quote_id', $forLogData['quote_id']);
              if ($paymentDataArr->count() >= 0) {
                $isConvertToOrder = false;
                $paymentData = $paymentDataArr->get()->toArray();
                $completedStatus = array_filter($paymentData, function($item) {
                    return $item['payment_status'] == 'paid';
                });
                $comAmountArr = array_column($completedStatus, 'payment_amount');
                $comPaidAmount = array_sum($comAmountArr);
                $quoteTotalAmount = $quotationDetails['quote_total'];
                $paidPercentage = ($comPaidAmount/$quoteTotalAmount)*100;
                $lastQuotationStatus = $quotationDetails['status_id'];
                //If minimum amount paid convert it to order
                if ($lastQuotationStatus != 5) {
                  if (($paidPercentage >= $minimumPaidAmount) 
                    && $minimumPaidAmount > 0 && $isMinimumPercent == 1) {
                      $isConvertToOrder = true;
                  }
                }
                $jsonResponse = [
                    'status' => 1,
                    'is_convert_to_order' => $isConvertToOrder,
                    'message' => message('Quotation Payment', 'updated')
                ];
              }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: PayPal Payment Integration  
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   10 June 2020
     * @return json response wheather data is saved or any error occured
     */
    public function paypalPayment($request, $response)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Paypal', 'error')
        ];
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $quotationId = to_int($allPostPutVars['quote_id']);
        if ($quotationId != '') {
            $userId = $allPostPutVars['user_id'];
            $userType = $allPostPutVars['user_type'];
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            $payPalURL = '';
            if ($getOldQuotation->count() > 0) {
                $quoteData = $getOldQuotation->first()->toArray();
                //Get currency 
                $currencyId = $quoteData['currency_id'];
                $currencyData = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
                //Get payment setting data
                $paymentSetting = $this->getPaymentMethod($getStoreDetails['store_id'], 1, 0);
                $paypalSettingData = array_filter($paymentSetting, function($item) {
                        return $item['payment_type'] == 'PayPal';
                    });
                $paypalSettingData = $paypalSettingData[0];
                //Get Paypal setting Data
                $sandboxURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
                $liveURL = 'https://www.paypal.com/cgi-bin/webscr';
                //
                $stoken = 'quote_id=' . $quoteData['xe_id'].'&status=success';
                $stoken = base64_encode($stoken);
                $sUrl = 'quotation/quotation-approval?token=' . $stoken;

                $ctoken = 'quote_id=' . $quoteData['xe_id'].'&status=fail';
                $ctoken = base64_encode($ctoken);
                $cUrl = 'quotation/quotation-approval?token=' . $ctoken;

                $returnUrl = API_URL.$sUrl;
                $cancelUrl = API_URL.$cUrl;
                $notifyUrl = BASE_URL.'quotation-payment/paypal-payment/update';
                $paypal_path = ($paypalSettingData['payment_mode'] == 'test') ? $sandboxURL : $liveURL;

                //Insert a row in payment table before payment
                $savePaymentData = [
                    'quote_id' => $quoteData['xe_id'],
                    'payment_amount' => $allPostPutVars['payment_amount'],
                    'payment_mode' => 'online',
                    'payment_status' => 'pending',
                    'payment_method_id' => $paypalSettingData['xe_id'],
                    'payment_date' => date_time(
                                'today', [], 'string'
                            )
                ];
                $merchantEmailId = $this->decryptKey($paypalSettingData['payment_setting']['merchant_email_id']);
                $paymentInit = new QuotationPayment($savePaymentData); 
                if ($paymentInit->save()) {
                    $lastPaymentId = $paymentInit->xe_id;
                    $paypalParam = array();
                    $paypalParam['cmd'] = '_xclick';
                    $paypalParam['business'] = $merchantEmailId;
                    //sb-aczhz1781272@personal.example.com 
                    //$paypalSettingData['payment_setting']['merchant_email_id'];
                    $paypalParam['item_name'] = $quoteData['quote_id'];
                    $paypalParam['amount'] = $allPostPutVars['payment_amount'];
                    $paypalParam['quantity'] = 1;
                    $paypalParam['item_number'] = $quoteData['xe_id'];
                    //Get currency from global setting
                    /*$storeId = 1;
                    $globalSettingData = $this->readSettingJsonFile($storeId);
                    $currencyCode = $globalSettingData['currency']['code'];*/
                    $paypalParam['currency_code'] = $currencyData['currency']['code'];//$currencyCode;
                    $paypalParam['custom'] = 'quotation-'.$quoteData['xe_id'].'~:~'.$lastPaymentId.'~:~'.$userId.'~:~'.$userType;
                    $paypalParam['rm'] = 2;
                    $paypalParam['return'] = $returnUrl;
                    $paypalParam['cancel_return'] = $cancelUrl;
                    $paypalParam['notify_url'] = $notifyUrl;
                    $payPalURL = "?";
                    foreach ($paypalParam as $key => $value) {
                        $payPalURL.=$key."=".$value."&";
                    }
                    $payPalURL=substr($payPalURL,0,-1);
                    $jsonResponse = [
                        'status' => 1,
                        'url' =>$paypal_path. $payPalURL
                    ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

    /**
     * POST: Update payment data after success
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author debashrib@riaxe.com
     * @date   10 June 2020
     * @return json response
     */
    public function updatePaypalResponse($request, $response)
    {
        $getStoreDetails = get_store_details($request);
        $allPostPutVars = $request->getParsedBody();
        $quotationId = to_int($allPostPutVars['quote_id']);
        if (isset($allPostPutVars['custom']) && $allPostPutVars['custom'] != '') {
            $customData = $allPostPutVars['custom'];
            $customDataArr = explode('~:~', $customData);
            $quotation = $customDataArr[0];
            $quotationArr = explode('-', $quotation);
            $quotationId = $quotationArr[1];
            $paymentId = $customDataArr[1];
            $userId = $customDataArr[2];
            $userType = $customDataArr[3];
            $txnId = $allPostPutVars['txn_id'];
            $paymentAmount = $allPostPutVars['payment_gross'];

            //Check if txn id is updated or not for this particular payment
            $paymentInit = new QuotationPayment();
            $checkPayment = $paymentInit->where([
              'xe_id' => $paymentId,
              'payment_status' => 'paid',
              'txn_id' => $txnId,
            ]);
            if ($txnId !='' && $checkPayment->count() == 0) {
              $updateData = [
                  'txn_id' => $txnId,
                  'payment_status' => 'paid'
              ];
              $paymentInit->where('xe_id', $paymentId)->update($updateData); 
              //Empty payment amount form quotation
              $quotationInit = new Quotations();
              $updateData = [
                  'request_payment' => null,
                  'request_date' => null
              ];
              $quotationInit->where('xe_id', $quotationId)
                  ->update($updateData); 
              //Get currency
              /*$globalSettingData = $this->readSettingJsonFile($getStoreDetails['store_id']);
              $currency = $globalSettingData['currency']['value'];*/
              $quotationData = $quotationInit->select('currency_id')->where('xe_id', $quotationId)->first()->toArray();
              $currencyId = $quotationData['currency_id'];
              $currencyData = $this->getUsedCurrency($currencyId, $getStoreDetails['store_id']);
              $currency = $currencyData['currency']['value'];
              //Adding to quote log
              $logData = [
                  'quote_id' => $quotationId,
                  'title' => 'Payment paid',
                  'description' => 'Payment is made for '.$currency.$paymentAmount.' through PayPal. Txn Id: '.$txnId,
                  'user_type' => $userType,
                  'user_id' => $userId,
                  'created_date' => date_time(
                      'today', [], 'string'
                  )
              ];
              $this->addingQuotationLog($logData);
              $this->paymentSuccessOperation($request, $response, $quotationId);
            }
        }
    }

    /**
     * POST: Stripe Payment Integration  
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   24 Sept 2020
     * @return json response wheather data is saved or any error occured
     */
    public function stripePayment($request, $response)
    {
        require_once 'app/Dependencies/stripe-php/init.php';
        $serverStatusCode = OPERATION_OKAY;
        $getStoreDetails = get_store_details($request);
        $jsonResponse = [
            'status' => 0,
            'message' => message('Stripe', 'error')
        ];
        $apiErrorArr = [];
        $allPostPutVars = $request->getParsedBody();
        $quotationId = to_int($allPostPutVars['quote_id']);
        $token = $allPostPutVars['token'];
        $paymentFor = $allPostPutVars['payment_for'];
        if ($quotationId != '' && $token !='') {
            $userId = $allPostPutVars['user_id'];
            $userType = $allPostPutVars['user_type'];
            $description = $allPostPutVars['description'];
            $quotationInit = new Quotations();
            $getOldQuotation = $quotationInit->where('xe_id', $quotationId);
            if ($getOldQuotation->count() > 0) {
                $quotationDetails = $this->getQuotationDetails($request, $response, ['id' => $quotationId], 1);
                $customerEmail = $quotationDetails['customer']['email'];
                $customerId = $quotationDetails['customer']['id'];
                $payableAmount = ($paymentFor == 'full') ? $quotationDetails['due_amount'] : $quotationDetails['request_payment'];
                //Get payment setting data
                $paymentSetting = $this->getPaymentMethod($getStoreDetails['store_id'], 1, 0);
                $stripeSettingData = array_filter($paymentSetting, function($item) {
                      return $item['payment_type'] == 'Stripe';
                  });
                $stripeSettingData = $stripeSettingData[array_keys($stripeSettingData)[0]];
                if (!empty($stripeSettingData['payment_setting'])) {
                  $secretKey =  $this->decryptKey($stripeSettingData['payment_setting']['secret_key']);
                  // Set API key
                  \Stripe\Stripe::setApiKey($secretKey);
                  //Check for stripe customer id
                  $customerAdditionalInfoInit = new CustomerAdditionalInfo();
                  $customerStripeRel = $customerAdditionalInfoInit->where([
                    'store_id' => $getStoreDetails['store_id'],
                    'customer_id' => $customerId,
                    'customer_email' => $customerEmail
                  ]);
                  if ($customerStripeRel->count() > 0) {
                    $customerStripeRelData = $customerStripeRel->first();
                    $customerStripeRelData = json_clean_decode($customerStripeRelData, true);
                    $stripeCustomerId = $customerStripeRelData['stripe_customer_id'];
                  } else {
                    // Add customer to stripe
                    try {
                      $customer = \Stripe\Customer::create(
                          array(
                              'email' => $customerEmail,
                              'source' => $token,
                          )
                      );
                      if ($customer) {
                        //Add data to dashboard
                        $saveData = [
                          'store_id' => $getStoreDetails['store_id'],
                          'customer_id' => $customerId,
                          'customer_email' => $customerEmail,
                          'stripe_customer_id' => $customer->id
                        ];
                        $saveCustomerAdditionalInfo = new customerAdditionalInfo($saveData);
                        $saveCustomerAdditionalInfo->save();
                        $stripeCustomerId = $customer->id;
                      }
                    } catch (\Exception $e) {
                        $jsonResponse = [
                          'status' => 0,
                          'message' => $e->getMessage()
                      ];
                    }
                  }
                  //Charge
                  if ($stripeCustomerId) {
                    // Convert price to cents
                    $itemPrice = ($payableAmount * 100);
                    try {
                      $country = $quotationDetails['customer']['billing_address']['country'];
                      if (strlen($country) == 3) {
                        if($country == 'ARE') {
                          $country = 'AE';
                        } else {
                          $country = substr_replace($country ,"",-1);
                        }
                      }
                        $billingAddress = array(
                            "address" => array(
                                "country" => $country,
                                "line1" => $quotationDetails['customer']['billing_address']['address_1'],
                                "line2" => $quotationDetails['customer']['billing_address']['address_2'],
                                "postal_code" => $quotationDetails['customer']['billing_address']['postcode'],
                            ),
                            "name" => $quotationDetails['customer']['billing_address']['first_name'].' '.$quotationDetails['customer']['billing_address']['last_name'],
                            "phone" => $quotationDetails['customer']['billing_address']['phone'],
                        );
                        //Get currency from global setting
                        //$globalSettingData = $this->readSettingJsonFile($getStoreDetails['store_id']);
                        $currency = $quotationDetails['currency']['value'];
                        $currencyCode = $quotationDetails['currency']['code'];
                        $charge = \Stripe\Charge::create(
                            array(
                                'customer' => $stripeCustomerId,
                                'amount' => $itemPrice,
                                'currency' => $currencyCode,
                                'description' => $description,
                                'shipping' => $billingAddress,
                            )
                        );
                        //var_dump($charge);
                    } catch (\Stripe\Exception\CardException $e) {
                        // Since it's a decline, \Stripe\Exception\CardException will be caught
                        $apiErrorArr[] = $e->getMessage();
                    } catch (\Stripe\Exception\RateLimitException $e) {
                        // Too many requests made to the API too quickly
                        $apiErrorArr[] = $e->getMessage();
                    } catch (\Stripe\Exception\InvalidRequestException $e) {
                        // Invalid parameters were supplied to Stripe's API
                        $apiErrorArr[] = $e->getMessage();
                    } catch (\Stripe\Exception\AuthenticationException $e) {
                        // Authentication with Stripe's API failed
                        // (maybe you changed API keys recently)
                        $apiErrorArr[] = $e->getMessage();
                    } catch (\Stripe\Exception\ApiConnectionException $e) {
                        // Network communication with Stripe failed
                        $apiErrorArr[] = $e->getMessage();
                    } catch (\Stripe\Exception\ApiErrorException $e) {
                        // Display a very generic error to the user, and maybe send
                        // yourself an email
                        $apiErrorArr[] = $e->getMessage();
                    } catch (\Exception $e) {
                        // Something else happened, completely unrelated to Stripe
                        $apiErrorArr[] = $e->getMessage();
                    }
                  }
                  if (empty($apiErrorArr) && $charge) {
                    // Retrieve charge details
                    $chargeJson = $charge->jsonSerialize();
                    // Check whether the charge is successful
                    if ($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1) {
                      //Add quotation payment data
                      $savePaymentData = [
                        'quote_id' => $quotationId,
                        'payment_amount' => $payableAmount,
                        'payment_mode' => 'online',
                        'payment_status' => 'paid',
                        'payment_method_id' => $stripeSettingData['xe_id'],
                        'txn_id' => $chargeJson['balance_transaction'],
                        'payment_date' => date_time(
                            'today', [], 'string'
                        )
                      ];
                      $savePayment = new QuotationPayment($savePaymentData); 
                      if ($savePayment->save()) {
                        //Empty payment amount form quotation
                        $quotationInit = new Quotations();
                        $updateData = [
                            'request_payment' => null,
                            'request_date' => null
                        ];
                        $quotationInit->where('xe_id', $quotationId)
                            ->update($updateData); 
                        //Adding to quote log
                        $logData = [
                            'quote_id' => $quotationId,
                            'title' => 'Payment paid',
                            'description' => 'Payment is made for '.$currency.$payableAmount.' through Stripe. Txn Id: '.$chargeJson['balance_transaction'],
                            'user_type' => $userType,
                            'user_id' => $userId,
                            'created_date' => date_time(
                                'today', [], 'string'
                            )
                        ];
                        $this->addingQuotationLog($logData);
                        $this->paymentSuccessOperation($request, $response, $quotationId);
                        $jsonResponse = [
                            'status' => 1,
                            'message' => message('Stripe', 'done'),
                        ];
                      }
                    }
                  } else {
                    $errMsg = implode(',', $apiErrorArr);
                    $jsonResponse = [
                        'status' => 0,
                        'message' => ($errMsg != '') ? $errMsg : message('Stripe', 'error'),
                    ];
                  }

                } else {
                  $jsonResponse = [
                      'status' => 0,
                      'message' => message('Stripe', 'insufficient')
                  ];
                }
            }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }


    /**
     *Operation should be done after payment success   
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   24 Sept 2020
     * @return json response wheather data is saved or any error occured
     */
    public function paymentSuccessOperation($request, $response, $quotationId) 
    {
      //Empty payment amount form quotation
      $quotationInit = new Quotations();
      $updateData = [
          'request_payment' => null,
          'request_date' => null
      ];
      $quotationInit->where('xe_id', $quotationId)->update($updateData); 
      //Create quotation pdf 
      $this->createQuotationPdf($request, $response, ['id' => $quotationId], 1);
      //Get quotation total amount
      $quotationInit = new Quotations();
      $quotationData = $quotationInit->select('quote_total', 'customer_id')
          ->where('xe_id', $quotationId)->first()->toArray();
      $quoteTotalAmount = $quotationData['quote_total'];
      $customerId = $quotationData['customer_id'];
      //Check the paid percentage
      $comPaidAmount = 0;
      $paymentInit = new QuotationPayment();
      $paymentDataArr =  $paymentInit->where('quote_id', $quotationId);
      if ($paymentDataArr->count() >= 0) {
        $paymentData = $paymentDataArr->get()->toArray();
        $completedStatus = array_filter($paymentData, function($item) {
            return $item['payment_status'] == 'paid';
        });
        $comAmountArr = array_column($completedStatus, 'payment_amount');
        $comPaidAmount = array_sum($comAmountArr);
        $paidPercentage = ($comPaidAmount/$quoteTotalAmount)*100;
        //If minimum amount paid convert it to order
        $convertQuoteToOrder = 0;
        if ($paidPercentage == 100) {
          $convertQuoteToOrder = 1;
        } else {
          //Get minimum pay amount for convert to order from setting
          $settingData = $this->getProductionSetting($request, $response, ['module_id' => 1, 'return_type' => 1]);
          $settingData = $settingData['data'];
          $isMinimumPercent = $settingData['is_minimum_payment'];
          $minimumPaidAmount = $settingData['minimum_payment_percent'];
          if ($paidPercentage >= $minimumPaidAmount && $minimumPaidAmount > 0 && $isMinimumPercent == 1) {
            $convertQuoteToOrder = 1;
          }
        }
        if ($convertQuoteToOrder == 1) {
          $requestData = [
              'quote_id' => $quotationId,
              'user_type' => 'customer',
              'user_id' => $customerId,
              'return_type' => 1
          ];
          $jsonResponse = $this->convertQuoteToOrder($request, $response, $requestData);
          if (isset($jsonResponse['data'])) {
            $this->moveQuoteFileToOrder($request, $response, ['id' => $quotationId, 'order_id' => $jsonResponse['data']], 1);
          }
        }
      }
      return true;
    }

    /**
     * POST: Send invoice mail with invoice pdf file
     *
     * @param $request  Slim's Request object
     * @param $response Slim's Response object
     *
     * @author diana@imprintnext.com
     * @date   08 Aug 2019
     * @return json response
     */
    public function sendInvoiceMail($request, $response, $args)
    {
        $serverStatusCode = OPERATION_OKAY;
        $jsonResponse = [
            'status' => 0,
            'message' => message('Invoice mail', 'error'),
        ];
        $getStoreDetails = get_store_details($request);
        if (!empty($args['id']) && $args['id'] > 0) {
          $quotationId = $args['id'];
          $quotationDetails = $this->getQuotationDetails($request, $response, $args, 1);
          $itemsList = $this->getQuoteItems($request, $response, $args, 1);
          //generate invoice section 
          $dir = $this->createInvoicePdf($request, $response, $quotationId, $quotationDetails, $itemsList);
          //Bind email template
          $templateData = $this->bindEmailTemplate('request_payment', $quotationDetails, $getStoreDetails);
          $templateData = $templateData[0];
          $mailResponse = $this->sendQuotationEmail($templateData, $quotationDetails['customer'],  $getStoreDetails, [$dir]);
          if (!empty($mailResponse['status']) && $mailResponse['status'] == 1) {
            $jsonResponse = [
              'status' => 1,
              'message' => message('Invoice mail', 'done'),
            ];
          }
        }
        return response(
            $response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
        );
    }

}
