<?php

namespace App\Http\Controllers;
use App\Models\modelReceipt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
use App\Models\PermissionsUserModel;
use Illuminate\Support\Facades\Auth;

class ReceiptController extends Controller
{
    public function PrintReceipt($type,$invoice)
    {
        $results=modelReceipt::ValidateTransactions(Session::get('PropertyCode'),Session::get('RegNo'),$type,$invoice);
        if(count($results)>0)
        {

            $Bankaccounts = modelReceipt::selectBanks(Session::get('PropertyCode'));
            modelReceipt::UpdateGenInvoice($type,Session::get('PropertyCode'));
            modelReceipt::processTransaction($type,$invoice,Session::get('PropertyCode'));
            modelReceipt::deleteTransactionJobs(Session::get('PropertyCode'),$type,$invoice);
            $cst=modelReceipt::selectInvoiceCustomer(Session::get('PropertyCode'),$type,$invoice);
            $pdetails=modelReceipt::selectInvoiceProperty(Session::get('PropertyCode'),Session::get('RegNo'));
            $Jts=modelReceipt::selectInvoiceTransactions(Session::get('PropertyCode'),$type,$invoice);

            $total=0;
            $symbol="";

            foreach ($Jts as $Jt)
            {
                $symbol=$Jt->Symbol;
                $total =$total+ ($Jt->DR*$Jt->Rate);


            }


            return view('/PrintReceipt',compact('invoice','Jts','total','cst','pdetails','type','symbol','Bankaccounts'));

        }
        else
        {

            return redirect()->route('receipt',['Type'=>$type]);
        }

    }
    public function index($Type)
    {


            try
            {
                $journal="";
                $batch="REC";

                    $batchs=modelReceipt::selectbatch(Session::get('PropertyCode'),Session::get('RegNo'));
                    if(count($batchs) == 0)
                    {

                    }
                    else
                    {
                        $exists = DB::table('receiptgenaration')->where('Status', '0')->exists();
                        if ($exists)
                        {


                        }
                        else
                        {

                        modelReceipt::Genbatch(Session::get('PropertyCode'),Session::get('RegNo'));

                        }
                    }

                        $batchs=modelReceipt::selectbatch(Session::get('PropertyCode'),Session::get('RegNo'));
                        $batch=$batchs[0]->ID;
                        if($batch<1000)
                        {
                            $batch="REC000".$batch+1;

                        }
                        else{
                            $batch="REC".$batch+1;
                        }
                $currencys=modelReceipt::selectcurrency(Session::get('PropertyCode'));
                $gls=modelReceipt::selectgl(Session::get('PropertyCode'));
                $Accounts=modelReceipt::selectTenants(Session::get('PropertyCode'));
                $Refs=modelReceipt::selectInvoices(Session::get('PropertyCode'));
                $Jts=modelReceipt::selectJournalTransactions(Session::get('PropertyCode'),Session::get('RegNo'),$Type);
                $total= 0;
                $symbol="";
                $mdes="";
                foreach ($Jts as $Jt)
                {
                    $symbol=$Jt->Symbol;
                    $total =$total+ ($Jt->DR*$Jt->Rate);
                    if($Jt->Source=="Supplier")
                    {
                        $batch=$Jt->Batch;


                    }
                    $mdes=$Jt->MNarration;

                }

                $journal=$Accounts[0]->AccCode;
                $JournalType=$Type;

                if($JournalType=="Tenant")
                {
                    $Accounts=modelReceipt::selectTenants(Session::get('PropertyCode'));
                    $journal=$Accounts[0]->AccCode;
                    $PermissionsAddReceipt = PermissionsUserModel::getPermission('Add Tenant Receipts', Auth::user()->id);
                    $PermissionsEditReceipt = PermissionsUserModel::getPermission('Edit Tenant Receipts', Auth::user()->id);
                    $PermissionsDeleteReceipt = PermissionsUserModel::getPermission('Delete Tenant Receipts', Auth::user()->id);

                }
                else if($JournalType=="Customer")
                {
                    $Accounts=modelReceipt::selectCustomers(Session::get('PropertyCode'));
                    $journal=$Accounts[0]->AccCode;
                    $PermissionsAddReceipt = PermissionsUserModel::getPermission('Add Customer Receipts', Auth::user()->id);
                    $PermissionsEditReceipt = PermissionsUserModel::getPermission('Edit Customer Receipts', Auth::user()->id);
                    $PermissionsDeleteReceipt = PermissionsUserModel::getPermission('Delete Customer Receipts', Auth::user()->id);

                }
                else if($JournalType=="Supplier")
                {
                    $Accounts=modelReceipt::selectSuppliers(Session::get('PropertyCode'));
                    $journal=$Accounts[0]->AccCode;
                }
                else if($JournalType=="GL")
                {
                    $Accounts=modelReceipt::selectGL(Session::get('PropertyCode'));
                    $journal=$Accounts[0]->AccCode;
                    $JournalType="General";


                }

                return view('/Receipt', compact('JournalType','Accounts','journal','Jts','Refs','gls','batch', 'total','currencys','symbol','mdes', 'PermissionsAddReceipt', 'PermissionsEditReceipt', 'PermissionsDeleteReceipt'));


        } catch (\Exception $e) {

            return redirect()->route('otheraccounts')->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
        }

        }
        public function getReferences($accountCode)
        {
            $references = DB::table('transactions as invoice')
                ->leftJoin('transactions as receipt', function ($join) {
                    $join->on('receipt.refference', '=', 'invoice.Batch')
                         ->where('receipt.TType', '=', 'receipt');
                })
                ->select('invoice.Batch', DB::raw('invoice.total - COALESCE(SUM(receipt.dr), 0) as balance'))
                ->where('invoice.AccSubCode', $accountCode)
                ->where('invoice.TType', 'invoice')
                ->groupBy('invoice.Batch', 'invoice.total')
                ->havingRaw('balance > 0')
                ->get();

            return response()->json($references);
        }

