<?php

namespace App\Http\Controllers;
use App\Models\modelInvoice;
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 InvoiceController extends Controller
{

    public function printinvoice($type, $invoice)
{
    $results = modelInvoice::ValidateTransactions(Session::get('PropertyCode'), Session::get('RegNo'), $type, $invoice);

    if (count($results) > 0) {
        $Bankaccounts = modelInvoice::selectBanks(Session::get('PropertyCode'));

        // ✅ Only update invoice generation if NOT a supplier
        if ($type != 'Supplier') {
            modelInvoice::UpdateGenInvoice($type, Session::get('PropertyCode'));
        }

        // ✅ Process transaction and delete job (works for all types)
        modelInvoice::processTransaction($type, $invoice, Session::get('PropertyCode'));
        modelInvoice::deleteTransactionJobs(Session::get('PropertyCode'), $type, $invoice);
        // Continue with invoice rendering
        $cst = modelInvoice::selectInvoiceCustomer(Session::get('PropertyCode'), $type, $invoice);
        $pdetails = modelInvoice::selectInvoiceProperty(Session::get('PropertyCode'), Session::get('RegNo'));
        $Jts = modelInvoice::selectInvoiceTransactions(Session::get('PropertyCode'), $type, $invoice);
        // Totals
        $totalExcludingTax = 0;
        $totalIncludingTax = 0;
        $totalDiscounts = 0;
        $totalTaxAmount = 0;
        $symbol = "";

        foreach ($Jts as $Jt) {
            $symbol = $Jt->Symbol;
            $itemTotalExcludingTax = ($Jt->Qnty * $Jt->Price);
            $itemDiscount = ($itemTotalExcludingTax * $Jt->Discount / 100);
            $itemTaxAmount = (($itemTotalExcludingTax - $itemDiscount) * ($Jt->Tax / 100));
            $itemTotalIncludingTax = ($itemTotalExcludingTax - $itemDiscount) + $itemTaxAmount;
            $totalDiscounts += $itemDiscount * $Jt->Rate;
            $totalExcludingTax += $itemTotalExcludingTax * $Jt->Rate;
            $totalTaxAmount += $itemTaxAmount * $Jt->Rate;
            $totalIncludingTax += $itemTotalIncludingTax * $Jt->Rate;
        }

        return view('/PrintInvoice', compact('invoice', 'Jts', 'totalExcludingTax', 'totalIncludingTax', 'totalTaxAmount', 'totalDiscounts', 'cst', 'pdetails', 'type', 'symbol', 'Bankaccounts'));
    } else {
        return redirect()->route('invoice', ['Type' => $type]);
    }
}
    public function index($Type)
    {
        try
        {
            $journal = "";
            $batch = "";
            $taxs = modelInvoice::selectTax(Session::get('PropertyCode'));

            if($Type == "Customer")

            {
                $PermissionsAddInvoice = PermissionsUserModel::getPermission('Add Customer Invoice', Auth::user()->id);
                $PermissionsEditInvoice = PermissionsUserModel::getPermission('Edit Customer Invoice', Auth::user()->id);
                $PermissionsDeleteInvoice = PermissionsUserModel::getPermission('Delete Customer Invoice', Auth::user()->id);

                $batchs = modelInvoice::cselectbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                if (count($batchs) == 0)

                {
                    // Handle no batch case if necessary
                }
                else
                {
                    $exists = DB::table('customerinvoicegenaration')->where('Status', '0')->exists();
                    if (!$exists)
                    {
                        modelInvoice::cGenbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                    }
                }

                $batchs = modelInvoice::cselectbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                $batch = $batchs[0]->ID;
                if ($batch < 1000)
                {
                    $batch = "CUS000" . ($batch + 1);
                }
                else
                {
                    $batch = "CUS" . ($batch + 1);
                }
            }
            else if ($Type == "Tenant")
            {
                $PermissionsAddInvoice = PermissionsUserModel::getPermission('Add Tenants Invoices', Auth::user()->id);
                $PermissionsEditInvoice = PermissionsUserModel::getPermission('Edit Tenants Invoices', Auth::user()->id);
                $PermissionsDeleteInvoice = PermissionsUserModel::getPermission('Delete Tenants Invoices', Auth::user()->id);

                $batchs = modelInvoice::selectbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                if (count($batchs) == 0)
                {
                    // Handle no batch case if necessary
                }
                else
                {
                    $exists = DB::table('invoicegenaration')->where('Status', '0')->exists();
                    if (!$exists)
                    {
                        modelInvoice::Genbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                    }
                }

                $batchs = modelInvoice::selectbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                $batch = $batchs[0]->ID;
                if ($batch < 1000)
                {
                    $batch = "INV000" . ($batch + 1);
                }
                else
                {
                    $batch = "INV" . ($batch + 1);
                }
            }
            else if ($Type == "Supplier")
            {
                $PermissionsAddInvoice = PermissionsUserModel::getPermission('Add Supplier Invoice', Auth::user()->id);
                $PermissionsEditInvoice = PermissionsUserModel::getPermission('Edit Supplier Invoice', Auth::user()->id);
                $PermissionsDeleteInvoice = PermissionsUserModel::getPermission('Delete Supplier Invoice', Auth::user()->id);


                $batchs = modelInvoice::selectbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                if (count($batchs) == 0)
                {
                    // Handle no batch case if necessary
                }
                else
                {
                    $exists = DB::table('invoicegenaration')->where('Status', '0')->exists();
                    if (!$exists)
                    {
                        modelInvoice::Genbatch(Session::get('PropertyCode'), Session::get('RegNo'));
                    }
                }

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

            $currencys = modelInvoice::selectcurrency(Session::get('PropertyCode'));
            $gls = modelInvoice::selectgl(Session::get('PropertyCode'));
            $Accounts = modelInvoice::selectTenants(Session::get('PropertyCode'));
            $Jts = modelInvoice::selectJournalTransactions(Session::get('PropertyCode'), Session::get('RegNo'), $Type);
            $totalExcludingTax = 0;
            $totalIncludingTax = 0;
            $totalDiscounts = 0;
            $totalTaxAmount = 0;
            $symbol = "";
            $mdes = "";
            foreach ($Jts as $Jt)
            {
                $symbol = $Jt->Symbol;
                $itemTotalExcludingTax = ($Jt->Qnty * $Jt->Price);
                $itemTaxAmount = ($itemTotalExcludingTax - (($Jt->Qnty * $Jt->Price) * ($Jt->Discount / 100))) * ($Jt->Tax / 100);
                $itemTotalIncludingTax = ($itemTotalExcludingTax - (($Jt->Qnty * $Jt->Price) * ($Jt->Discount / 100))) + $itemTaxAmount;
                $totalDiscounts = $totalDiscounts + ((($Jt->Qnty * $Jt->Price) * ($Jt->Discount / 100)) * $Jt->Rate);
                $totalExcludingTax += $itemTotalExcludingTax * $Jt->Rate;
                $totalTaxAmount += $itemTaxAmount * $Jt->Rate;
                $totalIncludingTax += $itemTotalIncludingTax * $Jt->Rate;
                if ($Jt->Source == "Supplier")
                {
                    $batch = $Jt->Batch;
                }
                $mdes = $Jt->MNarration;
            }

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

            if ($JournalType == "Tenant")
            {
                $Accounts = modelInvoice::selectTenants(Session::get('PropertyCode'));
                $journal = $Accounts[0]->AccCode;
            }
            else if ($JournalType == "Customer")
            {
                $Accounts = modelInvoice::selectCustomers(Session::get('PropertyCode'));
                $journal = $Accounts[0]->AccCode;
            }
            else if ($JournalType == "Supplier")
            {
                $Accounts = modelInvoice::selectSuppliers(Session::get('PropertyCode'));
                $journal = $Accounts[0]->AccCode;
            }


            return view('/Invoice', compact('JournalType', 'Accounts', 'journal', 'Jts', 'taxs', 'gls', 'batch', 'totalExcludingTax', 'totalIncludingTax', 'totalTaxAmount', 'totalDiscounts', 'currencys', 'symbol', 'mdes', 'PermissionsAddInvoice', 'PermissionsEditInvoice', 'PermissionsDeleteInvoice'));

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

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

                $Rate=1;
                $mdes = $request->input('mdes');
                $curr = $request->input('curr');
                $id= $request->input('id');
                $disc= $request->input('disc');
                $src = $request->input('source');
                $AccCode = $request->input('AccCode');
                $date = $request->input('date');
                $narr = $request->input('narr');
                $reff = $request->input('reff');
                $price = $request->input('price');
                $AccSubCode = $request->input('account');
                $taxs = $request->input('tax');
                $taxs = explode(':', $taxs);
                $taxid = $taxs[0];
                $tax = isset($taxs[1]) ? $taxs[1] : '0';

                $qty = $request->input('qty');
                $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="0";
                //distribute the cost
                if ($request->filled('customCheck')) {
                    $SelectSpace=modelInvoice::selectSpace(Session::get('PropertyCode'),$AccSubCode);
                    $PropertySpace=$SelectSpace[0]->PropertySpace;
                    $TenantSpace=$SelectSpace[0]->TenantSpace;
                    if($PropertySpace==null || $PropertySpace=="" || $TenantSpace==null || $TenantSpace=="")
                    {
                        return redirect()->route('invoice',['Type'=>$src])->withErrors(['error' => 'Space Not Set' ]);

                    }
                    else
                    {
                    $price=($TenantSpace/$PropertySpace)*$price;
                    }

                }

                $CR=(($price-($price*($disc/100)))*$qty)+((($price-($price*($disc/100)))*$qty)*($tax/100));
                $total=($price*$qty);
                $selectHomeCurrency=modelInvoice::selectHomeCurrency(Session::get('PropertyCode'));
                if(count($selectHomeCurrency)>0)
                {
                    $homeCurrency=$selectHomeCurrency[0]->Currency;
                    if($curr==$homeCurrency)
                    {

                    }
                    else
                    {

                        $selectRate=modelInvoice::selectRate(Session::get('PropertyCode'),$curr);
                        if(count($selectRate)>0)
                        {

                            $Rate=$selectRate[0]->Rate;
                            $CR= $CR/$Rate;
                            $total=$total/$Rate;
                            $price=$price/$Rate;

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

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

                }
                try
                {

                modelInvoice::updateTransactionMdes(Session::get('PropertyCode'),$batch,$mdes,$src);
                $result = modelInvoice::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,"Invoice");
                if ($result)
                {

                     return redirect()->route('invoice',['Type'=>$src]);
               }
                else
                {
                    return redirect()->route('invoice',['Type'=>$src]);
                }

            } catch (\Exception $e) {

                return redirect()->route('invoice',['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',
                        'reff' => 'required|string',
                        'price' => 'required|string',
                        'account' => 'required|string',
                        'qty' => 'required|string',
                        'gl' => 'required|string',
                        'batch' => 'required|string',
                        'disc' => 'required|string',
                        'id' => 'required|string',
                        'curr' => 'required|string',
                        'mdes' => 'required|string',
                        'tax' => 'required|string'
                    ]);

                    $Rate=1;
                    $mdes = $request->input('mdes');
                    $curr = $request->input('curr');
                    $id= $request->input('id');
                    $disc= $request->input('disc');
                    $src = $request->input('source');
                    $AccCode = $request->input('AccCode');
                    $date = $request->input('date');
                    $narr = $request->input('narr');
                    $reff = $request->input('reff');
                    $price = $request->input('price');
                    $AccSubCode = $request->input('account');
                    $taxs = $request->input('tax');
                    $taxs = explode(':', $taxs);
                    $taxid = $taxs[0];
                    $tax = isset($taxs[1]) ? $taxs[1] : '0';
                    $qty = $request->input('qty');
                    $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="0";
                    $CR=(($price-($price*($disc/100)))*$qty)+((($price-($price*($disc/100)))*$qty)*($tax/100));
                    $total=($price*$qty);
                    $selectHomeCurrency=modelInvoice::selectHomeCurrency(Session::get('PropertyCode'));
                    if(count($selectHomeCurrency)>0)
                    {

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

                        }
                        else
                        {

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

                            if(count($selectRate)>0)
                            {

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

                                $CR= $CR/$Rate;
                                $total=$total/$Rate;
                                $price=$price/$Rate;

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

                            }

                        }

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

                    }

                    try
                    {

                        modelInvoice::updateTransactionMdes(Session::get('PropertyCode'),$batch,$mdes,$src);
                    $result = modelInvoice::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,"Invoice");
                    if ($result)
                    {
                         return redirect()->route('invoice',['Type'=>$src]);
                   }
                    else
                    {
                        return redirect()->route('invoice',['Type'=>$src]);
                    }

                } catch (\Exception $e) {

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

                }

            public function deleteinvoice($id,$type)
            {

                try
                                {


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

                                if ($exists)
                                {

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

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


                                }
                                else
                                {

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

                                }

                            } catch (\Exception $e) {

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

            }
}
