<?php

namespace Accounting\reports;
use Accounting\config\Entities;
use Accounting\transactions\receivable\Billings;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
class TransactionReports
{
    public function billingView ($billingNumber)
    {
        $response = DB::table('tbl_billing')->where('billing_no',$billingNumber)->first();
        $client = DB::table('tbl_entities')->where('code',$response->customer_code)->first();
        $client->details = DB::table('tbl_entity_details')->where('entity_code',$response->customer_code)->get();
        $client = (new Entities)->entityParser($client);
        $client->billingDetails = (new Entities)->billingDetails($client);
        $response = (new Billings)->getDetailResponse($response);
        $response->customer = $client;

        $items = DB::table('tbl_billing_items')->where('billing_no',$billingNumber)->get();
        $itemHeaders = DB::table('tbl_billing_transaction_map')->where('type',$response->service_type)->orderBy('sequence')->get();
        $headers = array();
        $columns = array();
        foreach($itemHeaders as $itemHeader){
            $headers[$itemHeader->sequence] = ['name' => $itemHeader->header_display, 'class' => $itemHeader->header_class];
            $columns[$itemHeader->sequence] = ['code' => $itemHeader->header_code, 'type' => $itemHeader->col_type, 'class' => $itemHeader->col_class];
        }
        $itemData = array();
        foreach($items as $item){
            $itemData[$item->sequence][$item->type] = $item->value;
        }
        $response->rowCount = 20 - sizeof($itemData);
        $response->columnCount = sizeof($columns);
        $response->items = $itemData;
        $response->itemHeaders = $headers;
        $response->itemColums = $columns;

        //return $response;

        $pdf_parse = PDF::loadView('templates/reports/billing-statement',(array)$response);
        $pdf_parse->setPaper('a4', 'portrait');

        return $pdf_parse->stream();
    }
    public function billingVoucherView ($billingNumber) {
        $response = DB::table('tbl_billing')->select()->where('billing_no',$billingNumber)->first();
        $client = DB::table('tbl_entities')->select()->where('code',$response->customer_code)->first();
        $client->details = DB::table('tbl_entity_details')->where('entity_code',$response->customer_code)->get();
        $client = (new Entities)->entityParser($client);
        $client->billingDetails = (new Entities)->billingDetails($client);
        $response = (new Billings)->getDetailResponse($response);
        $response->customer = $client;
        $entryDate = DB::table('tbl_entries')->where('trans_code', $response->transaction_no)->orderByDesc('created_at')->first();
        if($entryDate){
            $response->entry_date = $entryDate->created_at;
            $entries = DB::table('tbl_entries')->where('created_at',$entryDate->created_at)->where('trans_code',$response->transaction_no)->get();
            $entries->map(function ($entries){
                $acc_name = DB::table('tbl_chart_of_accounts')->select('title','custom_code')->where('code',$entries->acc_code)->first();
                $sub_ledger = DB::table('tbl_entries_details')->select('value')->where('acc_code',$entries->acc_code)->where('key','desc')
                    ->where('trans_code',$entries->trans_code)->first();
                $entries->acc_name = $acc_name?->title;
                $entries->custom_code = $acc_name?->custom_code;
                $entries->sub_ledger = $sub_ledger?->value;

            });
            $data = array();
            foreach($entries as $entry){
                $debit = '';$credit = '';
                if($entry->normal_balance === 'Dr') $debit = $entry->actual_value;
                else $credit = $entry->actual_value;
                $data[$entry->normal_balance][] = [
                    'account' => '['.$entry->custom_code.'] '.$entry->acc_name,
                    'acc_code' => $entry->custom_code,
                    'acc_name' => $entry->acc_name,
                    'sub_name' => $entry->sub_ledger,
                    'debit' => $debit > 0 ? number_format($debit, 2, '.',',') : '',
                    'credit' => $credit > 0 ? number_format($credit, 2, '.',',') : '',
                    'normal_balance' => $entry->normal_balance
                ];
            }
            $response->entries = $data;
        }
        $pdf_parse = PDF::loadView('templates/reports/billing-voucher',(array)$response);
        $pdf_parse->setPaper('a4', 'portrait');
        $customPaper = array(0,0,595, 421); //Half Size
        $pdf_parse->setPaper($customPaper, 'portrait');
        $return['data'] = $response;
        $return['pdf'] = $pdf_parse->stream();
        return  $pdf_parse->stream();
    }
    public function vouchers($voucherNo) {
        $voucher = array();
        $response = DB::table('tbl_journal')->select()->where('code',$voucherNo)->first();
        if($response){
            $entries = DB::table('tbl_general_ledgers')->select()->where('journal_code',$voucherNo)->get();
            $subsidiary =  DB::table('tbl_entities')->select('name')->where('code',$response->entity)->first();
            $entries = $entries->map(function ($entries) use($response){
                $subsidiaryName = '';
                $account = DB::table('tbl_chart_of_accounts')->select()->where('code',$entries->acc_code)->first();
                $sub = DB::table('tbl_subsidiary_ledgers')->select()->where('gl_id',$entries->id)->first();
                if($sub){
                    $subName =  DB::table('tbl_entities')->select('name')->where('code',$sub->sl_code)->first();
                    $subsidiaryName = $subName?->name;
                    if($subsidiaryName === null){
                        $subName =  DB::table('tbl_operations')->select('name')->where('code',$sub->sl_code)->first();
                        $subsidiaryName = $subName?->name;
                    }
                }
                $branch = DB::table('tbl_ledger_details')
                    ->leftJoin('tbl_operations', 'tbl_operations.code', '=', 'tbl_ledger_details.value')
                    ->select('tbl_operations.name')->where('key','branch')->where('ledger_id',$response->id)->first();
                $entryDesc = $entries->description;
                $particulars = $branch ? $branch->name : '';
                $particulars .= $subsidiaryName !== '' ? ' | '.$subsidiaryName : '';
                $particulars .= $entryDesc ? ' | '.$entryDesc : '';
                return [
                    'account' => '['.$account->custom_code.'] '.$account->title,
                    'details' => $particulars,
                    'debit' => $entries->debit_credit === 'Dr' ? formatAccountingCurrency($entries->amount) : '' ,
                    'credit' => $entries->debit_credit === 'Cr' ? formatAccountingCurrency($entries->amount) : '' ,
                    'normalBalance' => $entries->debit_credit,
                ];
            });
            $response->entries = $entries;
            $voucher['voucherNo'] = $response->reference_number;
            $voucher['transDate'] = dateParse($response->transaction_date,'M d, Y');
            $voucher['particulars'] = $response->particulars;
            $voucher['entries'] = $entries;
            if($response->type === 'receipt'){
                $voucher['payor'] = $subsidiary ? $subsidiary->name : '';
                $voucher['address'] = $this->entityAddress($response->entity, 'billingAddress');
                $voucher['data'] = $response;
                $pdf_parse = PDF::loadView('templates/vouchers/receipt-voucher',(array)$voucher);
            }
            else if($response->type === 'disbursement'){
                $voucher['payee'] = $subsidiary ? $subsidiary->name : '';
                $voucher['address'] = $this->entityAddress($response->entity, 'billingAddress');
                $voucher['data'] = $response;
                $pdf_parse = PDF::loadView('templates/vouchers/disbursement-voucher',(array)$voucher);
            }
            else {
                $pdf_parse = PDF::loadView('templates/vouchers/journal-voucher',(array)$voucher);
            }
            $pdf_parse->setPaper('a4', 'portrait');
            $customPaper = array(0,0,595, 421); //Half Size -
            $pdf_parse->setPaper($customPaper, 'portrait');
            return $pdf_parse->stream();
        }
        return $voucher;
    }
    private function entityAddress($code, $type) : string {
        $addresses =  DB::table('tbl_entity_details')->select()->where('entity_code', $code)->where('category', $type)->get();
        $addressData['province'] = null;
        $addressData['city'] = null;
        $addressData['barangay'] = null;
        $addressData['address'] = null;
        $addressStr = '';
        if($addresses){
            foreach($addresses as $address){
                if($address->type === 'provinceCode'){
                    $addressData['province'] = DB::connection('sys_base')->table('tbl_addresses')->where('type', 'province')
                        ->where('code', $address->value)->first();
                }
                else if($address->type === 'cityCode'){
                    $addressData['city'] = DB::connection('sys_base')->table('tbl_addresses')->where('type', 'city')
                        ->where('code', $address->value)->first();
                }
                else if($address->type === 'barangayCode'){
                    $addressData['barangay'] = DB::connection('sys_base')->table('tbl_addresses')->where('type', 'city')
                        ->where('code', $address->value)->first();
                }
                else if($address->type === 'address'){
                    $addressData['address'] = $address->value;
                }
            }
            $addressStr = $addressData['address'] ? $addressData['address'].', ' : '';
            $addressStr .= $addressData['barangay'] ? $addressData['barangay']->name.', ' : '';
            $addressStr .= $addressData['city'] ? $addressData['city']->name.', ' : '';
            $addressStr .= $addressData['province'] ? $addressData['province']->name : '';
        }
        return ucwords(strtolower($addressStr));
    }