        public function savetransaction(Request $request)
        {
           // Validate the request data
                $request->validate([
                    'source' => 'required|string',
                    'AccCode' => 'required|string',
                    'date' => 'required|string',
                    'narr' => 'required|string',
                    'account' => 'required|string',
                    'amount' => 'required|string',
                    'gl' => 'required|string',
                    'batch' => 'required|string',
                    'mdes' => 'required|string',
                    'curr' => 'required|string'
                ]);

                $Rate=1;
                $mdes = $request->input('mdes');
                $curr = $request->input('curr');
                $id= "0";
                $disc="0";
                $src = $request->input('source');
                $AccCode = $request->input('AccCode');
                $date = $request->input('date');
                $narr = $request->input('narr');
                $reff = $request->input('reff');
                if($reff==null || $reff=="")
                {
                    $reff="0";
                }
                $amount = $request->input('amount');
                $price ="0";
                $AccSubCode = $request->input('account');
                $tax="0";
                $taxid="0";
                $qty = "0";
                $gl = $request->input('gl');
                $batch=$request->input('batch');
                $user=Session::get('RegNo');
                $parts = explode('/', $gl);
                $ContraCode = $parts[0];
                $ContraSubCode = isset($parts[1]) ? $parts[1] : '0';
                $DR=$amount;
                $CR="0";
                $total="0";
                $selectHomeCurrency=modelReceipt::selectHomeCurrency(Session::get('PropertyCode'));
                if(count($selectHomeCurrency)>0)
                {


                    $homeCurrency=$selectHomeCurrency[0]->Currency;


                    if($curr==$homeCurrency)
                    {

                    }
                    else
                    {

                        $selectRate=modelReceipt::selectRate(Session::get('PropertyCode'),$curr);

                        if(count($selectRate)>0)
                        {

                            $Rate=$selectRate[0]->Rate;

                            $DR= $DR/$Rate;

                        }
                        else
                        {
                            return redirect()->route('receipt',['Type'=>$src])->withErrors(['error' => 'No rate set for this currency' ]);

                        }

                    }

                }
                else
                {
                    return redirect()->route('invoice',['Type'=>$src])->withErrors(['error' => 'Home Currency Not Found' ]);

                }

                try
                {
                    modelReceipt::updateTransactionMdes(Session::get('PropertyCode'),$batch,$mdes,$src);
                $result = modelReceipt::saveTransaction(Session::get('PropertyCode'),$date,$AccCode,$AccSubCode,$ContraCode,$ContraSubCode,$narr,$reff, $DR,$CR,$user,$src,$tax,$taxid,$disc,$qty,$price,$total,$batch,$curr,$Rate,$mdes,"Receipt");
                if ($result)
                {
                     return redirect()->route('receipt',['Type'=>$src]);
               }
                else
                {
                    return redirect()->route('receipt',['Type'=>$src]);
                }

            } catch (\Exception $e) {

                return redirect()->route('receipt',['Type'=>$src])->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
            }

            }

