<?php

namespace App\Http\Controllers;
use App\Models\modelProcessCashBook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
class ProcessCashBookController extends Controller
{
  public function index($type = null)
{
    try {
        // Fetch GLs and currencies (unchanged)
        $gls = modelProcessCashBook::selectgl(Session::get('PropertyCode'));
        $currencys = modelProcessCashBook::selectcurrency(Session::get('PropertyCode'));

        // Initialize $Accounts as empty array
        $Accounts = [];

        // Validate and fetch accounts based on $type
        if ($type === 'GL') {
            $Accounts = modelProcessCashBook::selectgls(Session::get('PropertyCode'));
        } elseif ($type === 'Suppliers') {
            $Accounts = modelProcessCashBook::selectSuppliers(Session::get('PropertyCode'));
        }

        return view('ProcessCashBook', compact('gls', 'currencys', 'Accounts', 'type'));

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

        public function savetransaction(Request $request)
        {
           // Validate the request data
                $request->validate([

                    'date' => 'required|string',
                    'narr' => 'required|string',
                    'account' => 'required|string',
                    'amount' => 'required|string',
                    'reff' => 'required|string',
                    'tr' => 'required|string',
                    'contra' => 'required|string',
                    'curr' => 'required|string'
                ]);

                $ContraCode ="0";
                $ContraSubCode = "0";


                $contra = $request->input('contra');

                if($contra=="Reff")
                {

                    $TransReff=modelProcessCashBook::selectTransReff(Session::get('PropertyCode'),($request->input('reff')));
                if(count($TransReff)>0)
                {

                    $ContraCode =$TransReff[0]->Accode;
                    $ContraSubCode = $TransReff[0]->AccSubCode;

                }

                else
                {

                    return redirect()->route('ProcessCashBook')->withErrors(['error' => 'Refference Not Found' ]);
                }


                }
                else
                {


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

            }

                $Rate=1;
                $curr = $request->input('curr');
                $tr = $request->input('tr');
                $id= "0";
                $disc="0";
                $src = "CashBook";
                $AccCode = $request->input('account');
                $date = $request->input('date');
                $narr = $request->input('narr');
                $reff = $request->input('reff');
                $amount =  $request->input('amount');
                $price ="0";
                $AccSubCode = "0";
                $tax="0";
                $taxid="0";
                $qty = "0";
                $gl = "0";
                $batch="CashBook";
                $mdes="CashBook";
                $user=Session::get('RegNo');
                $DR=$amount;
                $CR=0;
                $total="0";
                $selectHomeCurrency=modelProcessCashBook::selectHomeCurrency(Session::get('PropertyCode'));

                if(count($selectHomeCurrency)>0)
                {


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


                    if($curr==$homeCurrency)
                    {

                    }
                    else
                    {

                        $selectRate=modelProcessCashBook::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('ProcessCashBook')->withErrors(['error' => 'Home Currency Not Found' ]);

                }


                if($tr=="DR")
                {


                    $CR=$DR;
                    $DR="0";


                }
                else
                if($tr=="CR")
                {

                    $CR="0";
                    $DR=$DR;


                }


                try
                {

                $result = modelProcessCashBook::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,"CashBook");
                if ($result)
                {
                     return redirect()->route('ProcessCashBook')->with('success', 'Proccessed Successfully.');
               }
                else
                {
                    return redirect()->route('ProcessCashBook')->withErrors(['error' => 'Failed to Proccess.']);
                }

            } catch (\Exception $e) {

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

            }
}