    public function apiLogin(Request $request){
	//return $request->all();
        $data = array();
        $data['usercode'] = $request->user;
        $data['password'] = $request->pass;
   	
	$params['request'] = 'users';
        $params['type'] = 'login';
        $params['data'] = $data;

        //$response = $this->doRequest($params);
	//return successResponse("Success",$response);
       $headers = array(
            "Accept: application/json",
            "Accept-Encoding: gzip,deflate",
        );
	//return $data;
        $url = 'https://customer.tambunting.net/login-user-api';
        $postdata = json_encode($data);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, "postdata=".$postdata);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response,true);
   	$file['data'] = $response;
	return $file;
   }

   private static function apiWebRequest($return){
        $data = bin2hex(serialize($return));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://customer.tambunting.net/settings-request?filedata=".$data);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($ch, CURLOPT_SSLVERSION, 3);        
	$apioutput = curl_exec ($ch);
	var_dump( curl_getinfo($ch) ) . '<br/>';
	echo curl_errno($ch) . '<br/>';
	echo curl_error($ch) . '<br/>';	
        curl_close ($ch);
        return $apioutput;
    }

    public static function doRequest($file){
      if($file['request'] == "users"){
        if($file['type'] == "login") {
          $file['ipaddress'] = $_SERVER['REMOTE_ADDR'];
        }
      }
      $data['request'] = $file['request'];
      $data['type'] = $file['type'];
      $data['data'] = $file;
      //return $data;
      $key = "admin"."password";
      $headers = array(
          "Authorization: Basic ".base64_encode($key),
          "Accept: application/json",
          "Accept-Encoding: gzip,deflate",
        );
      $url = 'http://192.168.254.252/api-request';
      $postdata = json_encode($data);
      return $postdata;
      $curl = curl_init($url);
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($curl, CURLOPT_POSTFIELDS, "postdata=".$postdata);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_ENCODING, 'UTF-8');
      $response = curl_exec($curl);
      curl_close($curl);
      return $response;
    }
}