            public function edittransaction(Request $request)
            {
               // Validate the request data
               $request->validate([
                'source' => 'required|string',
                'AccCode' => 'required|string',
                'date' => 'required|string',
                'narr' => 'required|string',
                'account' => 'required|string',
                'amount' => 'required|string',
                'gl' => 'required|string',
                'id' => 'required|string',
                'mdes' => 'required|string',
                'batch' => 'required|string',

                'curr' => 'required|string'
            ]);

            $Rate=1;
            $mdes = $request->input('mdes');
            $curr = $request->input('curr');
            $id=$request->input('id');
            $disc="0";
            $src = $request->input('source');
            $AccCode = $request->input('AccCode');
            $date = $request->input('date');
            $narr = $request->input('narr');
            $reff = $request->input('reff');
            if($reff==null || $reff=="")
            {
                $reff="0";
            }
            $amount = $request->input('amount');
            $price ="0";
            $AccSubCode = $request->input('account');
            $tax="0";
            $taxid="0";
            $qty = "0";
            $gl = $request->input('gl');
            $batch=$request->input('batch');
            $user=Session::get('RegNo');

            $parts = explode('/', $gl);
            $ContraCode = $parts[0];
            $ContraSubCode = isset($parts[1]) ? $parts[1] : '0';
            $DR=$amount;

            $CR="0";
            $total="0";

            $selectHomeCurrency=modelReceipt::selectHomeCurrency(Session::get('PropertyCode'));
            if(count($selectHomeCurrency)>0)
            {

                $homeCurrency=$selectHomeCurrency[0]->Currency;
                if($curr==$homeCurrency)
                {

                }
                else
                {

                    $selectRate=modelReceipt::selectRate(Session::get('PropertyCode'),$curr);

                    if(count($selectRate)>0)
                    {

                        $Rate=$selectRate[0]->Rate;

                        $DR= $DR/$Rate;

                    }
                    else
                    {
                        return redirect()->route('receipt',['Type'=>$src])->withErrors(['error' => 'No rate set for this currency' ]);

                    }

                }

            }
            else
            {
                return redirect()->route('receipt',['Type'=>$src])->withErrors(['error' => 'Home Currency Not Found' ]);

            }




                    try
                    {

                        modelReceipt::updateTransactionMdes(Session::get('PropertyCode'),$batch,$mdes,$src);
                    $result = modelReceipt::updateTransaction($id,Session::get('PropertyCode'),$date,$AccCode,$AccSubCode,$ContraCode,$ContraSubCode,$narr,$reff, $DR,$CR,$user,$src,$tax,$taxid,$disc,$qty,$price,$total,$batch,$curr,$Rate,$mdes,"Receipt");
                    if ($result)
                    {
                         return redirect()->route('receipt',['Type'=>$src]);
                   }
                    else
                    {
                        return redirect()->route('receipt',['Type'=>$src]);
                    }

                } catch (\Exception $e) {

                    return redirect()->route('receipt',['Type'=>$src])->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
                }

                }

            public function deletereceipt($id,$type)
            {


                try
                                {


                                $exists = DB::table('transactionsjob')->where('ID', $id)->exists();

                                if ($exists)
                                {


                                $result =modelReceipt::deleteTransaction($id);

                                if ($result)
                                {
                                     return redirect()->route('receipt',['Type'=>$type]);
                               }
                                else
                                {
                                    return redirect()->route('receipt',['Type'=>$type]);
                                }


                                }
                                else
                                {

                                    return redirect()->route('receipt',['Type'=>$type]);


                                }



                            } catch (\Exception $e) {

                                return redirect()->route('receipt',['Type'=>$type])->withErrors(['error' => 'An error occurred!!' . $e->getMessage()]);
                            }

            }
}
