<?php

namespace App\Http\Controllers;
use App\Models\Capital;
use App\Models\CapitalIncrease;
use App\Models\Investors;
use App\Models\Partners;
use App\Models\ProductMoves;
use App\Models\ProductSales;
use App\Models\ProductsStartPeriods;
use App\Models\Sales;
use App\Models\SpendProfits;
use App\Models\StartPeriods;
use App\Models\UpdateValuesInvestors;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use DateTime;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

use App\Models\AcccountingManual;
use App\Models\UsersMoves;
use App\Models\CostCenter;
use App\Models\Coins;
use App\Models\Branches;
use App\Models\Journalizing;
use App\Models\JournalizingDetails;
use App\Models\GeneralDaily;
use App\Models\Admin;
use App\Models\PaymentVoucher;
use App\Models\PaymentVoucherDetails;
use App\Models\ReciptVoucher;
use App\Models\ReciptVoucherDetails;
use App\Models\OpeningEntries;
use App\Models\OpeningEntriesDetails;
use App\Models\ChecksTypes;
use App\Models\ExportChecks;
use App\Models\IncomChecks;
use App\Models\ShippingCompany;
use App\Models\SafesBanks;
use App\Models\Stores;
use App\Models\SafeTransfers;
use App\Models\ItemsGroups;
use App\Models\Employess;
use App\Models\Vendors;
use App\Models\Customers;
use App\Models\AssetsExpenses;
use App\Models\Assets;
use App\Models\Taxes;
use App\Models\CrmDefaultData;
use App\Models\InsurancePaper;
use App\Models\SalesDefaultData;
use App\Models\AccountsDefaultData;
use App\Models\PurchasesDefaultData;
use App\Models\StoresDefaultData;
use App\Models\Event;
use App\Models\Notifications;
use App\Models\CompanyData;
use App\Models\OrderPay;

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

use App\Traits\GeneralTrait;

use App\Events\IncomCheckEvent;
use App\Events\ExportChecksEvent;
use App\Events\CreateAccountManualEvent;
use App\Events\EditAccountManualEvent;
use App\Events\DeleteAccountManualEvent;
use App\Events\AddJournalizingEvent;
use App\Events\SureJournalizingEvent;
use App\Events\AddReciptVoucherEvent;
use App\Events\SureReciptVoucherEvent;
use App\Events\AddPaymentVoucherEvent;
use App\Events\SurePaymentVoucherEvent;
use App\Events\AddOpeningEntriesEvent;
use App\Events\SureOpeningEntriesEvent;
use App\Events\InsurancePaperEvent;
use App\Events\AssetsMonthlyEvent;
use App\Events\AssetsEvent;

use App\Http\Requests\ChecksRequest;
use App\Http\Requests\ArEnRequest;
use App\Http\Requests\CoinRequest;
use App\Http\Requests\JournalizingRequest;
use App\Http\Requests\VoucherRequest;
use App\Http\Requests\OpeningRequest;
use App\Http\Requests\InsurancePaperRequest;
use App\Http\Requests\SafeTransferRequest;
use App\Http\Requests\AssetsRequest;

use App\Services\ChecksService;
class AccountsController extends Controller
{
  use GeneralTrait;
    function __construct()
    {

    $this->middleware('permission:الدليل المحاسبي', ['only' => ['AccountingManualPage','AddAccount','EditAccount','DeleteAccount']]);
    $this->middleware('permission:مراكز التكلفه', ['only' =>['CostCentersPage','AddCostCenters','EditCostCenters','DeleteCostCenters']]);
    $this->middleware('permission:العملات', ['only' =>['CoinsPage','AddCoins','EditCoins','DeleteCoins']]);
    $this->middleware('permission:انواع الشيكات', ['only' =>['Checks_TypePage','AddChecks_Type','EditChecks_Type','DeleteChecks_Type']]);
    $this->middleware('permission:اضافه قيد يومي', ['only' =>['JournalizingPage','AddJournalizing','JournalizingPrint']]);
    $this->middleware('permission:جدول القيود اليوميه', ['only' =>['JournalizingSechdule','EditJournalizing','DeleteJournalizing','PostEditJournalizing']]);
    $this->middleware('permission:اضافه سند قبض', ['only' =>['Receipt_VoucherPage','AddReceipt_Voucher','Receipt_VoucherPrint']]);
    $this->middleware('permission:جدول سند القبض', ['only' =>['Receipt_VoucherSechdule','EditReceipt_Voucher','DeleteReceipt_Voucher','PostEditReceipt_Voucher']]);
    $this->middleware('permission:اضافه سند صرف', ['only' =>['Payment_VoucherPage','AddPayment_Voucher','Payment_VoucherPrint']]);
    $this->middleware('permission:جدول سند الصرف', ['only' =>['Payment_VoucherSechdule','EditPayment_Voucher','DeletePayment_Voucher','PostEditPayment_Voucher']]);
    $this->middleware('permission:اضافه قيد افتتاحي', ['only' =>['OpeningEntriesPage','AddOpeningEntries','Opening_EntriesPrint']]);
    $this->middleware('permission:جدول القيود الافتتاحيه', ['only' =>['Opening_EntriesSechdule','EditOpening_Entries','DeleteOpening_Entries','PostEditOpening_Entries']]);
    $this->middleware('permission:الشيكات الصادره', ['only' =>['Exporting_ChecksPage','AddExporting_Checks','EditExporting_Checks','DeleteExportingChecks','ReasonExportChecks','TransExportingChecks','PayExportingChecks']]);
    $this->middleware('permission:الشيكات الوارده', ['only' =>['Incoming_checksPage','AddIncoming_checks','EditIncoming_checks','DeleteIncoming_checks','ReasonIncoming_checks','TransIncoming_checks','PayIncomingChecks']]);
    $this->middleware('permission:الخزائن و البنوك', ['only' =>['Safes_BanksPage','AddSafes_Banks','EditSafes_Banks','DeleteSafes_Banks']]);
    $this->middleware('permission:الاصول', ['only' =>['AssetsPage','AddAssets','DeleteAssets']]);
    $this->middleware('permission:تحويلات الخزائن', ['only' =>['SafesTransferPage','AddSafeTransfer']]);
    $this->middleware('permission:جدول تحويلات الخزائن', ['only' =>['SafesTransferSechdulePage']]);
    $this->middleware('permission:مصاريف اصول', ['only' =>['AssetExpensesPage','AddAssetsExpenses']]);
    $this->middleware('permission:وصل امانه', ['only' =>['Insurance_PaperPage','AddInsurancePaper','DeleteInsurancePaper','RecivedInurance']]);

        $this->middleware('permission:المستثمرين', ['only' =>['Investors']]);
        $this->middleware('permission:اضافه راس المال', ['only' =>['CapitalPage']]);
        $this->middleware('permission:صرف ارباح', ['only' =>['Spend_ProfitsPage']]);
        $this->middleware('permission:الشركاء', ['only' =>['PartnersPage']]);
        $this->middleware('permission:تقرير راس المال', ['only' =>['CapitalReport']]);
        $this->middleware('permission:جدول اوامر الدفع', ['only' =>['Order_PaySechdule']]);
        $this->middleware('permission:امر دفع', ['only' =>['Order_Pay']]);





    }

    // === Accounting Manual =====
    public function AccountingManualPage(){
    $parents=AcccountingManual::orderBy('Code','asc')->where('Parent',0)->get();
        $parentss=AcccountingManual::orderBy('Code','asc')->get();
    $Groups=ItemsGroups::all();
    $Def=AccountsDefaultData::orderBy('id','desc')->first();
    $DefC=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Accounting_Manual');


        return view('admin.Accounts.AccountingManual',get_defined_vars());
    }

    public function AddAccount(){

    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Name'=>'required',
    'Type'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    'Type.required' => trans('admin.AccountTypeRequired'),
    ]);



    if(!empty(request('Parent'))){
    $data['Parent']=request('Parent');

    $count=AcccountingManual::orderBy('Code','desc')->where('Parent',request('Parent'))->count(); //  عدد الحسابات اللي تحت الحساب اللي هنشئ تحته
    $code=AcccountingManual::orderBy('Code','desc')->where('Parent',request('Parent'))->first();  //  اخر كود موجود لحساب تحت نفس الحساب
    $codee=AcccountingManual::find(request('Parent'));  // كود نفس الحساب

    if($count == 0){   // لو اجمالي العدد ده بصفر

    $x=$codee->Code.'01';   // يبقي هناخد كود الحساب الرئيسي و نزود عليه ٠١
    $data['Code']=(int) $x ; // و نخزنه في الفايربل

    }else{    //لو تحتيه حسابات تانيه


    $y=substr($code->Code, strlen($codee->Code));  // باخد اخر رقمين من الكود بتاع الحساب الاخير
    $newY=$y + 1 ;  // ازود عليه ١

    if(strlen($newY) == 1){ // لو مجموعه ١
    $NewXY='0'.$newY;  // هزود قبله صفر
    }else{
    $NewXY=$newY;  // لو لا هناخدة زي ما هو
    }
    $x= $codee->Code.$NewXY;  // و نخزنه في فايربل



    $data['Code']=(int) $x;

    }


    }else{

    $data['Parent']=0;
    $code=AcccountingManual::orderBy('id','desc')->where('Parent',0)->first();

    if(!empty($code)){
    $data['Code']=$code->Code + 1 ;
    }else{

    $data['Code']=1;
    }

    }

    if(!empty(request('NameEn'))){

    $english_name=request('NameEn');
    }else{

    $english_name=request('Name');
    }


    $data['Name']=request('Name');
    $data['NameEn']=$english_name;
    $data['Type']=request('Type');
    $data['Note']=request('Note');
    $data['Account_Code']=request('Account_Code');
    $data['Pro_Group']=request('Pro_Group');
    $data['User']=auth()->guard('admin')->user()->id;
    AcccountingManual::create($data);


    //Event to Create Safe or Store or Client ... etc
    $item=AcccountingManual::latest('id')->first();
    CreateAccountManualEvent::dispatch($item);



    $dataUser=[
    'screen_ar'=>'الدليل المحاسبي',
    'screen_en'=>'Accounting Manual',
    'explain_ar'=>request('Name'),
    'explain_en'=>$english_name,
    ];
    $this->UserCreateMoves($dataUser);


    DB::commit();
    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=AcccountingManual::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=AcccountingManual::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function EditAccount(){

    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Name'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    ]);

    $data['Name']=request('Name');
    $data['NameEn']=request('NameEn');
    $data['Note']=request('Note');
    $data['Account_Code']=request('Account_Code');
    $data['Pro_Group']=request('Pro_Group');



        if(!empty(request('Parent'))){
            $data['Parent']=request('Parent');

            $count=AcccountingManual::orderBy('Code','desc')->where('Parent',request('Parent'))->count();
            $code=AcccountingManual::orderBy('Code','desc')->where('Parent',request('Parent'))->first();
            $codee=AcccountingManual::find(request('Parent'));

            if($count == 0){

                $x=$codee->Code.'01';
                $data['Code']=(int) $x ;

            }else{


                $y=substr($code->Code, strlen($codee->Code));
                $newY=$y + 1 ;

                if(strlen($newY) == 1){
                    $NewXY='0'.$newY;
                }else{
                    $NewXY=$newY;
                }
                $x= $codee->Code.$NewXY;



                $data['Code']=(int) $x;

            }


        }else{

            $data['Parent']=0;
            $code=AcccountingManual::orderBy('id','desc')->where('Parent',0)->first();

            if(!empty($code)){
                $data['Code']=$code->Code + 1 ;
            }else{

                $data['Code']=1;
            }

        }



    AcccountingManual::where('id',request('ID'))->update($data);


    $item=AcccountingManual::findOrFail(request('ID'));
    EditAccountManualEvent::dispatch($item);



    $dataUser=[
    'screen_ar'=>'الدليل المحاسبي',
    'screen_en'=>'Accounting Manual',
    'explain_ar'=>request('Name'),
    'explain_en'=>request('NameEn'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();


    session()->flash('success',trans('admin.Updated'));
    return back();

    }catch(\Exception $ex){

    $MODEL=AcccountingManual::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=AcccountingManual::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function DeleteAccount(){

    try {
    DB::beginTransaction();

     $id=request('Parent');
    $count=AcccountingManual::orderBy('id','desc')->where('Parent',$id)->count();
    $xh=GeneralDaily::where('Account',$id)->orderBy('id','desc')->first();

    if($count != 0){

    session()->flash('error',trans('admin.U_Cant_Delete_Any_Account_Has_Traffic'));
    return back();

    }
    if(!empty($xh)){

    session()->flash('error',trans('admin.CantDeleteAnyItemHasTraffic'));
    return back();

    }


    $del=AcccountingManual::findOrFail($id);

    //Event to delete safe and store .. etc
    DeleteAccountManualEvent::dispatch($del);

    $dataUser=[
    'screen_ar'=>'الدليل المحاسبي',
    'screen_en'=>'Accounting Manual',
    'explain_ar'=>$del->Name,
    'explain_en'=>$del->NameEn,
    ];
    $this->UserDeleteMoves($dataUser);
    $del->delete();
    DB::commit();
    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=AcccountingManual::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=AcccountingManual::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }


    function SupAccountFilter(Request $request)
    {

        if($request->ajax())
        {
            $output = '';
            $parent = $request->get('Parent');


            if($parent != '')
            {



                $Childs=AcccountingManual::oldest('Code')->where('Parent',$parent)->get();


            }


            $total_row = $Childs->count();
            if($total_row > 0)
            {

                foreach($Childs as $child){

                    if( app()->getLocale() == 'ar'){
                        $name=$child->Name;
                    }else{
                        $name=$child->NameEn;
                    }

                    $output .= '



   <li class="parent_li">


     <span onclick="SupGroups('.$child->id.')"><i class="fal fa-folder"></i>
    ('.$child->Code.') - ('.$name.')
     </span>




               <ul class="Data'.$child->id.'">




                  </ul>




    </li>


    ';


                }

            }
            else
            {
                $output = '
    <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
    ';
            }
            $data = array(
                'table_data' => $output,

            );
            echo json_encode($data);
        }
    }

    function EditAccountFilter(Request $request)
    {

        $group=request('group');

        $item=AcccountingManual::findOrFail($group);


        if(!empty($item->Parent()->first()->Name)){
            $Parent=$item->Parent()->first()->Name;
        }else{
            $Parent=0;
        }

        if(!empty($item->Pro_Group()->first()->Name)){
            $Pro_Group=$item->Pro_Group()->first()->Name;
        }else{
            $Pro_Group=0;
        }


        $states=[
            'Name'=>$item->Name,
            'NameEn'=>$item->NameEn,
            'Account_Code'=>$item->Account_Code,
            'Note'=>$item->Note,
            'Pro_Group'=>$item->Pro_Group,
            'Pro_Group_Name'=>$Pro_Group,
            'Parent'=>$item->Parent,
            'Parent_Name'=>$Parent,


        ];

        return response()->json($states);


    }




    //====== Cost Centers =======
    public function CostCentersPage(){
    $items=CostCenter::lazy()->all();
    return view('admin.Accounts.CostCenters',['items'=>$items]);
    }

    public function AddCostCenters(ArEnRequest $vali){


    try {

    DB::beginTransaction();

    $validated = $vali->validated();

    if(!empty(request('English_Name'))){

    $english_name=request('English_Name');
    }else{

    $english_name=request('Arabic_Name');
    }


    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=$english_name;
    CostCenter::create($data);

    $dataUser=[
    'screen_ar'=>'مراكز التكلفه',
    'screen_en'=>'Cost Centers',
    'explain_ar'=>request('Arabic_Name'),
    'explain_en'=>$english_name,
    ];
    $this->UserCreateMoves($dataUser);

    DB::commit();
    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=CostCenter::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=CostCenter::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function EditCostCenters(ArEnRequest $vali,$id){


    try {

    DB::beginTransaction();

    $validated = $vali->validated();

    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=request('English_Name');
    CostCenter::where('id',$id)->update($data);

    $dataUser=[
    'screen_ar'=>'مراكز التكلفه',
    'screen_en'=>'Cost Centers',
    'explain_ar'=>request('Arabic_Name'),
    'explain_en'=>request('English_Name'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();
    session()->flash('success',trans('admin.Updated'));
    return back();


    }catch(\Exception $ex){

    $MODEL=CostCenter::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=CostCenter::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }




    }

    public function DeleteCostCenters($id){

    try {

    DB::beginTransaction();

    $del=CostCenter::findOrFail($id);

    $dataUser=[
    'screen_ar'=>'مراكز التكلفه',
    'screen_en'=>'Cost Centers',
    'explain_ar'=>$del->Arabic_Name,
    'explain_en'=>$del->English_Name,
    ];
    $this->UserDeleteMoves($dataUser);


    $del->delete();

    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=CostCenter::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=CostCenter::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }


    //====== Coins =======
    public function CoinsPage(){
    $items=Coins::lazy()->all();
    return view('admin.Accounts.Coins',['items'=>$items]);
    }

    public function AddCoins(CoinRequest $vali){

    try {
    DB::beginTransaction();

    $validated = $vali->validated();


    if(!empty(request('English_Name'))){

    $english_name=request('English_Name');
    }else{

    $english_name=request('Arabic_Name');
    }


    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=$english_name;
    $data['Draw']=request('Draw');
    $data['Symbol']=request('Symbol');
    $data['Code']=request('Code');
    Coins::create($data);



    $dataUser=[
    'screen_ar'=>'العملات',
    'screen_en'=>'Coins',
    'explain_ar'=>request('Arabic_Name'),
    'explain_en'=>$english_name,
    ];
    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=Coins::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Coins::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function EditCoins(CoinRequest $vali,$id){

    try {
    DB::beginTransaction();

    $validated = $vali->validated();

    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=request('English_Name');
    $data['Draw']=request('Draw');
    $data['Symbol']=request('Symbol');
    $data['Code']=request('Code');
    Coins::where('id',$id)->update($data);

    $dataUser=[
    'screen_ar'=>'العملات',
    'screen_en'=>'Coins',
    'explain_ar'=>request('Arabic_Name'),
    'explain_en'=>request('English_Name'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();


    session()->flash('success',trans('admin.Updated'));
    return back();

    }catch(\Exception $ex){

    $MODEL=Coins::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Coins::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }





    }

    public function DeleteCoins($id){


    try {
    DB::beginTransaction();

    $del=Coins::findOrFail($id);


    // Delete Default Data
    $defA=$this->DefaultDataDelete(AccountsDefaultData::class,$id,'Coin');
    $defSt=$this->DefaultDataDelete(StoresDefaultData::class,$id,'Coin');
    $defP=$this->DefaultDataDelete(PurchasesDefaultData::class,$id,'Coin');
    $defS=$this->DefaultDataDelete(SalesDefaultData::class,$id,'Coin');


    $result= $defA + $defSt + $defP + $defS ;

    if($result != 0){

    session()->flash('error',trans('admin.Cant_Delete_Default_Data'));
    return back();

    }



    $dataUser=[
    'screen_ar'=>'العملات',
    'screen_en'=>'Coins',
    'explain_ar'=>$del->Arabic_Name,
    'explain_en'=>$del->English_Name,
    ];
    $this->UserDeleteMoves($dataUser);

    $del->delete();


    DB::commit();
    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Coins::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Coins::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }





    }


    //====== Checks Types =======
    public function Checks_TypePage(){
    $items=ChecksTypes::lazy()->all();
    return view('admin.Accounts.ChecksTypes',['items'=>$items]);
    }

    public function AddChecks_Type(ArEnRequest $vali){


    try {
    DB::beginTransaction();


    $validated = $vali->validated();

    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=request('English_Name');
    ChecksTypes::create($data);



    $dataUser=[
    'screen_ar'=>'انواع الشيكات',
    'screen_en'=>'Checks Type',
    'explain_ar'=>request('Arabic_Name'),
    'explain_en'=>request('English_Name'),
    ];
    $this->UserCreateMoves($dataUser);

    DB::commit();
    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=ChecksTypes::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ChecksTypes::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }




    }

    public function EditChecks_Type(ArEnRequest $vali,$id){

    try {
    DB::beginTransaction();


    $validated = $vali->validated();

    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=request('English_Name');

    ChecksTypes::where('id',$id)->update($data);

    $dataUser=[
    'screen_ar'=>'انواع الشيكات',
    'screen_en'=>'Checks Type',
    'explain_ar'=>request('Arabic_Name'),
    'explain_en'=>request('English_Name'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return back();


    }catch(\Exception $ex){

    $MODEL=ChecksTypes::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ChecksTypes::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }




    }

    public function DeleteChecks_Type($id){


    try {
    DB::beginTransaction();

    $del=ChecksTypes::findOrFail($id);


    $dataUser=[
    'screen_ar'=>'انواع الشيكات',
    'screen_en'=>'Checks Type',
    'explain_ar'=>$del->Arabic_Name,
    'explain_en'=>$del->English_Name,
    ];
    $this->UserDeleteMoves($dataUser);

    $del->delete();

    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=ChecksTypes::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ChecksTypes::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }



    //====== Safes Banks =======
    public function Safes_BanksPage(){
    $items=SafesBanks::cursor();
    $Branches=Branches::cursor();
    $Code=$this->ReturnCode(SafesBanks::class);
    return view('admin.Accounts.SafesBanks',get_defined_vars());
    }

    public function AddSafes_Banks(){

    try {
    DB::beginTransaction();


    $data= $this->validate(request(),[
    'Name'=>'required',
    'Type'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    'Type.required' => trans('admin.TypeRequired'),
    ]);

    if(!empty(request('NameEn'))){

    $english_name=request('NameEn');
    }else{

    $english_name=request('Name');
    }


    if(request('Type') == 1){

    $ty=28;
    }else{

    $ty=29;
    }
    $Account_ID=$this->CreateAccount(request('Name'),$english_name,$ty,request('Note'));

    $dataa['Code']=request('Code');
    $dataa['Date']=date('Y-m-d');
    $dataa['Name']=request('Name');
    $dataa['NameEn']=$english_name;
    $dataa['Type']=request('Type');
    $dataa['Note']=request('Note');
    $dataa['Service_Fee']=request('Service_Fee');
    $dataa['Account']=$Account_ID;
    $dataa['User']=auth()->guard('admin')->user()->id;
    $dataa['Branch']=request('Branch');
    SafesBanks::create($dataa);



    $dataUser=[
    'screen_ar'=>'الخزائن و البنوك',
    'screen_en'=>'Safes and Banks',
    'explain_ar'=>request('Name'),
    'explain_en'=>$english_name,
    ];
    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=SafesBanks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafesBanks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function EditSafes_Banks($id){


    try {
    DB::beginTransaction();


    $data= $this->validate(request(),[
    'Name'=>'required',
    'Type'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    'Type.required' => trans('admin.TypeRequired'),
    ]);


    $safe=SafesBanks::find($id);
    AcccountingManual::where('id',$safe->Account)->update(['Name'=>request('Name'),'NameEn'=>request('NameEn'),'Note'=>request('Note')]);



    $dataa['Code']=request('Code');
    $dataa['Date']=request('Date');
    $dataa['Name']=request('Name');
    $dataa['NameEn']=request('NameEn');
    $dataa['Type']=request('Type');
    $dataa['Note']=request('Note');
    $dataa['Account']=request('Account');
    $dataa['User']=request('User');
    $dataa['Service_Fee']=request('Service_Fee');
    $dataa['Branch']=request('Branch');

    SafesBanks::where('id',$id)->update($dataa);


    $dataUser=[
    'screen_ar'=>'الخزائن و البنوك',
    'screen_en'=>'Safes and Banks',
    'explain_ar'=>request('Name'),
    'explain_en'=>request('NameEn'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return back();


    }catch(\Exception $ex){

    $MODEL=SafesBanks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafesBanks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }





    }

    public function DeleteSafes_Banks($id){


    try {
    DB::beginTransaction();

    $del=SafesBanks::findOrFail($id);

    // Delete Default Data
    $defP=$this->DefaultDataDelete(PurchasesDefaultData::class,$del->Account,'Safe');
    $defS=$this->DefaultDataDelete(SalesDefaultData::class,$del->Account,'Safe');
    $defB=$this->DefaultDataDelete(SalesDefaultData::class,$del->Account,'Bank');

    $result= $defP + $defS + $defB ;

    if($result != 0){

    session()->flash('error',trans('admin.Cant_Delete_Default_Data'));
    return back();

    }




    $dataUser=[
    'screen_ar'=>'الخزائن و البنوك',
    'screen_en'=>'Safes and Banks',
    'explain_ar'=>$del->Name,
    'explain_en'=>$del->NameEn,
    ];
    $this->UserDeleteMoves($dataUser);


    AcccountingManual::where('id',$del->Account)->delete();
    $del->delete();

    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();




    }catch(\Exception $ex){

    $MODEL=SafesBanks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafesBanks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }



    //====== Branches =======

    public function BranchesPage(){
    $items=Branches::all();
    return view('admin.Accounts.Branches',['items'=>$items]);
    }

    public function AddBranches(){

    try {
    DB::beginTransaction();



    $data= $this->validate(request(),[
    'Arabic_Name'=>'required',
    ],[
    'Arabic_Name.required' => trans('admin.Arabic_NameRequired'),
    ]);



    $result=$this->MaxUse('Branch_Select',Branches::class,'Branch_Num');
    if($result == 1){

    session()->flash('error',trans('admin.Alert_Maximum_Add'));
    return back();

    }


    if(!empty(request('English_Name'))){

    $english_name=request('English_Name');
    }else{

    $english_name=request('Arabic_Name');
    }


    $data['Arabic_Name']=request('Arabic_Name');
    $data['Letter']=request('Letter');
    $data['Location']=request('Location');
    $data['Code']=request('Code');
    $data['Budget']=request('Budget');
    $data['English_Name']=$english_name;

    Branches::create($data);

    $dataUser=[
    'screen_ar'=>'الفروع',
    'screen_en'=>'Branches',
    'explain_ar'=>request('Name'),
    'explain_en'=>$english_name,
    ];
    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=Branches::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Branches::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function EditBranches($id){


    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Arabic_Name'=>'required',
    ],[
    'Arabic_Name.required' => trans('admin.Arabic_NameRequired'),
    ]);


    $data['Location']=request('Location');
    $data['Letter']=request('Letter');
    $data['Code']=request('Code');
    $data['Budget']=request('Budget');
    $data['Arabic_Name']=request('Arabic_Name');
    $data['English_Name']=request('English_Name');
    Branches::where('id',$id)->update($data);

    $dataUser=[
    'screen_ar'=>'الفروع',
    'screen_en'=>'Branches',
    'explain_ar'=>request('Name'),
    'explain_en'=>request('English_Name'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return back();

    }catch(\Exception $ex){

    $MODEL=Branches::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Branches::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function DeleteBranches($id){

    try {
    DB::beginTransaction();

    $del=Branches::findOrFail($id);

    $dataUser=[
    'screen_ar'=>'الفروع',
    'screen_en'=>'Branches',
    'explain_ar'=>$del->Name,
    'explain_en'=>$del->NameEn,
    ];

    $this->UserDeleteMoves($dataUser);
    $del->delete();

    DB::commit();
    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Branches::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Branches::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

         //======  Taxes  =======
     public function TaxesPage(){
        $items=Taxes::all();
            $Code=$this->ReturnCode(Taxes::class);

         return view('admin.Accounts.Taxes',get_defined_vars());
    }

     public function AddTaxes(){

          try {
    DB::beginTransaction();

        $data= $this->validate(request(),[
             'Name'=>'required',
             'Rate'=>'required',
             'Type'=>'required',
               ],[
            'Name.required' => trans('admin.NameRequired'),
            'Rate.required' => trans('admin.RateRequired'),
            'Type.required' => trans('admin.Taxes_TypeRequired'),
         ]);


      if(!empty(request('NameEn'))){

         $english_name=request('NameEn');
         }else{

         $english_name=request('Name');
         }


        $Acc=$this->CreateAccount(request('Name'),$english_name,39,null);


         $data['Code']=request('Code');
         $data['Name']=request('Name');
         $dataa['NameEn']=$english_name;
         $data['Rate']=request('Rate');
         $data['Type']=request('Type');
         $data['CodeTax']=request('CodeTax');
         $data['SubType']=request('SubType');
         $data['Hide']=0;
         $data['Account']=$Acc;

         Taxes::create($data);


                  $dataUser=[
    'screen_ar'=>'الضرائب',
    'screen_en'=>'Taxes',
    'explain_ar'=>request('Name'),
    'explain_en'=>$english_name,
    ];
    $this->UserCreateMoves($dataUser);

                DB::commit();

             session()->flash('success',trans('admin.Added_Successfully'));
             return back();


             }catch(\Exception $ex){

     $MODEL=Taxes::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=Taxes::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


    }

     public function EditTaxes($id){


          try {
    DB::beginTransaction();


  $data= $this->validate(request(),[
             'Name'=>'required',
             'Rate'=>'required',
             'Type'=>'required',
               ],[
            'Name.required' => trans('admin.NameRequired'),
            'Rate.required' => trans('admin.RateRequired'),
            'Type.required' => trans('admin.Taxes_TypeRequired'),
         ]);

            $safe=Taxes::find($id);
         AcccountingManual::where('id',$safe->Account)->update(['Name'=>request('Name'),'NameEn'=>request('NameEn')]);

         $dataa['Code']=request('Code');
         $dataa['Name']=request('Name');
         $dataa['NameEn']=request('NameEn');
         $dataa['Rate']=request('Rate');
         $dataa['Type']=request('Type');
         $dataa['Hide']=0;
         $dataa['Account']=request('Account');
         $dataa['CodeTax']=request('CodeTax');
         $dataa['SubType']=request('SubType');
         Taxes::where('id',$id)->update($dataa);


    $dataUser=[
    'screen_ar'=>'الضرائب',
    'screen_en'=>'Taxes',
    'explain_ar'=>request('Name'),
    'explain_en'=>request('NameEn'),
    ];
    $this->UserUpdateMoves($dataUser);

                DB::commit();

            session()->flash('success',trans('admin.Updated'));
            return back();


             }catch(\Exception $ex){

     $MODEL=Taxes::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=Taxes::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }



     }

     public function DeleteTaxes($id){

          try {
    DB::beginTransaction();

              $del=Taxes::findOrFail($id);

 $st=$this->DefaultDataDelete(StoresDefaultData::class,$id,'Tax');
            $pu=$this->DefaultDataDelete(PurchasesDefaultData::class,$id,'Tax');
            $sa=$this->DefaultDataDelete(SalesDefaultData::class,$id,'Tax');
                $result= $st+ $pu + $sa ;
                if($result != 0){
        session()->flash('error',trans('admin.Cant_Delete_Default_Data'));
        return back();

         }


  $dataUser=[
    'screen_ar'=>'الضرائب',
    'screen_en'=>'Taxes',
    'explain_ar'=>$del->Name,
    'explain_en'=>$del->NameEn,
    ];
    $this->UserDeleteMoves($dataUser);

        $del->delete();



                DB::commit();


        session()->flash('error',trans('admin.Deleted'));
        return back();


             }catch(\Exception $ex){

     $MODEL=Taxes::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

           session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }catch(\Error $ex){


             $MODEL=Taxes::class;
              DB::rollBack();
Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

        session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

         }


           }



    // ====== Journalizing =======

    public function JournalizingPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Branchs=Branches::all();
    $Code=$this->ReturnCode(Journalizing::class);
    $Accounts=AcccountingManual::where('Type',1)->get();

    return view('admin.Accounts.Journalizing',get_defined_vars());
    }

    public function JournalizingSechdule(){

        $def=AccountsDefaultData::latest('id')->first();
if($def->Hide_Edit_Delete == 1){
    $items=Journalizing::paginate(50);
}else{
    $items=Journalizing::where('Edit',null)->where('Delete',null)->paginate(50);
}

 $Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();
    return view('admin.Accounts.JournalizingSechdules',[
    'items'=>$items,
    'Types'=>$Types,

    ]);
    }

    public function JournalizingSechduleFilter(){

    $from=request('From');
    $to=request('To');
    $CodeType=request('Type');
        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=Journalizing::whereBetween('Date',[$from,$to])

                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Type',$CodeType);

                })
                ->paginate(50);

        }else{


            $items=Journalizing::whereBetween('Date',[$from,$to])
                ->where('Edit',null)->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Type',$CodeType);

                })
                ->paginate(50);

        }


    $items->appends(request()->query());
$Types=GeneralDaily::select('Type','TypeEn')->distinct(['Type'])->get();
    return view('admin.Accounts.JournalizingSechdules',[
    'items'=>$items,
    'Types'=>$Types,

    ]);
    }

    public function AddJournalizing(JournalizingRequest $request){

    try {
    DB::beginTransaction();


    $validated = $request->validated();
    $DefAcc=AccountsDefaultData::latest('id')->first()->Sure_Recipts;

    if($DefAcc == 0) {
    $Status=1;
    $type=0;
    }else{
    $Status=0;
    $type=1;
    }


    $type_ar= 'القيود اليومية';
    $type_en='Journalizing';
    $cutom=0;
    $custom_data=0;

    AddJournalizingEvent::dispatch($request->all(),$Status,$type,$type_ar,$type_en,$cutom,$custom_data);

    $dataUser=[
    'screen_ar'=>'القيود اليومية',
    'screen_en'=>'Journalizing',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];
    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));

    if(request('SP') == 1){

        $ID=Journalizing::latest('id')->first()->id;
    return redirect('JournalizingPrint/'.$ID);

    }elseif(request('SP') == 0){

    return back();

    }


    }catch(\Exception $ex){

    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function EditJournalizing($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=Journalizing::find($id);
    $details=JournalizingDetails::where('Joun_ID',$item->id)->get();
    $Branchs=Branches::all();
    $Code=$this->ReturnCode(Journalizing::class);
    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();
    if($DefAcc->Sure_Recipts == 1) {
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('JournalizingSechdule');
    }
    }

    return view('admin.Accounts.EditJournalizing',get_defined_vars());
    }

    public function DeleteJournalizing($id){

    try {
    DB::beginTransaction();


    $del=Journalizing::findOrFail($id);

    Notifications::where('Type_Code',$del->Code)->where('Type','القيد اليومي')->delete();
    GeneralDaily::where('Code',$del->Code)->where('Type','القيود اليومية')->delete();

    $dataUser=[
    'screen_ar'=>'القيود اليومية',
    'screen_en'=>'Journalizing',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);

    Journalizing::where('id',$id)->update(['Delete'=>1]);

    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function PostEditJournalizing(JournalizingRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();

    Journalizing::where('id',request('ID'))->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);



    $item=Journalizing::findOrFail(request('ID'));



    Notifications::where('Type_Code',$item->Code)->where('Type','القيد اليومي')->delete();
    GeneralDaily::where('Code',$item->Code)->where('Type','القيود اليومية')->delete();

    $DefAcc=AccountsDefaultData::latest('id')->first()->Sure_Recipts;

    if($DefAcc == 0) {
    $Status=1;
    $type=0;
    }else{
    $Status=0;
    $type=1;
    }


    $type_ar= 'القيود اليومية';
    $type_en='Journalizing';
    $cutom=0;
    $custom_data=0;

    AddJournalizingEvent::dispatch($request->all(),$Status,$type,$type_ar,$type_en,$cutom,$custom_data);

    $dataUser=[
    'screen_ar'=>'القيود اليومية',
    'screen_en'=>'Journalizing',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return redirect('JournalizingSechdule');



    }catch(\Exception $ex){

    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return redirect('JournalizingSechdule');

    }




    }

    public function SureJournalizing($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=Journalizing::find($id);
    $details=JournalizingDetails::where('Joun_ID',$item->id)->get();
    $Branchs=Branches::all();
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('JournalizingSechdule');
    }
    return view('admin.Accounts.SureJournalizing',get_defined_vars());
    }

    public function PostSureJournalizing(JournalizingRequest $request){

    try {
    DB::beginTransaction();


    $validated = $request->validated();

    Journalizing::where('id',request('ID'))->update(['Status'=>1]);

    $item=Journalizing::findOrFail(request('ID'));

    Notifications::where('Type_Code',$item->Code)->where('Type','القيد اليومي')->delete();


    //Event Sure

    SureJournalizingEvent::dispatch($request->all());

    DB::commit();
    session()->flash('success',trans('admin.Updated'));
    return redirect('JournalizingSechdule');


    }catch(\Exception $ex){

    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Journalizing::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return redirect('JournalizingSechdule');

    }

    }

    public function JournalizingPrint($id){

    $item=Journalizing::find($id);
    $details=JournalizingDetails::where('Joun_ID',$item->id)->get();
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Journalizing');
    $place='Jounralizing';
    return view('admin.Accounts.JournalizingPrint',get_defined_vars());
    }


    //=== Recipt Voucher ====
    public function Receipt_VoucherPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Code=$this->ReturnCode(ReciptVoucher::class);
    $Accounts=AcccountingManual::where('Type',1)->get();
    $Emps = Employess::type()->get();
    return view('admin.Accounts.Receipt_Voucher',get_defined_vars());
    }

    public function AddReceipt_Voucher(VoucherRequest $request){


    try {
    DB::beginTransaction();

    $validated = $request->validated();

    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();
    if($DefAcc->Sure_Recipts == 0) {
    $Status=1;
    }else{
    $Status=0;
    }

    $imageFile=request()->file('File');
    $zFile=$this->UploadFile($imageFile);
    AddReciptVoucherEvent::dispatch($request->all(),$Status,$zFile);


    $dataUser=[
    'screen_ar'=>'سند قبض',
    'screen_en'=>'Receipt Voucher',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);

    DB::commit();
    session()->flash('success',trans('admin.Added_Successfully'));

    if(request('SP') == 1){
        $IDD=ReciptVoucher::latest('id')->first()->id;
        return redirect('Receipt_VoucherPrint/'.$IDD);
    }elseif(request('SP') == 0){
    return back();
    }



    }catch(\Exception $ex){

    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function Receipt_VoucherSechdule(){


        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=ReciptVoucher::paginate(50);
        }else{
            $items=ReciptVoucher::where('Edit',null)->where('Delete',null)->paginate(50);
        }

    $Safes = AcccountingManual::where('Type',1)->safetype()->get();
    return view('admin.Accounts.ReceiptVoucherSechdule',get_defined_vars());
    }

    public function ReceiptVoucherSechduleFilter(){
    $from=request('From');
    $to=request('To');
    $CodeType=request('Code');
    $Safe=request('Safe');

        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){

            $items=ReciptVoucher::whereBetween('Date',[$from,$to])

                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Safe), function ($query) use ($Safe) {
                    return $query->where('Safe',$Safe);

                })
                ->paginate(50);
        }else{

            $items=ReciptVoucher::whereBetween('Date',[$from,$to])
->where('Edit',null)->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Safe), function ($query) use ($Safe) {
                    return $query->where('Safe',$Safe);

                })
                ->paginate(50);

        }


    $Safes = AcccountingManual::where('Type',1)->safetype()->get();
    $items->appends(request()->query());
    return view('admin.Accounts.ReceiptVoucherSechdule',get_defined_vars());
    }

    public function EditReceipt_Voucher($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=ReciptVoucher::find($id);
    $details=ReciptVoucherDetails::where('RV_ID',$item->id)->get();
    $Emps = Employess::type()->get();
    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();
    $Code=$this->ReturnCode(ReciptVoucher::class);
    if($DefAcc->Sure_Recipts == 1) {
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Receipt_VoucherSechdule');

    }

    }
    return view('admin.Accounts.EditReceiptVoucher',get_defined_vars());
    }

    public function DeleteReceipt_Voucher($id){

    try {
    DB::beginTransaction();

    $del=ReciptVoucher::findOrFail($id);

    if($del->Status == 1){
    GeneralDaily::where('Code_Type',$del->Code)->where('Type','سند قبض')->delete();
    Notifications::where('Type_Code',$del->Code)->where('Type','سند قبض')->delete();
    Journalizing::where('Code_Type',$del->Code)->where('Type','سند قبض')->update(['Delete'=>1]);
        if(!empty($item->Sales_Bill)) {
            Sales::where('Code',$item->Sales_Bill)->update(['Later_Collection'=>0]);
        }
    }

    ReciptVoucher::where('id',$id)->update(['Delete'=>1]);

    $del=ReciptVoucher::findOrFail($id);



    $dataUser=[
    'screen_ar'=>'سند قبض',
    'screen_en'=>'Receipt Voucher',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);

    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();




    }catch(\Exception $ex){

    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function PostEditReceipt_Voucher(VoucherRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();

    $item=ReciptVoucher::findOrFail(request('ID'));

    if($item->Status == 1){
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','سند قبض')->delete();
    Notifications::where('Type_Code',$item->Code)->where('Type','سند قبض')->delete();
    Journalizing::where('Code_Type',$item->Code)->where('Type','سند قبض')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);

        if(!empty($item->Sales_Bill)) {
            Sales::where('Code',$item->Sales_Bill)->update(['Later_Collection'=>0]);
        }
    }
    ReciptVoucher::where('id',request('ID'))->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);



    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();
    if($DefAcc->Sure_Recipts == 0) {
    $Status=1;
    }else{
    $Status=0;
    }

    $imageFile=request()->file('File');
    $zFile=$this->UploadFile($imageFile);

    AddReciptVoucherEvent::dispatch($request->all(),$Status,$zFile);



    $dataUser=[
    'screen_ar'=>'سند قبض',
    'screen_en'=>'Receipt Voucher',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];
    $this->UserUpdateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return redirect('Receipt_VoucherSechdule');



    }catch(\Exception $ex){

    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function Receipt_VoucherPrint($id){

    $item=ReciptVoucher::find($id);
    $details=ReciptVoucherDetails::where('RV_ID',$item->id)->get();
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Recipt_Voucher');
    $place='Recipt';
    return view('admin.Accounts.Receipt_VoucherPrint',get_defined_vars());
    }

    public function SureReceipt_Voucher($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=ReciptVoucher::find($id);
    $details=ReciptVoucherDetails::where('RV_ID',$item->id)->get();
    $Emps = Employess::type()->get();
    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();

    if($DefAcc->Sure_Recipts == 1) {
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Receipt_VoucherSechdule');

    }

    }

    return view('admin.Accounts.SureReceipt_Voucher',get_defined_vars());
    }

    public function PostSureReceipt_Voucher(VoucherRequest $request){

    try {
    DB::beginTransaction();
    $validated = $request->validated();

        $itemR=ReciptVoucher::findOrFail(request('ID'));



        $Bill_Num = request('Bill_Num');


        for($z=0 ; $z < count($Bill_Num) ; $z++){


            //Sales Bill

                if ($Bill_Num[$z] != null) {


                    $item = Sales::where('Code', $Bill_Num[$z])->latest('id')->first();

                    if (!empty($item)) {




                        $resdiual=$item->Total_Net - $item->Pay ;
                        $recipt=ReciptVoucherDetails::whereRelation('RV_ID','Status',1)->whereRelation('RV_ID','Delete',null)->whereRelation('RV_ID','Edit',null)->where('Bill_Num',$item->Code)->get()->sum('Creditor');
                        $totRes= $resdiual -  $recipt ;

                        $Total_Creditor=ReciptVoucherDetails::where('RV_ID',$itemR->id)->get()->sum('Creditor');

                        $paid=$totRes - $Total_Creditor ;

                        if($paid == 0){

                            Sales::where('id', $item->id)->update(['Later_Collection' => 1]);


                            $Pros = ProductSales::where('Sales', $item->id)->get();

                            foreach ($Pros as $pro) {

                                ProductSales::where('id', $pro->id)->update(['Later_Collection' => 1]);

                            }

                        }
                    }

                }


        }





    ReciptVoucher::where('id',request('ID'))->update(['Status'=>1]);


    Notifications::where('Type_Code',$itemR->Code)->where('Type','سند قبض')->delete();



    //Use Sure event
    SureReciptVoucherEvent::dispatch($request->all());


    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return redirect('Receipt_VoucherSechdule');




    }catch(\Exception $ex){

    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ReciptVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }


    // ==== Payment Voucher ===
    public function Payment_VoucherPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Emps=Employess::type()->get();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $Code=$this->ReturnCode(PaymentVoucher::class);
    return view('admin.Accounts.Payment_Voucher',get_defined_vars());
    }

    public function AddPayment_Voucher(VoucherRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();


    //Safe Credit
    $dif=$this->SafeCredit(request('Safe'),request('Total_Debaitor'));
    if($dif == 1){

    session()->flash('error',trans('admin.SafeNotEnoughMoney'));
    return back();

    }

    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();

    if($DefAcc->Sure_Recipts == 0) {
    $Status=1;
    }else{
    $Status=0;
    }


    $imageFile=request()->file('File');
    $zFile=$this->UploadFile($imageFile);
    AddPaymentVoucherEvent::dispatch($request->all(),$Status,$zFile);


    $dataUser=[
    'screen_ar'=>'سند صرف',
    'screen_en'=>'Payment Voucher',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    if(request('SP') == 1){
        $IDD=PaymentVoucher::latest('id')->first()->id;
    return redirect('Payment_VoucherPrint/'.$IDD);
    }elseif(request('SP') == 0){
    return back();
    }


    }catch(\Exception $ex){

    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function Payment_VoucherSechdule(){



        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=PaymentVoucher::paginate(50);
        }else{
            $items=PaymentVoucher::where('Edit',null)->where('Delete',null)->paginate(50);
        }


        $Safes = AcccountingManual::where('Type',1)->safetype()->get();
    return view('admin.Accounts.PaymentVoucherSechdule',get_defined_vars());
    }

    public function PaymentVoucherSechduleFilter(){
    $from=request('From');
    $to=request('To');
    $CodeType=request('Code');
    $Safe=request('Safe');



        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){

            $items=PaymentVoucher::whereBetween('Date',[$from,$to])
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Safe), function ($query) use ($Safe) {
                    return $query->where('Safe',$Safe);

                })
                ->paginate(50);
        }else{

            $items=PaymentVoucher::whereBetween('Date',[$from,$to])
                ->where('Edit',null)->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Safe), function ($query) use ($Safe) {
                    return $query->where('Safe',$Safe);

                })
                ->paginate(50);
        }



        $Safes = AcccountingManual::where('Type',1)->safetype()->get();

    $items->appends(request()->query());
    return view('admin.Accounts.PaymentVoucherSechdule',get_defined_vars());
    }


    public function EditPayment_Voucher($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=PaymentVoucher::find($id);
    $details=PaymentVoucherDetails::where('PV_ID',$item->id)->get();
    $Code=$this->ReturnCode(PaymentVoucher::class);
        $Emps=Employess::type()->get();

    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();

    if($DefAcc->Sure_Recipts == 1) {
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Payment_VoucherSechdule');

    }

    }

    return view('admin.Accounts.EditPaymentVoucher',get_defined_vars());
    }

    public function DeletePayment_Voucher($id){

    try {
    DB::beginTransaction();

    $del=PaymentVoucher::findOrFail($id);

    if($del->Status == 1){
    GeneralDaily::where('Code_Type',$del->Code)->where('Type','سند صرف')->delete();
    Notifications::where('Type_Code',$del->Code)->where('Type','سند صرف')->delete();
    Journalizing::where('Code_Type',$del->Code)->where('Type','سند صرف')->update(['Delete'=>1]);
    }

    PaymentVoucher::where('id',$id)->update(['Delete'=>1]);

    $del=PaymentVoucher::findOrFail($id);

    $dataUser=[
    'screen_ar'=>'سند صرف',
    'screen_en'=>'Payment Voucher',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);

    DB::commit();


    session()->flash('error',trans('admin.Deleted'));
    return back();


    }catch(\Exception $ex){

    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function PostEditPayment_Voucher(VoucherRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();


    $item=PaymentVoucher::findOrFail(request('ID'));

    if($item->Status == 1){
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','سند صرف')->delete();
    Notifications::where('Type_Code',$item->Code)->where('Type','سند صرف')->delete();
    Journalizing::where('Code_Type',$item->Code)->where('Type','سند صرف')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    }
    PaymentVoucher::where('id',request('ID'))->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);



    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();
    if($DefAcc->Sure_Recipts == 0) {
    $Status=1;
    }else{
    $Status=0;
    }

    $imageFile=request()->file('File');
    $zFile=$this->UploadFile($imageFile);

    AddPaymentVoucherEvent::dispatch($request->all(),$Status,$zFile);


    $dataUser=[
    'screen_ar'=>'سند صرف',
    'screen_en'=>'Payment Voucher',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];

    $this->UserUpdateMoves($dataUser);
    DB::commit();


    session()->flash('success',trans('admin.Updated'));
    return redirect('Payment_VoucherSechdule');



    }catch(\Exception $ex){

    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }





    }

    public function Payment_VoucherPrint($id){

    $item=PaymentVoucher::find($id);
    $details=PaymentVoucherDetails::where('PV_ID',$item->id)->get();
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Payment_Voucher');
    $place='Payment';
    return view('admin.Accounts.Payment_VoucherPrint',get_defined_vars());
    }

    public function SurePayment_Voucher($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=PaymentVoucher::find($id);
    $details=PaymentVoucherDetails::where('PV_ID',$item->id)->get();
        $Emps=Employess::type()->get();
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Payment_VoucherSechdule');

    }

    return view('admin.Accounts.SurePayment_Voucher',get_defined_vars());
    }

    public function PostSurePayment_Voucher(VoucherRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();


    $item=PaymentVoucher::findOrFail(request('ID'));
    PaymentVoucher::where('id',request('ID'))->update(['Status'=>1]);


    Notifications::where('Type_Code',$item->Code)->where('Type','سند صرف')->delete();



    //Use Sure event
    SurePaymentVoucherEvent::dispatch($request->all());


    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return redirect('Payment_VoucherSechdule');

    }catch(\Exception $ex){

    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=PaymentVoucher::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }


    // ==== Opening Entries ===
    public function OpeningEntriesPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();

    $Code=$this->ReturnCode(OpeningEntries::class);

    $Accounts=AcccountingManual::where('Type',1)->get();
    return view('admin.Accounts.OpeningEntries',get_defined_vars());
    }

    public function AddOpeningEntries(OpeningRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();

    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();

    if($DefAcc->Sure_Recipts == 0) {
    $Status=1;
    }else{
    $Status=0;
    }



    AddOpeningEntriesEvent::dispatch($request->all(),$Status);


    $dataUser=[
    'screen_ar'=>'القيد الإفتتاحي',
    'screen_en'=>'Opening Entries',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    if(request('SP') == 1){
        $IDD=OpeningEntries::latest('id')->first()->id;
    return redirect('Opening_EntriesPrint/'.$IDD);
    }elseif(request('SP') == 0){
    return back();
    }


    }catch(\Exception $ex){

    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function Opening_EntriesSechdule(){

        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=OpeningEntries::paginate(50);
        }else{
            $items=OpeningEntries::where('Edit',null)->where('Delete',null)->paginate(50);
        }


    return view('admin.Accounts.OpeningEntriesSechdules',get_defined_vars());
    }

    public function OpeningEntriesSechduleFilter(){

    $from=request('From');
    $to=request('To');
    $CodeType=request('Code');


        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=OpeningEntries::whereBetween('Date',[$from,$to])
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })
                ->paginate(50);
        }else{

            $items=OpeningEntries::whereBetween('Date',[$from,$to])
                ->where('Edit',null)->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })
                ->paginate(50);

        }


    $items->appends(request()->query());
    return view('admin.Accounts.OpeningEntriesSechdules',get_defined_vars());
    }

    public function EditOpening_Entries($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=OpeningEntries::find($id);
    $details=OpeningEntriesDetails::where('OP_ID',$item->id)->get();

    $Code=$this->ReturnCode(OpeningEntries::class);
    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();

    if($DefAcc->Sure_Recipts == 1) {
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Opening_EntriesSechdule');

    }

    }



    return view('admin.Accounts.EditOpeningEntries',get_defined_vars());
    }

    public function DeleteOpening_Entries($id){


    try {
    DB::beginTransaction();

    $del=OpeningEntries::findOrFail($id);

    if($del->Status == 1){
    GeneralDaily::where('Code_Type',$del->Code)->where('Type','القيد الإفتتاحي')->delete();
    Notifications::where('Type_Code',$del->Code)->where('Type','القيد الإفتتاحي')->delete();
    Journalizing::where('Code_Type',$del->Code)->where('Type','القيد الإفتتاحي')->update(['Delete'=>1]);
    }

    OpeningEntries::where('id',$id)->update(['Delete'=>1]);

    $del=OpeningEntries::findOrFail($id);

    $dataUser=[
    'screen_ar'=>'القيد الإفتتاحي',
    'screen_en'=>'Opening Entries',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];
    $this->UserDeleteMoves($dataUser);

    DB::commit();


    session()->flash('error',trans('admin.Deleted'));
    return back();

    }catch(\Exception $ex){

    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }





    }

    public function PostEditOpeningEntries(OpeningRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();


    $item=OpeningEntries::findOrFail(request('ID'));

    if($item->Status == 1){
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','القيد الإفتتاحي')->delete();
    Notifications::where('Type_Code',$item->Code)->where('Type','القيد الإفتتاحي')->delete();
    Journalizing::where('Code_Type',$item->Code)->where('Type','القيد الإفتتاحي')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    }
    OpeningEntries::where('id',request('ID'))->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);



    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();
    if($DefAcc->Sure_Recipts == 0) {
    $Status=1;
    }else{
    $Status=0;
    }



    AddOpeningEntriesEvent::dispatch($request->all(),$Status);


    $dataUser=[
    'screen_ar'=>'القيد الإفتتاحي',
    'screen_en'=>'Opening Entries',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];

    $this->UserUpdateMoves($dataUser);
    DB::commit();



    session()->flash('success',trans('admin.Updated'));
    return redirect('Opening_EntriesSechdule');



    }catch(\Exception $ex){

    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function Opening_EntriesPrint($id){

    $item=OpeningEntries::find($id);
    $details=OpeningEntriesDetails::where('OP_ID',$item->id)->get();
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Opening_Entries');
    $place='Opening Entries';
    return view('admin.Accounts.Opening_EntriesPrint',get_defined_vars());
    }

    public function SureOpening_Entries($id){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Accounts=AcccountingManual::where('Type',1)->get();
    $item=OpeningEntries::find($id);
    $details=OpeningEntriesDetails::where('OP_ID',$item->id)->get();

    $DefAcc=AccountsDefaultData::orderBy('id','desc')->first();

    if($DefAcc->Sure_Recipts == 1) {
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('Opening_EntriesSechdule');

    }

    }

    return view('admin.Accounts.SureOpening_Entries',get_defined_vars());
    }


    public function PostSureOpeningEntries(OpeningRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();




    $item=OpeningEntries::findOrFail(request('ID'));
    OpeningEntries::where('id',request('ID'))->update(['Status'=>1]);

    Notifications::where('Type_Code',$item->Code)->where('Type','القيد الإفتتاحي')->delete();



    //Use Sure event
    SureOpeningEntriesEvent::dispatch($request->all());


    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return redirect('Opening_EntriesSechdule');



    }catch(\Exception $ex){

    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=OpeningEntries::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }


    // ==== Exporting Checks ===
    public function Exporting_ChecksPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $ChecksTypes=ChecksTypes::all();

        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=ExportChecks::paginate(50);
        }else{
            $items=ExportChecks::where('Edit',null)->where('Delete',null)->paginate(50);
        }


    $Code=$this->ReturnCode(ExportChecks::class);

    return view('admin.Accounts.ExportChecks',get_defined_vars());
    }

    public function ExportingChecksSechduleFilter(){


    $from=request('From');
    $to=request('To');
    $CodeType=request('Code');
    $Account=request('Account');
    $Due_Date=request('Due_Date');


        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=ExportChecks::whereBetween('Date',[$from,$to])

                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Account), function ($query) use ($Account) {
                    return $query->where('Account',$Account);

                })

                ->when(!empty($Due_Date), function ($query) use ($Due_Date) {
                    return $query->where('Due_Date',$Due_Date);

                })

                ->paginate(50);
        }else{


            $items=ExportChecks::whereBetween('Date',[$from,$to])

                ->where('Edit',null)->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Account), function ($query) use ($Account) {
                    return $query->where('Account',$Account);

                })

                ->when(!empty($Due_Date), function ($query) use ($Due_Date) {
                    return $query->where('Due_Date',$Due_Date);

                })

                ->paginate(50);

        }




    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $ChecksTypes=ChecksTypes::all();
    $Code=$this->ReturnCode(ExportChecks::class);


    $items->appends(request()->query());
    return view('admin.Accounts.ExportChecks',get_defined_vars());
    }

    public function AddExporting_Checks(ChecksRequest $request){

    try {
    DB::beginTransaction();

    $validated = $request->validated();


    $File=request()->file('File');
    $zFile=$this->UploadFile($File);
    $Image=request()->file('Image');
    $zImage=$this->UploadFile($Image);

    ExportChecksEvent::dispatch($request->all(),$zFile,$zImage);


    $dataUser=[
    'screen_ar'=>'الشيكات الصادرة',
    'screen_en'=>'Exporting Checks',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);

    DB::commit();


    session()->flash('success',trans('admin.Added_Successfully'));
    return back();


    }catch(\Exception $ex){

    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function EditExporting_Checks(ChecksRequest $request,$id){

    try {
    DB::beginTransaction();

    $validated = $request->validated();

    $item=ExportChecks::findOrFail($id);


    GeneralDaily::where('Code_Type',$item->Code)->where('Type','الشيكات الصادرة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الصادرة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','دفع شيك صادر')->delete();

    Event::where('Type_Code',$item->Code)->where('Type','شيك صادر')->delete();

    Journalizing::where('Code_Type',$item->Code)->where('Type','الشيكات الصادرة')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الصادرة')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','دفع شيك صادر')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);


    ExportChecks::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);



    $File=request()->file('File');
    $zFile=$this->UploadFile($File);
    $Image=request()->file('Image');
    $zImage=$this->UploadFile($Image);

    ExportChecksEvent::dispatch($request->all(),$zFile,$zImage);


    $dataUser=[
    'screen_ar'=>'الشيكات الصادرة',
    'screen_en'=>'Exporting Checks',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];

    $this->UserUpdateMoves($dataUser);

    DB::commit();


    session()->flash('success',trans('admin.Updated'));
    return back();


    }catch(\Exception $ex){

    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function DeleteExportingChecks($id){

    try {
    DB::beginTransaction();

    $item=ExportChecks::findOrFail($id);


    GeneralDaily::where('Code_Type',$item->Code)->where('Type','الشيكات الصادرة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الصادرة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','دفع شيك صادر')->delete();

    Event::where('Type_Code',$item->Code)->where('Type','شيك صادر')->delete();

    Journalizing::where('Code_Type',$item->Code)->where('Type','الشيكات الصادرة')->update(['Delete'=>1]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الصادرة')->update(['Delete'=>1]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','دفع شيك صادر')->update(['Delete'=>1]);


    ExportChecks::where('id',$id)->update(['Delete'=>1]);



    $dataUser=[
    'screen_ar'=>'الشيكات الصادرة',
    'screen_en'=>'Exporting Checks',
    'explain_ar'=>$item->Code,
    'explain_en'=>$item->Code,
    ];

    $this->UserDeleteMoves($dataUser);

    DB::commit();

    session()->flash('error',trans('admin.Deleted'));
    return back();




    }catch(\Exception $ex){

    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function ReasonExportChecks(ChecksService $service){

    try {
    DB::beginTransaction();

    ExportChecks::where('id',request('ID'))->update(['Status'=>1,'Reason'=>request('Reason')]);

    $check=ExportChecks::findOrFail(request('ID'));


    $service->RefuseExportChecks($check);


    DB::commit();
    session()->flash('error',trans('admin.Refused'));
    return back();

    }catch(\Exception $ex){

    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function PayExportingChecks(ChecksService $service){


    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'BankSafe_Account'=>'required',
    ],[
    'BankSafe_Account.required' => trans('admin.BankSafe_AccountRequired'),
    ]);


    ExportChecks::where('id',request('ID'))->update(['Status'=>3,'BankSafe_Account'=>request('BankSafe_Account')]);

    $check=ExportChecks::findOrFail(request('ID'));

    $service->PayExportChecks($check);


    DB::commit();

    session()->flash('success',trans('admin.Check_Payed'));
    return back();


    }catch(\Exception $ex){

    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }


    public function TransExportingChecks(ChecksRequest $request,ChecksService $service){



    try {

    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Bene_Account'=>'required',
    ],[
    'Bene_Account.required' => trans('admin.Bene_AccountRequired'),
    ]);

    $validated = $request->validated();


    $Code=$this->ReturnCode(IncomChecks::class);
    ExportChecks::where('id',request('ID'))->update(['Status'=>2,'Bene_Account'=>request('Bene_Account'),'Transfer'=>1,'Edit_New_Code'=>$Code]);

    $item=ExportChecks::findOrFail(request('ID'));

    $service->TransferToIncomChecks($item);


    DB::commit();

    session()->flash('success',trans('admin.Transfer_Successfully'));
    return back();



    }catch(\Exception $ex){

    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=ExportChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }





    }


    public function PrintOutcomChecks($id){

    $item=ExportChecks::find($id);
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Exporting_Checks');
    $place='OutCome';

    return view('admin.Accounts.PrintOutcomChecks',get_defined_vars());
    }

    public function PrintIncomChecks($id){

    $item=IncomChecks::find($id);
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Incoming_Checks');
    $place='Income';

    return view('admin.Accounts.PrintIncomChecks',get_defined_vars());
    }


    // ==== Incoming Checks ===
    public function Incoming_checksPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $ChecksTypes=ChecksTypes::all();

        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=IncomChecks::paginate(50);
        }else{
            $items=IncomChecks::where('Edit',null)->where('Delete',null)->paginate(50);
        }


    $Code=$this->ReturnCode(IncomChecks::class);

    return view('admin.Accounts.IncomChecks',get_defined_vars());
    }

    public function IncomingchecksSechduleFilter(){


    $from=request('From');
    $to=request('To');
    $CodeType=request('Code');
    $Account=request('Account');
    $Due_Date=request('Due_Date');


        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=IncomChecks::whereBetween('Date',[$from,$to])

                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Account), function ($query) use ($Account) {
                    return $query->where('Account',$Account);

                })

                ->when(!empty($Due_Date), function ($query) use ($Due_Date) {
                    return $query->where('Due_Date',$Due_Date);

                })

                ->paginate(50);
        }else{

            $items=IncomChecks::whereBetween('Date',[$from,$to])

                ->where('Edit',null)->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Account), function ($query) use ($Account) {
                    return $query->where('Account',$Account);

                })

                ->when(!empty($Due_Date), function ($query) use ($Due_Date) {
                    return $query->where('Due_Date',$Due_Date);

                })

                ->paginate(50);

        }


        $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $ChecksTypes=ChecksTypes::all();
    $Code=$this->ReturnCode(IncomChecks::class);
    $items->appends(request()->query());
    return view('admin.Accounts.IncomChecks',get_defined_vars());
    }

    public function AddIncoming_checks(ChecksRequest $request){

    try {

    DB::beginTransaction();

    $validated = $request->validated();



    $File=request()->file('File');
    $zFile=$this->UploadFile($File);
    $Image=request()->file('Image');
    $zImage=$this->UploadFile($Image);

    IncomCheckEvent::dispatch($request->all(),$zFile,$zImage);


    DB::commit();


    $dataUser=[
    'screen_ar'=>'الشيكات الواردة',
    'screen_en'=>'Incoming Checks',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function EditIncoming_checks(ChecksRequest $request,$id){

    try {

    DB::beginTransaction();

    $validated = $request->validated();


    $item=IncomChecks::findOrFail($id);


    GeneralDaily::where('Code_Type',$item->Code)->where('Type','الشيكات الواردة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الواردة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','دفع شيك وارد')->delete();

    Event::where('Type_Code',$item->Code)->where('Type','شيك وارد')->delete();

    Journalizing::where('Code_Type',$item->Code)->where('Type','الشيكات الواردة')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الواردة')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','دفع شيك وارد')->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);


    IncomChecks::where('id',$id)->update(['Edit'=>1,'Edit_New_Code'=>request('Code')]);



    $File=request()->file('File');
    $zFile=$this->UploadFile($File);
    $Image=request()->file('Image');
    $zImage=$this->UploadFile($Image);

    IncomCheckEvent::dispatch($request->all(),$zFile,$zImage);


    $dataUser=[
    'screen_ar'=>'الشيكات الواردة',
    'screen_en'=>'Incoming Checks',
    'explain_ar'=>request('Old_Code'),
    'explain_en'=>request('Old_Code'),
    ];

    $this->UserUpdateMoves($dataUser);

    DB::commit();


    session()->flash('success',trans('admin.Updated'));
    return back();


    }catch(\Exception $ex){

    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function DeleteIncoming_checks($id){


    try {
    DB::beginTransaction();

    $item=IncomChecks::findOrFail($id);


    GeneralDaily::where('Code_Type',$item->Code)->where('Type','الشيكات الواردة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الواردة')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','دفع شيك وارد')->delete();

    Event::where('Type_Code',$item->Code)->where('Type','شيك وارد')->delete();

    Journalizing::where('Code_Type',$item->Code)->where('Type','الشيكات الواردة')->update(['Delete'=>1]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','رفض الشيكات الواردة')->update(['Delete'=>1]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','دفع شيك وارد')->update(['Delete'=>1]);


    IncomChecks::where('id',$id)->update(['Delete'=>1]);





    $dataUser=[
    'screen_ar'=>'الشيكات الصادرة',
    'screen_en'=>'Exporting Checks',
    'explain_ar'=>$item->Code,
    'explain_en'=>$item->Code,
    ];

    $this->UserDeleteMoves($dataUser);

    DB::commit();


    session()->flash('error',trans('admin.Deleted'));
    return back();



    }catch(\Exception $ex){

    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function ReasonIncoming_checks(ChecksService $service){

    try {
    DB::beginTransaction();

    IncomChecks::where('id',request('ID'))->update(['Status'=>1,'Reason'=>request('Reason')]);

    $check=IncomChecks::findOrFail(request('ID'));


    $service->RefuseIncomChecks($check);


    DB::commit();
    session()->flash('error',trans('admin.Refused'));
    return back();

    }catch(\Exception $ex){

    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function PayIncomingChecks( ChecksService $service){

    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'BankSafe_Account'=>'required',
    ],[
    'BankSafe_Account.required' => trans('admin.BankSafe_AccountRequired'),
    ]);


    IncomChecks::where('id',request('ID'))->update(['Status'=>3,'BankSafe_Account'=>request('BankSafe_Account')]);

    $check=IncomChecks::findOrFail(request('ID'));

    $service->PayIncomChecks($check);


    DB::commit();

    session()->flash('success',trans('admin.Check_Payed'));
    return back();


    }catch(\Exception $ex){

    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }


    public function TransIncoming_checks(ChecksRequest $request,ChecksService $service){

    try {

    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Bene_Account'=>'required',
    ],[
    'Bene_Account.required' => trans('admin.Bene_AccountRequired'),
    ]);


    $validated = $request->validated();


    $Code=$this->ReturnCode(ExportChecks::class);

    IncomChecks::where('id',request('ID'))->update(['Status'=>2,'Bene_Account'=>request('Bene_Account'),'Transfer'=>1,'Edit_New_Code'=>$Code]);

    $item=IncomChecks::findOrFail(request('ID'));


    $service->TransferToExportChecks($item);


    DB::commit();

    session()->flash('success',trans('admin.Transfer_Successfully'));
    return back();
    }catch(\Exception $ex){

    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=IncomChecks::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    // === Insurance Paper ====
    public function Insurance_PaperPage(){

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();


        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=InsurancePaper::paginate(50);
        }else{
            $items=InsurancePaper::where('Delete',null)->paginate(50);
        }


        $Code=$this->ReturnCode(InsurancePaper::class);

    return view('admin.Accounts.InsurancePaper',get_defined_vars());
    }

    public function InsurancePaperSechduleFilter(){



    $from=request('From');
    $to=request('To');
    $CodeType=request('Code');
    $Account=request('Account');
    $Due_Date=request('Due_Date');



        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=InsurancePaper::whereBetween('Date',[$from,$to])

                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Account), function ($query) use ($Account) {
                    return $query->where('Account',$Account);

                })

                ->when(!empty($Due_Date), function ($query) use ($Due_Date) {
                    return $query->where('Due_Date',$Due_Date);

                })

                ->paginate(50);
        }else{

            $items=InsurancePaper::whereBetween('Date',[$from,$to])

                ->where('Delete',null)
                ->when(!empty($CodeType), function ($query) use ($CodeType) {
                    return $query->where('Code',$CodeType);

                })

                ->when(!empty($Account), function ($query) use ($Account) {
                    return $query->where('Account',$Account);

                })

                ->when(!empty($Due_Date), function ($query) use ($Due_Date) {
                    return $query->where('Due_Date',$Due_Date);

                })

                ->paginate(50);

        }



        $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Code=$this->ReturnCode(InsurancePaper::class);

    $items->appends(request()->query());
    return view('admin.Accounts.InsurancePaper',get_defined_vars());
    }

    public function AddInsurancePaper(InsurancePaperRequest $request){

    try {

    DB::beginTransaction();

    $validated = $request->validated();



    $File=request()->file('File');
    $zFile=$this->UploadFile($File);


    InsurancePaperEvent::dispatch($request->all(),$zFile);


    $dataUser=[
    'screen_ar'=>'وصل أمانة',
    'screen_en'=>'Insurance Paper',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);


    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();

    }catch(\Exception $ex){

    $MODEL=InsurancePaper::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=InsurancePaper::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function DeleteInsurancePaper($id){

    try {
    DB::beginTransaction();

    $item=InsurancePaper::findOrFail($id);


    GeneralDaily::where('Code_Type',$item->Code)->where('Type','وصل أمانة')->delete();
    Event::where('Type_Code',$item->Code)->where('Type','وصل أمانة')->delete();
    Journalizing::where('Code_Type',$item->Code)->where('Type','وصل أمانة')->update(['Delete'=>1]);



    InsurancePaper::where('id',$id)->update(['Delete'=>1]);


    $dataUser=[
    'screen_ar'=>'وصل أمانة',
    'screen_en'=>'Insurance Paper',
    'explain_ar'=>$item->Code,
    'explain_en'=>$item->Code,
    ];

    $this->UserDeleteMoves($dataUser);

    DB::commit();


    session()->flash('error',trans('admin.Deleted'));
    return back();



    }catch(\Exception $ex){

    $MODEL=InsurancePaper::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=InsurancePaper::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function RecivedInurance(ChecksService $service,$id){

    try {
    DB::beginTransaction();

    $data= $this->validate(request(),[
    'Bank'=>'required',
    ],[
    'Bank.required' => trans('admin.BankRequired'),
    ]);


    InsurancePaper::where('id',$id)->update(['Status'=>1,'Bank'=>request('Bank')]);
    $item=InsurancePaper::findOrFail($id);

    $service->RecivedInsurancePaper($item);


    DB::commit();



    session()->flash('success',trans('admin.Insurance_Paper_Recived'));
    return back();



    }catch(\Exception $ex){

    $MODEL=InsurancePaper::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=InsurancePaper::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }



    //===== Safes Transfers ===
    public function SafesTransferPage(){
    $items=SafeTransfers::all();
    $Coins=Coins::all();
    $CostCenters=CostCenter::all();
    $Safes = AcccountingManual::where('Type',1)->safetype()->get();
    $ToSafes = AcccountingManual::where('Type',1)->whereIn('Parent',[28,29])->get();
    $Emps = Employess::type()->get();
    $Branches=Branches::all();
    $Code=$this->ReturnCode(SafeTransfers::class);
    return view('admin.Accounts.SafesTransfer',get_defined_vars());
    }

    public function AddSafeTransfer(SafeTransferRequest $request){

    try {

    DB::beginTransaction();

    $validated = $request->validated();

    $File=request()->file('File');
    $zFile=$this->UploadFile($File);



    $data['Delegate']=request('Delegate');
    $data['Time']=date("h:i:s a", time());
    $data['Code']=request('Code');
    $data['Date']=request('Date');
    $data['Draw']=request('Draw');
    $data['Amount']=request('Amount');
    $data['Note']=request('Note');
    $data['From_Safe']=request('From_Safe');
    $data['Branch']=request('Branch');
    $data['To_Safe']=request('To_Safe');
    $data['Coin']=request('Coin');
    $data['Status']=0;
    $data['File']=$zFile;
    $data['Edit']=0;
    $data['OldAmount']=request('Amount');
    $data['Cost_Center']=request('Cost_Center');
    $data['User']=auth()->guard('admin')->user()->id;

    SafeTransfers::create($data);

    $notii['Date']=date('Y-m-d');
    $notii['Status']=0;
    $notii['Noti_Ar_Name']='تحويل خزائن يحتاج للتأكيد';
    $notii['Noti_En_Name']='Safe Transfer Need Confirmation';
    $notii['Type']='تحويلات خزائن';
    $notii['TypeEn']='Safe Transfers';
    $notii['Type_Code']=request('Code');
    $notii['Emp']=request('Delegate');
    $notii['Client']=null;
    $notii['Product']=null;
    $notii['Store']=null;
    $notii['Safe']=request('To_Safe');
    Notifications::create($notii);

    notify()->warning(trans('admin.Safe_Transfer_Need_Confirmation'));




    $dataUser=[
    'screen_ar'=>'تحويلات خزائن',
    'screen_en'=>'Safes Transfer',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserCreateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();



    }catch(\Exception $ex){

    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function TransferSureSafe($id){
    $items=SafeTransfers::all();
    $Coins=Coins::all();
    $CostCenters=CostCenter::all();
    $Safes = AcccountingManual::where('Type',1)->safetype()->get();
        $ToSafes = AcccountingManual::where('Type',1)->whereIn('Parent',[28,29])->get();
    $Emps = Employess::type()->get();
    $Branches=Branches::all();
    $item=SafeTransfers::find($id);
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('SafesTransferSechdule');

    }


    return view('admin.Accounts.SureSafesTransfer',get_defined_vars());
    }

    public function SureSafeTransfer($id,SafeTransferRequest $request,ChecksService $service){

    try {

    DB::beginTransaction();

    $validated = $request->validated();


    $item=SafeTransfers::find($id);
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('SafesTransferSechdule');

    }


    $File=request()->file('File');
    $zFile=$this->UploadFile($File);

    if(!empty($zFile)){

    $data['File']=$zFile;

    }else{
    $data['File']=request('Files');
    }

    $data['Delegate']=request('Delegate');
    $data['Status']=1;
    $data['Code']=request('Code');
    $data['Date']=request('Date');
    $data['Draw']=request('Draw');
    $data['Amount']=request('Amount');
    $data['Note']=request('Note');
    $data['From_Safe']=request('From_Safe');
    $data['To_Safe']=request('To_Safe');
    $data['Coin']=request('Coin');
    $data['OldAmount']=request('OldAmount');
    $data['Edit']=0;
    $data['Cost_Center']=request('Cost_Center');
    $data['User']=auth()->guard('admin')->user()->id;
    $data['Branch']=request('Branch');
    SafeTransfers::where('id',$id)->update($data);

    $item=SafeTransfers::findOrFail($id);

        $service->SureSafeTransfer($item);


    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return redirect('SafesTransferSechdule');


    }catch(\Exception $ex){

    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }

    public function SafesTransferSechdulePage(){


    $items=SafeTransfers::type()->paginate(100);


    return view('admin.Accounts.SafesTransferSechdule',get_defined_vars());
    }

    public function EditSafeTransfer($id){
    $items=SafeTransfers::all();
    $Coins=Coins::all();
    $CostCenters=CostCenter::all();
    $item=SafeTransfers::find($id);
    $Safes = AcccountingManual::where('Type',1)->safetype()->get();
        $ToSafes = AcccountingManual::where('Type',1)->whereIn('Parent',[28,29])->get();
    $Emps = Employess::type()->get();
    $Branches=Branches::all();
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('SafesTransferSechdule');

    }
    return view('admin.Accounts.EditSafesTransfer',get_defined_vars());
    }

    public function RefusedSafeTransfer($id){


    try {

    DB::beginTransaction();

    SafeTransfers::where('id',$id)->update(['Status'=>2]);

    $del=SafeTransfers::findOrFail($id);

    $notii['Date']=date('Y-m-d');
    $notii['Status']=0;
    $notii['Noti_Ar_Name']='رفض تحويل خزينة';
    $notii['Noti_En_Name']='Refuse Safe Transfer';
    $notii['Type']='تحويلات خزائن';
    $notii['TypeEn']='Safe Transfers';
    $notii['Type_Code']=$del->Code;
    $notii['Emp']=$del->Delegate;
    $notii['Client']=null;
    $notii['Product']=null;
    $notii['Store']=null;
    $notii['Safe']=$del->To_Safe;
    Notifications::create($notii);

    notify()->error(trans('admin.RefuseSafeTransfer'));


    $dataUser=[
    'screen_ar'=>'تحويلات خزائن',
    'screen_en'=>'Safes Transfer',
    'type_ar'=>'رفض تحويل خزينة',
    'type_en'=>'Refuse Safe Transfer',
    'explain_ar'=>$del->Code,
    'explain_en'=>$del->Code,
    ];

    $this->UserCustomMoves($dataUser);

    DB::commit();


    session()->flash('error',trans('admin.Refused'));
    return back();



    }catch(\Exception $ex){

    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }




    }

    public function PostEditSafeTransfer(SafeTransferRequest $request,$id){

    try {

    DB::beginTransaction();

    $validated = $request->validated();



    $item=SafeTransfers::find($id);
    if($item->Status != 0){
    session()->flash('error',trans('admin.Already_Done'));
    return redirect('SafesTransferSechdule');

    }

    Notifications::where('Type_Code',request('Code'))->where('Type','تحويلات خزائن')->delete();

    $File=request()->file('File');
    $zFile=$this->UploadFile($File);

    if(!empty($zFile)){

    $data['File']=$zFile;

    }else{
    $data['File']=request('Files');
    }

    $data['Delegate']=request('Delegate');
    $data['Status']=0;
    $data['Code']=request('Code');
    $data['Date']=request('Date');
    $data['Draw']=request('Draw');
    $data['Amount']=request('Amount');
    $data['Note']=request('Note');
    $data['From_Safe']=request('From_Safe');
    $data['To_Safe']=request('To_Safe');
    $data['Coin']=request('Coin');
    $data['OldAmount']=request('OldAmount');
    $data['Edit']=1;
    $data['Cost_Center']=request('Cost_Center');
    $data['User']=auth()->guard('admin')->user()->id;
    $data['Branch']=request('Branch');
    SafeTransfers::where('id',$id)->update($data);



    $notii['Date']=date('Y-m-d');
    $notii['Status']=0;
    $notii['Noti_Ar_Name']='تحويل خزائن يحتاج للتأكيد';
    $notii['Noti_En_Name']='Safe Transfer Need Confirmation';
    $notii['Type']='تحويلات خزائن';
    $notii['Type_Code']=request('Code');
    $notii['Emp']=request('Delegate');
    $notii['Client']=null;
    $notii['Product']=null;
    $notii['Store']=null;
    $notii['Safe']=request('To_Safe');
    Notifications::create($notii);
    notify()->success(trans('admin.Safe_Transfer_Need_Confirmation'));



    $dataUser=[
    'screen_ar'=>'تحويلات خزائن',
    'screen_en'=>'Safes Transfer',
    'explain_ar'=>request('Code'),
    'explain_en'=>request('Code'),
    ];

    $this->UserUpdateMoves($dataUser);

    DB::commit();

    session()->flash('success',trans('admin.Updated'));
    return redirect('SafesTransferSechdule');





    }catch(\Exception $ex){

    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=SafeTransfers::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }



    }

    public function TransSafePrint($id){

    $item=SafeTransfers::find($id);
    $Def=CompanyData::orderBy('id','desc')->first();
    $title=trans('admin.Safes_Transfer');
    $place='Safe';

    return view('admin.Accounts.SafeTransferPrint',get_defined_vars());
    }


    //===== Assets ===
    public function AssetsPage(){

        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=Assets::paginate(50);
        }else{
            $items=Assets::where('Delete',null)->paginate(50);
        }

        $Safes = AcccountingManual::where('Type',1)->safetype()->get();
    $Code=$this->ReturnCode(Assets::class);
    $Ehlak = AcccountingManual::
    where('Type',1)
    ->where('Parent',120)
    ->get();

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Branchs=Branches::all();

    // Assets Monthly Event

    try {

    DB::beginTransaction();
    // Assets Monthly Event

    AssetsMonthlyEvent::dispatch();


    DB::commit();

    }catch(\Exception $ex){

    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    return view('admin.Accounts.Assets',get_defined_vars());
    }

    public function AssetsSechduleFilter(){


    $From=request('From');
    $To=request('To');
    $Main_Account=request('Main_Account');
    $Asset_Type=request('Asset_Type');
    $Depreciation_Method=request('Depreciation_Method');




        $def=AccountsDefaultData::latest('id')->first();
        if($def->Hide_Edit_Delete == 1){
            $items=Assets::whereBetween('Operation_Date',[$From,$To])

                ->when(!empty($Main_Account), function ($query) use ($Main_Account) {
                    return $query->where('Main_Account',$Main_Account);

                })

                ->when(!empty($Asset_Type), function ($query) use ($Asset_Type) {
                    return $query->where('Asset_Type',$Asset_Type);

                })


                ->when(!empty($Depreciation_Method), function ($query) use ($Depreciation_Method) {
                    return $query->where('Depreciation_Method',$Depreciation_Method);

                })

                ->paginate(100);
        }else{

            $items=Assets::whereBetween('Operation_Date',[$From,$To])
->where('Delete',null)
                ->when(!empty($Main_Account), function ($query) use ($Main_Account) {
                    return $query->where('Main_Account',$Main_Account);

                })

                ->when(!empty($Asset_Type), function ($query) use ($Asset_Type) {
                    return $query->where('Asset_Type',$Asset_Type);

                })


                ->when(!empty($Depreciation_Method), function ($query) use ($Depreciation_Method) {
                    return $query->where('Depreciation_Method',$Depreciation_Method);

                })

                ->paginate(100);

        }

    $Safes = AcccountingManual::where('Type',1)->safetype()->get();
    $Code=$this->ReturnCode(Assets::class);


    $Ehlak = AcccountingManual::
    where('Type',1)
    ->where('Parent',120)
    ->get();

    $CostCenters=CostCenter::all();
    $Coins=Coins::all();
    $Branchs=Branches::all();

    return view('admin.Accounts.Assets',get_defined_vars());
    }

    public function AddAssets(Request $request){


    try {

    DB::beginTransaction();

    if(request('Asset_Type') === 'consumer'){

       $data= $this->validate(request(),[
          'Name'=>'required',
               'Depreciation_Complex'=>'required',
             'Main_Account'=>'required',
             'Draw'=>'required',
             'Coin'=>'required',
             'Ehlak'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    ]);

    }else{

    $data= $this->validate(request(),[
    'Name'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    ]);


    }


    if(request('Sort_Asset') == 2) {

        if(request('Payment_Method') == 'Cash') {
        $SafeBalance = $this->SafeCredit(request('Safe'), request('Cost'));

        if ($SafeBalance == 1) {
            session()->flash('error', trans('admin.SafeNotEnoughMoney'));
            return back();

        }
        }
    }

    if(!empty(request('NameEn'))){

    $english_name=request('NameEn');
    }else{

    $english_name=request('Name');
    }


    // Event

    $File=request()->file('Image');
    $zFile=$this->UploadFile($File);

    AssetsEvent::dispatch($request->all(),$zFile);


    $dataUser=[
    'screen_ar'=>'الاصول',
    'screen_en'=>'Assets',
    'explain_ar'=>request('Name'),
    'explain_en'=>$english_name,
    ];

    $this->UserCreateMoves($dataUser);



    DB::commit();

    session()->flash('success',trans('admin.Added_Successfully'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }

    }

    public function DeleteAssets($id){

    try {
    DB::beginTransaction();

    $item=Assets::findOrFail($id);

  //  AcccountingManual::where('id',$item->Account)->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','شراء أصل')->delete();
    GeneralDaily::where('Code_Type',$item->Code)->where('Type','الهالك')->delete();
    Journalizing::where('Code_Type',$item->Code)->where('Type','شراء أصل')->update(['Delete'=>1]);
    Journalizing::where('Code_Type',$item->Code)->where('Type','الهالك')->update(['Delete'=>1]);



    Assets::where('id',$id)->update(['Delete'=>1]);


    $dataUser=[
    'screen_ar'=>'الاصول',
    'screen_en'=>'Assets',
    'explain_ar'=>$item->Name,
    'explain_en'=>$item->NameEn,
    ];

    $this->UserDeleteMoves($dataUser);

    DB::commit();


    session()->flash('error',trans('admin.Deleted'));
    return back();



    }catch(\Exception $ex){

    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }




    }

    public function AssetSale(ChecksService $service){


    try {
    DB::beginTransaction();

             $data= $this->validate(request(),[

             'CurrentAssetPrice'=>'required',
             'Amount'=>'required',
             'Client'=>'required',
             'Safe'=>'required',
    ],[
    'Name.required' => trans('admin.NameRequired'),
    ]);

        $id=request('ID');

    Assets::where('id',$id)->update([
        'Sale'=>1,
        'CurrentAssetPrice'=>request('CurrentAssetPrice'),
        'Amount'=>request('Amount'),
        'Client'=>request('Client'),
        'Safe'=>request('Safe'),

    ]);

  $item=Assets::findOrFail($id);
  //  AcccountingManual::where('id',$item->Account)->delete();

    $service->AssetsSale($item);

    DB::commit();

    session()->flash('success',trans('admin.Asset_Sale'));
    return back();


    }catch(\Exception $ex){

    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }catch(\Error $ex){


    $MODEL=Assets::class;
    DB::rollBack();
    Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

    session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
    return back();

    }


    }


   //Assets Expenses  ( Msh M3ana )
     public function AssetExpensesPage(){
        $items=AssetsExpenses::paginate(100);
           $Assets=Assets::all();
            $res=AssetsExpenses::orderBy('id','desc')->first();

           if(!empty($res->Code)){

              $Code=$res->Code + 1 ;

           }else{

              $Code=1;

           }

            $CostCenters=CostCenter::all();
          $Coins=Coins::all();

         $Safes=AcccountingManual::
          where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();

         return view('admin.Accounts.AssetsExpenses',['items'=>$items,'Code'=>$Code,'CostCenters'=>$CostCenters,'Coins'=>$Coins,'Safes'=>$Safes,'Assets'=>$Assets]);
    }

     public function AddAssetsExpenses(){

        $data= $this->validate(request(),[
             'Name'=>'required',
               ],[
            'Name.required' => trans('admin.NameRequired'),
         ]);



         $dataa['Code']=request('Code');
         $dataa['Date']=request('Date');
         $dataa['Name']=request('Name');
         $dataa['Amount']=request('Amount');
         $dataa['Asset']=request('Asset');
         $dataa['Safe']=request('Safe');
         $dataa['Draw']=request('Draw');
         $dataa['Coin']=request('Coin');
         $dataa['Cost_Center']=request('Cost_Center');
         $dataa['User']=auth()->guard('admin')->user()->id;

         AssetsExpenses::create($dataa);


         $last=Assets::find(request('Asset'));
         $new=$last->Asset_Net + request('Amount') ;
         $zz=($last->Annual_Depreciation_Ratio / 100 )  * $new;

         $ass['Asset_Net']=$new;
         $ass['Annual_Depreciation']=$zz;
         Assets::where('id',$last->id)->update($ass);


                 $res=Journalizing::orderBy('id','desc')->first();

           if(!empty($res->Code)){

              $Code=$res->Code + 1 ;
           }else{
              $Code=1;

           }

        $ID = DB::table('journalizings')->insertGetId(

        array(

            'Code' => $Code,
            'Type' => trans('admin.AssetExpenses'),
            'Code_Type' => request('Code'),
            'Date' => date('Y-m-d'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => request('Cost_Center'),
            'Total_Debaitor' => request('Amount'),
            'Total_Creditor' => request('Amount'),
            'Note' => request('Note'),

        )
    );


        $PRODUCTSS['Joun_ID']=$ID;
        $PRODUCTSS['Debitor']=request('Amount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$last->Depreciation_Expenses;
        $PRODUCTSS['Statement']=null;


         JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=date('Y-m-d');
        $Gen['Type']=trans('admin.AssetExpenses');
        $Gen['Debitor']=request('Amount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Amount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=$last->Depreciation_Expenses;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']= request('Cost_Center');
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);



        $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=0;
        $PRODUCTSSS['Creditor']=request('Amount');
        $PRODUCTSSS['Account']=request('Safe');
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);

        $Genn['Code']=$Code;
        $Genn['Code_Type']=request('Code');
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']=trans('admin.AssetExpenses');
        $Genn['Debitor']=0;
        $Genn['Creditor']=request('Amount');
        $Genn['Statement']=null;
        $Genn['Draw']=request('Draw');
        $Genn['Debitor_Coin']= request('Draw') * 0;
        $Genn['Creditor_Coin']=request('Draw') * request('Amount');
        $Genn['Account']=request('Safe');
        $Genn['Coin']= request('Coin');
        $Genn['Cost_Center']= request('Cost_Center');
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);

           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']=trans('admin.AssetExpenses');
           $dataUser['Type']=trans('admin.AddNew');
           $dataUser['Explain']=request('Name');
           UsersMoves::create($dataUser);

             session()->flash('success',trans('admin.Added_Successfully'));
             return back();

    }


//Investors
    public function Investors(){
        $items=Investors::paginate(50);
        $Safes = AcccountingManual::where('Type',1)->safetype()->get();
        $Coins=Coins::all();
        return view('admin.Accounts.Investors',get_defined_vars());
    }

    public function AddInvestors(Request $request){


        try {

            DB::beginTransaction();

            $data= $this->validate(request(),[
                'Date'=>'required',
                'Name'=>'required',
                'Investment_Value'=>'required',
                'Safe'=>'required',
                'Draw'=>'required',
                'Coin'=>'required',
                'Profit_Precent'=>'required',
            ],[
                'Name.required' => trans('admin.NameRequired'),
            ]);


            $Acc=$this->CreateAccountByName(request('Name'),request('Name') ,'المستثمرين' ,null);
            $AccDue=$this->CreateAccountByName(request('Name').' '.'استحقاق',request('Name').' '.'Due' ,'استحقاق مستثمرين' ,null);
            $AccExp=$this->CreateAccountByName(request('Name').' '.'مصروفات',request('Name').' '.'Expenses' ,'مصروفات ارباح مستثمرين' ,null);


            $dataa['Date']=request('Date');
            $dataa['Name']=request('Name');
            $dataa['Investment_Value']=request('Investment_Value');
            $dataa['Safe']=request('Safe');
            $dataa['Draw']=request('Draw');
            $dataa['Coin']=request('Coin');
            $dataa['Profit_Precent']=request('Profit_Precent');
            $dataa['Investment_Period']=request('Investment_Period');
            $dataa['Liquidation_Time']=request('Liquidation_Time');
            $dataa['Status']=0;
            $dataa['End_Date']=null;
            $dataa['Account']=$Acc;
            $dataa['Due_Account']=$AccDue;
            $dataa['Expenses_Account']=$AccExp;
            Investors::create($dataa);

            $Draw=request('Draw');
$Coin=request('Coin');
$Safe=request('Safe');
$Creditor=request('Investment_Value');
//Create Recipt Voucher
            $IDD = DB::table('recipt_vouchers')->insertGetId(

                array(


                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Safe' => $Safe,
                    'Cost_Center' => null,
                    'Total_Creditor' => $Creditor,
                    'Shift' => null,
                    'Store' => null,
                    'Collector' => null,
                    'Note' => null,
                    'User' => auth()->guard('admin')->user()->emp,

                )
            );


            $PRODUCTS['RV_ID']=$IDD;
            $PRODUCTS['Creditor']=$Creditor;
            $PRODUCTS['Account']=$Acc;
            $PRODUCTS['Statement']=null;

            ReciptVoucherDetails::create($PRODUCTS);



            $Code=ReciptVoucher::findOrFail($IDD)->Code;


            $ID = DB::table('journalizings')->insertGetId(

                array(


                    'Type' => 'سند قبض',
                    'TypeEn' => 'Receipt Voucher',
                    'Code_Type' => $Code,
                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $Creditor,
                    'Total_Creditor' => $Creditor,
                    'Note' => null,

                )
            );


            $Codee=Journalizing::findOrFail($ID)->Code;

            $PRODUCTSS['Joun_ID']=$ID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$Creditor;
            $PRODUCTSS['Account']=$Acc;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Codee;
            $Gen['Code_Type']=$Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']= 'سند قبض';
            $Gen['TypeEn']='Receipt Voucher';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$Creditor;
            $Gen['Statement']=null;
            $Gen['Draw']=$Draw;
            $Gen['Debitor_Coin']= $Draw * 0;
            $Gen['Creditor_Coin']=$Draw * $Creditor;
            $Gen['Account']=$Acc;
            $Gen['Coin']= $Coin;
            $Gen['Cost_Center']= null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);


            $PRODUCTSSS['Joun_ID']=$ID;
            $PRODUCTSSS['Debitor']=$Creditor;
            $PRODUCTSSS['Creditor']=0;
            $PRODUCTSSS['Account']=$Safe;
            $PRODUCTSSS['Statement']=null;
            JournalizingDetails::create($PRODUCTSSS);

            $Genn['Code']=$Codee;
            $Genn['Code_Type']=$Code;
            $Genn['Date']=date('Y-m-d');
            $Genn['Type']= 'سند قبض';
            $Genn['TypeEn']='Receipt Voucher';
            $Genn['Debitor']=$Creditor;
            $Genn['Creditor']=0;
            $Genn['Statement']=null;
            $Genn['Draw']=$Draw;
            $Genn['Debitor_Coin']= $Draw * $Creditor;
            $Genn['Creditor_Coin']=$Draw * 0;
            $Genn['Account']=$Safe;
            $Genn['Coin']= $Coin;
            $Genn['Cost_Center']= null;
            $Genn['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Genn);



            $dataUser=[
                'screen_ar'=>'المستثمرين',
                'screen_en'=>'Investors',
                'explain_ar'=>request('Name'),
                'explain_en'=>request('Name'),
            ];

            $this->UserCreateMoves($dataUser);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();


        }catch(\Exception $ex){

            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }

    }

    public function DeleteInvestors($id){

        try {
            DB::beginTransaction();

            $item=Investors::findOrFail($id);


            $Draw=$item->Draw;
$Coin=$item->Coin;
$Safe=$item->Safe;
$Debitor=$item->Investment_Value;
            $AccountCodee=$item->Account;
            $STATEMENT=null;
            $IDD = DB::table('payment_vouchers')->insertGetId(

                array(


                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Safe' => $Safe,
                    'Shift' => null,
                    'Store' => null,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $Debitor,
                    'Note' => null,
                    'User' => auth()->guard('admin')->user()->emp,
                    'Branch' => null,
                )
            );

            $PRODUCTS['PV_ID']=$IDD;
            $PRODUCTS['Debitor']=$Debitor;
            $PRODUCTS['Account']=$AccountCodee;
            $PRODUCTS['Statement']=$STATEMENT;
            $PRODUCTS['Date']=date('Y-m-d');
            $PRODUCTS['Time']=date("h:i:s a", time());
            $PRODUCTS['Cost_Center']=null;
            $PRODUCTS['Coin']=$Coin;
            $PRODUCTS['User']=auth()->guard('admin')->user()->id;
            $PRODUCTS['Branch']=null;
            $PRODUCTS['Safe']=$Safe;

            PaymentVoucherDetails::create($PRODUCTS);

            $Code=PaymentVoucher::findOrFail($IDD)->Code;



            $ID = DB::table('journalizings')->insertGetId(

                array(

                    'Type' => 'سند صرف',
                    'TypeEn' => 'Payment Voucher',
                    'Code_Type' => $Code,
                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $Debitor,
                    'Total_Creditor' =>$Debitor,
                    'Note' => null,

                )
            );


            $Codee=Journalizing::findOrFail($ID)->Code;

            $PRODUCTSS['Joun_ID']=$ID;
            $PRODUCTSS['Debitor']=$Debitor;
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$AccountCodee;
            $PRODUCTSS['Statement']=$STATEMENT;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Codee;
            $Gen['Code_Type']=$Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']='سند صرف';
            $Gen['TypeEn']='Payment Voucher';
            $Gen['Debitor']=$Debitor;
            $Gen['Creditor']=0;
            $Gen['Statement']=$STATEMENT;
            $Gen['Draw']=$Draw;
            $Gen['Debitor_Coin']= $Draw * $Debitor;
            $Gen['Creditor_Coin']=$Draw * 0;
            $Gen['Account']=$AccountCodee;
            $Gen['Coin']= $Coin;
            $Gen['Cost_Center']= null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);



            $PRODUCTSSS['Joun_ID']=$ID;
            $PRODUCTSSS['Debitor']=0;
            $PRODUCTSSS['Creditor']=$Debitor;
            $PRODUCTSSS['Account']=$Safe;
            $PRODUCTSSS['Statement']=$STATEMENT;
            JournalizingDetails::create($PRODUCTSSS);

            $Genn['Code']=$Codee;
            $Genn['Code_Type']=$Code;
            $Genn['Date']=date('Y-m-d');
            $Genn['Type']='سند صرف';
            $Genn['TypeEn']='Payment Voucher';
            $Genn['Debitor']=0;
            $Genn['Creditor']=$Debitor;
            $Genn['Statement']=$STATEMENT;
            $Genn['Draw']=$Draw;
            $Genn['Debitor_Coin']= $Draw * 0;
            $Genn['Creditor_Coin']=$Draw * $Debitor;
            $Genn['Account']=$Safe;
            $Genn['Coin']= $Coin;
            $Genn['Cost_Center']= null;
            $Genn['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Genn);

//              AcccountingManual::where('id',$item->Account)->delete();
//              AcccountingManual::where('id',$item->Due_Account)->delete();
//              AcccountingManual::where('id',$item->Expenses_Account)->delete();
            Investors::where('id',$id)->delete();
            $dataUser=[
                'screen_ar'=>'المستثمرين',
                'screen_en'=>'Investors',
                'explain_ar'=>$item->Name,
                'explain_en'=>$item->Name,
            ];

            $this->UserDeleteMoves($dataUser);

            DB::commit();


            session()->flash('error',trans('admin.Deleted'));
            return back();



        }catch(\Exception $ex){

            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }




    }

    public function EndInvestors($id){

        try {
            DB::beginTransaction();

            $item=Investors::findOrFail($id);


            $Draw=$item->Draw;
$Coin=$item->Coin;
$Safe=$item->Safe;
$Debitor=$item->Investment_Value;
            $AccountCodee=$item->Account;
            $STATEMENT=null;
            $IDD = DB::table('payment_vouchers')->insertGetId(

                array(


                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Safe' => $Safe,
                    'Shift' => null,
                    'Store' => null,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $Debitor,
                    'Note' => null,
                    'User' => auth()->guard('admin')->user()->emp,
                    'Branch' => null,
                )
            );

            $PRODUCTS['PV_ID']=$IDD;
            $PRODUCTS['Debitor']=$Debitor;
            $PRODUCTS['Account']=$AccountCodee;
            $PRODUCTS['Statement']=$STATEMENT;
            $PRODUCTS['Date']=date('Y-m-d');
            $PRODUCTS['Time']=date("h:i:s a", time());
            $PRODUCTS['Cost_Center']=null;
            $PRODUCTS['Coin']=$Coin;
            $PRODUCTS['User']=auth()->guard('admin')->user()->id;
            $PRODUCTS['Branch']=null;
            $PRODUCTS['Safe']=$Safe;

            PaymentVoucherDetails::create($PRODUCTS);

            $Code=PaymentVoucher::findOrFail($IDD)->Code;



            $ID = DB::table('journalizings')->insertGetId(

                array(

                    'Type' => 'سند صرف',
                    'TypeEn' => 'Payment Voucher',
                    'Code_Type' => $Code,
                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $Debitor,
                    'Total_Creditor' =>$Debitor,
                    'Note' => null,

                )
            );


            $Codee=Journalizing::findOrFail($ID)->Code;

            $PRODUCTSS['Joun_ID']=$ID;
            $PRODUCTSS['Debitor']=$Debitor;
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$AccountCodee;
            $PRODUCTSS['Statement']=$STATEMENT;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Codee;
            $Gen['Code_Type']=$Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']='سند صرف';
            $Gen['TypeEn']='Payment Voucher';
            $Gen['Debitor']=$Debitor;
            $Gen['Creditor']=0;
            $Gen['Statement']=$STATEMENT;
            $Gen['Draw']=$Draw;
            $Gen['Debitor_Coin']= $Draw * $Debitor;
            $Gen['Creditor_Coin']=$Draw * 0;
            $Gen['Account']=$AccountCodee;
            $Gen['Coin']= $Coin;
            $Gen['Cost_Center']= null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);



            $PRODUCTSSS['Joun_ID']=$ID;
            $PRODUCTSSS['Debitor']=0;
            $PRODUCTSSS['Creditor']=$Debitor;
            $PRODUCTSSS['Account']=$Safe;
            $PRODUCTSSS['Statement']=$STATEMENT;
            JournalizingDetails::create($PRODUCTSSS);

            $Genn['Code']=$Codee;
            $Genn['Code_Type']=$Code;
            $Genn['Date']=date('Y-m-d');
            $Genn['Type']='سند صرف';
            $Genn['TypeEn']='Payment Voucher';
            $Genn['Debitor']=0;
            $Genn['Creditor']=$Debitor;
            $Genn['Statement']=$STATEMENT;
            $Genn['Draw']=$Draw;
            $Genn['Debitor_Coin']= $Draw * 0;
            $Genn['Creditor_Coin']=$Draw * $Debitor;
            $Genn['Account']=$Safe;
            $Genn['Coin']= $Coin;
            $Genn['Cost_Center']= null;
            $Genn['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Genn);


            Investors::where('id',$id)->update(['Status'=>1,'End_Date'=>date('Y-m-d')]);

            $dataUser=[
                'screen_ar'=>'المستثمرين',
                'screen_en'=>'Investors',
                'type_ar'=>'انهاء استثمار',
                'type_en'=>'End Investment',
                'explain_ar'=>$item->Name,
                'explain_en'=>$item->Name,
            ];
            $this->UserCustomMoves($dataUser);

            DB::commit();


            session()->flash('error',trans('admin.Ended'));
            return back();



        }catch(\Exception $ex){

            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }




    }


    public function MoreValueInvestors($id){


        try {

            DB::beginTransaction();

            $data= $this->validate(request(),[
                'Date'=>'required',
                'Value'=>'required',

            ],[

            ]);

            $item=Investors::findOrFail($id);
            $newval=$item->Investment_Value +  request('Value') ;
            Investors::where('id',$id)->update(['Investment_Value'=>$newval]);




            $dataa['Date']=request('Date');
            $dataa['Valye']=request('Value');
            $dataa['Investor']=$item->id;
            UpdateValuesInvestors::create($dataa);


            $Draw=$item->Draw;
            $Coin=$item->Coin;
            $Safe=$item->Safe;
            $Creditor=request('Value');
            $Acc=$item->Account;
//Create Recipt Voucher
            $IDD = DB::table('recipt_vouchers')->insertGetId(

                array(


                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Safe' => $Safe,
                    'Cost_Center' => null,
                    'Total_Creditor' => $Creditor,
                    'Shift' => null,
                    'Store' => null,
                    'Collector' => null,
                    'Note' => null,
                    'User' => auth()->guard('admin')->user()->emp,

                )
            );


            $PRODUCTS['RV_ID']=$IDD;
            $PRODUCTS['Creditor']=$Creditor;
            $PRODUCTS['Account']=$Acc;
            $PRODUCTS['Statement']=null;

            ReciptVoucherDetails::create($PRODUCTS);



            $Code=ReciptVoucher::findOrFail($IDD)->Code;


            $ID = DB::table('journalizings')->insertGetId(

                array(


                    'Type' => 'سند قبض',
                    'TypeEn' => 'Receipt Voucher',
                    'Code_Type' => $Code,
                    'Date' => date('Y-m-d'),
                    'Draw' => $Draw,
                    'Coin' => $Coin,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $Creditor,
                    'Total_Creditor' => $Creditor,
                    'Note' => null,

                )
            );


            $Codee=Journalizing::findOrFail($ID)->Code;

            $PRODUCTSS['Joun_ID']=$ID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$Creditor;
            $PRODUCTSS['Account']=$Acc;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Codee;
            $Gen['Code_Type']=$Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']= 'سند قبض';
            $Gen['TypeEn']='Receipt Voucher';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$Creditor;
            $Gen['Statement']=null;
            $Gen['Draw']=$Draw;
            $Gen['Debitor_Coin']= $Draw * 0;
            $Gen['Creditor_Coin']=$Draw * $Creditor;
            $Gen['Account']=$Acc;
            $Gen['Coin']= $Coin;
            $Gen['Cost_Center']= null;
            $Gen['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Gen);


            $PRODUCTSSS['Joun_ID']=$ID;
            $PRODUCTSSS['Debitor']=$Creditor;
            $PRODUCTSSS['Creditor']=0;
            $PRODUCTSSS['Account']=$Safe;
            $PRODUCTSSS['Statement']=null;
            JournalizingDetails::create($PRODUCTSSS);

            $Genn['Code']=$Codee;
            $Genn['Code_Type']=$Code;
            $Genn['Date']=date('Y-m-d');
            $Genn['Type']= 'سند قبض';
            $Genn['TypeEn']='Receipt Voucher';
            $Genn['Debitor']=$Creditor;
            $Genn['Creditor']=0;
            $Genn['Statement']=null;
            $Genn['Draw']=$Draw;
            $Genn['Debitor_Coin']= $Draw * $Creditor;
            $Genn['Creditor_Coin']=$Draw * 0;
            $Genn['Account']=$Safe;
            $Genn['Coin']= $Coin;
            $Genn['Cost_Center']= null;
            $Genn['userr']= auth()->guard('admin')->user()->id;

            GeneralDaily::create($Genn);



            DB::commit();

            session()->flash('success',trans('admin.Updated'));
            return back();


        }catch(\Exception $ex){

            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=Investors::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }

    }




    //Partners
    public function PartnersPage(){
        $items=Partners::all();
        $SumShares=Partners::get()->sum('Shares_Number');
        $capital=Capital::latest('id')->first();
      $profit=$this->TOTALPROFIT(date('Y-01-01'),date('Y-m-d'));

       foreach($items as $item){

$ne7sa=$item->Shares_Number * $capital->Actual_Share_Value;
                $up['Now_Partner_Share']=$ne7sa;
                $up['Actual_Share_Value']=$capital->Actual_Share_Value;

           $qema=$ne7sa - $item->First_Partner_Share;
               $up['Capital_Increase_Value']=$qema;


               if($item->First_Partner_Share != 0) {
                   $nsba = ($qema / $item->First_Partner_Share) * 100;
               }else{
                   $nsba = ($qema) * 100;
               }
                $up['Capital_Increase_Rate']=$nsba;

            $spend=SpendProfits::where('Partner',$item->id)->get()->sum('Amount');

           $Newprofit=$profit * ($item->Partnership_Ratio/100) ;

            $up['Profits']=$Newprofit;
            $up['Withdraw_Profits']=$spend;
            $up['Remaining_Profits']=$Newprofit - $spend;

            Partners::where('id',$item->id)->update($up);

        }

        return view('admin.Accounts.Partners',get_defined_vars());
    }

    public function AddPartner(){

        try {
            DB::beginTransaction();


$DEF=AccountsDefaultData::latest('id')->first();
            $Gary_Acc=$this->CreateAccount(request('Name').' '.' جاري ',request('Name').' '.' Current ',46,null);
            $Capital_Acc=$this->CreateAccount(request('Name').' '.' رأس مال ',request('Name').' '.' Capital ',44,null);
            $Recent_Account=$this->CreateAccount(request('Name').' '.' ارباح حالية ',request('Name').' '.' Recent Profit ',139,null);
            $Stage_Account=$this->CreateAccount(request('Name').' '.' ارباح مرحلة ',request('Name').' '.' Stage Profit ',141,null);

            $data['Name']=request('Name');
            $data['Shares_Number']=request('Shares_Number');
            $data['Nominal_Value_of_Shares']=request('Nominal_Value_of_Shares');
            $data['Actual_Share_Value']=request('Actual_Share_Value');
            $data['Profits_Precentage']=request('Profits_Precentage');
            $data['Profits']=request('Profits');
            $data['Withdraw_Profits']=request('Withdraw_Profits');
            $data['Remaining_Profits']=request('Remaining_Profits');
            $data['First_Partner_Share']=request('First_Partner_Share');
            $data['Now_Partner_Share']=request('Now_Partner_Share');
            $data['Capital_Increase_Rate']=request('Capital_Increase_Rate');
            $data['Capital_Increase_Value']=request('Capital_Increase_Value');
            $data['Partnership_Ratio']=request('Partnership_Ratio');
            $data['Account']=$Capital_Acc;
            $data['Gary_Account']=$Gary_Acc;
            $data['Recent_Profit_Account']=$Recent_Account;
            $data['Stage_Profit_Account']=$Stage_Account;

        Partners::create($data);

        $data=[


            'branch'=>null,
            'status'=>null,
            'type_ar'=>'اضافة شريك',
            'type_en'=>'Add Partner',
            'code_type'=>1,
            'date'=>date('Y-m-d'),
            'draw'=>1,
            'coin'=>$DEF->Coin,
            'cost_center'=>null,
            'note'=>null,
            'total'=>request('First_Partner_Share'),

        ];

        $code=$this->CreateNewJun($data);

        $COOODE=Journalizing::find($code)->Code;
            $data=[


                'branch'=>null,
                'status'=>null,
                'type_ar'=>'اضافة شريك',
                'type_en'=>'Add Partner',
                'code_type'=>'',
                'date'=>date('Y-m-d'),
                'draw'=>1,
                'coin'=>$DEF->Coin,
                'cost_center'=>null,
                'total'=>request('First_Partner_Share'),
                'admin_id'=>null,
                'joun_id'=>$code,
                'debitor_debt'=>request('First_Partner_Share'),
                'creditor_debt'=>0,
                'debitor_cred'=>0,
                'creditor_cred'=>request('First_Partner_Share'),
                'account_debt'=>45,
                'note'=>null,
                'code'=>$COOODE,
                'account_cred'=>$Capital_Acc,

            ];
$this->JunDetails($data);

            DB::commit();

        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

            $MODEL=Partners::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=Partners::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }

    public function DeletePartner($id){

        $del=Partners::find($id);
        AcccountingManual::where('id',$del->Account)->delete();
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

    }


    //Capital
    public function CapitalPage(){
        $item=Capital::orderBy('id','desc')->first();

        $Increases=CapitalIncrease::latest('id')->get();
        $Capital_Increase=CapitalIncrease::latest('id')->get()->sum('Value');


        $x=$this->TOTALCAPITAL();


        $Capital=$x['capital'];
        $Invest=$x['invest'];

        return view('admin.Accounts.Capital',get_defined_vars());
    }

    public function AddCapital(){


        $data['Authorized_Capital']=request('Authorized_Capital');
        $data['Source_Capital']=request('Source_Capital');
        $data['Shares_Number']=request('Shares_Number');
        $data['Nominal_Value_of_Shares']=request('Nominal_Value_of_Shares');
        $data['Actual_Share_Value']=request('Actual_Share_Value');
        $data['Actual_Capital']=request('Actual_Capital');
        $data['Capital_Increase']=request('Capital_Increase');
        $data['New_Source_Capital']=request('New_Source_Capital');
        $data['New_Shares_Number']=request('New_Shares_Number');
        $data['Working_Capital']=request('Working_Capital');
        $data['Total_Investment']=request('Total_Investment');

        Capital::create($data);


        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

    }

    public function AddCapitalIncrease(){


        $data['Date']=date('Y-m-d');
        $data['Month']=request('Month');
        $data['Value']=request('Value');

        CapitalIncrease::create($data);


        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

    }



    public function DeleteCapitalIncrease($id){

        $del=CapitalIncrease::find($id);
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

    }



//Spend Profits
    public function Spend_ProfitsPage(){
        $items=SpendProfits::paginate(100);

        $CostCenters=CostCenter::all();

        $Coins=Coins::all();

        $Safes = AcccountingManual::
        where('Type',1)
            ->where('Parent',28)
            ->orWhere('Parent',29)
            ->get();

        $Partners=Partners::all();


        $res=SpendProfits::orderBy('id','desc')->first();

        if(!empty($res->Code)){

            $Code=$res->Code + 1 ;

        }else{

            $Code=1;

        }


        return view('admin.Accounts.SpendProfits',[
            'items'=>$items,
            'Code'=>$Code,
            'CostCenters'=>$CostCenters,
            'Coins'=>$Coins,
            'Safes'=>$Safes,
            'Partners'=>$Partners,
        ]);
    }

    public function PartnerFilter($id){

        $spend=SpendProfits::where('Partner',$id)->get()->sum('Amount');
        $states=[];

        $part=Partners::find($id);


        $states += ["spending" => $part->Profits - $spend,'profit'=>$part->Remaining_Profits];



        return response()->json($states);

    }

    public function AddSpendProfit(){

        try {
            DB::beginTransaction();


        $data['Code']=request('Code');
        $data['Date']=request('Date');
        $data['Draw']=request('Draw');
        $data['Amount']=request('Amount');
        $data['Remaining_Profit']=request('Remaining_Profit');
        $data['Partner']=request('Partner');
        $data['Safe']=request('Safe');
        $data['Coin']=request('Coin');
        $data['Cost_Center']=request('Cost_Center');
        $data['Payment_Method']=request('Payment_Method');
        $data['User']=auth()->guard('admin')->user()->id;
        SpendProfits::create($data);

            $Partner=Partners::find(request('Partner'));
        $JunID = DB::table('journalizings')->insertGetId(
            array(

                'Type' => trans('admin.Spend_Profits'),
                'Code_Type' => request('Code'),
                'Date' => request('Date'),
                'Draw' => request('Draw'),
                'Coin' => request('Coin'),
                'Cost_Center' => request('Cost_Center'),
                'Total_Debaitor' => request('Amount'),
                'Total_Creditor' => request('Amount'),
                'Note' =>null,
            )
        );


            $Code=Journalizing::find($JunID)->Code;




        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Amount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Partner->Recent_Profit_Account;
        $PRODUCTSS['Statement']=null;
        JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
        $Gen['Type']='صرف ارباح';
        $Gen['TypeEn']='Spend Profits';
        $Gen['Debitor']=request('Amount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Amount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=$Partner->Recent_Profit_Account;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']= request('Cost_Center');
        $Gen['userr']= auth()->guard('admin')->user()->id;
        GeneralDaily::create($Gen);

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Amount');
        $PRODUCTSS['Account']=$Partner->Gary_Account;
        $PRODUCTSS['Statement']=null;
        JournalizingDetails::create($PRODUCTSS);

        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
       $Gen['Type']='صرف ارباح';
        $Gen['TypeEn']='Spend Profits';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Amount');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Amount');
        $Gen['Account']=$Partner->Gary_Account;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=request('Cost_Center');
        $Gen['userr']= auth()->guard('admin')->user()->id;
        GeneralDaily::create($Gen);


if(request('Payment_Method') == 'Cash'){

    $PRODUCTSS['Joun_ID']=$JunID;
    $PRODUCTSS['Debitor']=request('Amount');
    $PRODUCTSS['Creditor']=0;
    $PRODUCTSS['Account']=$Partner->Gary_Account;
    $PRODUCTSS['Statement']=null;
    JournalizingDetails::create($PRODUCTSS);

    $Gen['Code']=$Code;
    $Gen['Code_Type']=request('Code');
    $Gen['Date']=request('Date');
    $Gen['Type']='صرف ارباح';
    $Gen['TypeEn']='Spend Profits';
    $Gen['Debitor']=request('Amount');
    $Gen['Creditor']=0;
    $Gen['Statement']=null;
    $Gen['Draw']=request('Draw');
    $Gen['Debitor_Coin']= request('Draw') * request('Amount');
    $Gen['Creditor_Coin']=request('Draw') * 0;
    $Gen['Account']=$Partner->Gary_Account;
    $Gen['Coin']= request('Coin');
    $Gen['Cost_Center']= request('Cost_Center');
    $Gen['userr']= auth()->guard('admin')->user()->id;
    GeneralDaily::create($Gen);




    $PRODUCTSS['Joun_ID']=$JunID;
    $PRODUCTSS['Debitor']=0;
    $PRODUCTSS['Creditor']=request('Amount');
    $PRODUCTSS['Account']=request('Safe');
    $PRODUCTSS['Statement']=null;
    JournalizingDetails::create($PRODUCTSS);

    $Gen['Code']=$Code;
    $Gen['Code_Type']=request('Code');
    $Gen['Date']=request('Date');
    $Gen['Type']='صرف ارباح';
    $Gen['TypeEn']='Spend Profits';
    $Gen['Debitor']=0;
    $Gen['Creditor']=request('Amount');
    $Gen['Statement']=null;
    $Gen['Draw']=request('Draw');
    $Gen['Debitor_Coin']= request('Draw') * 0;
    $Gen['Creditor_Coin']=request('Draw') * request('Amount');
    $Gen['Account']=request('Safe');
    $Gen['Coin']= request('Coin');
    $Gen['Cost_Center']=request('Cost_Center');
    $Gen['userr']= auth()->guard('admin')->user()->id;
    GeneralDaily::create($Gen);

}else{

    $PRODUCTSS['Joun_ID']=$JunID;
    $PRODUCTSS['Debitor']=request('Amount');
    $PRODUCTSS['Creditor']=0;
    $PRODUCTSS['Account']=$Partner->Stage_Profit_Account;
    $PRODUCTSS['Statement']=null;
    JournalizingDetails::create($PRODUCTSS);

    $Gen['Code']=$Code;
    $Gen['Code_Type']=request('Code');
    $Gen['Date']=request('Date');
    $Gen['Type']='صرف ارباح';
    $Gen['TypeEn']='Spend Profits';
    $Gen['Debitor']=request('Amount');
    $Gen['Creditor']=0;
    $Gen['Statement']=null;
    $Gen['Draw']=request('Draw');
    $Gen['Debitor_Coin']= request('Draw') * request('Amount');
    $Gen['Creditor_Coin']=request('Draw') * 0;
    $Gen['Account']=$Partner->Stage_Profit_Account;
    $Gen['Coin']= request('Coin');
    $Gen['Cost_Center']= request('Cost_Center');
    $Gen['userr']= auth()->guard('admin')->user()->id;
    GeneralDaily::create($Gen);




    $PRODUCTSS['Joun_ID']=$JunID;
    $PRODUCTSS['Debitor']=0;
    $PRODUCTSS['Creditor']=request('Amount');
    $PRODUCTSS['Account']=$Partner->Account;
    $PRODUCTSS['Statement']=null;
    JournalizingDetails::create($PRODUCTSS);

    $Gen['Code']=$Code;
    $Gen['Code_Type']=request('Code');
    $Gen['Date']=request('Date');
    $Gen['Type']='صرف ارباح';
    $Gen['TypeEn']='Spend Profits';
    $Gen['Debitor']=0;
    $Gen['Creditor']=request('Amount');
    $Gen['Statement']=null;
    $Gen['Draw']=request('Draw');
    $Gen['Debitor_Coin']= request('Draw') * 0;
    $Gen['Creditor_Coin']=request('Draw') * request('Amount');
    $Gen['Account']=$Partner->Account;
    $Gen['Coin']= request('Coin');
    $Gen['Cost_Center']=request('Cost_Center');
    $Gen['userr']= auth()->guard('admin')->user()->id;
    GeneralDaily::create($Gen);


}





            DB::commit();
        session()->flash('success',trans('admin.Added_Successfully'));
        return back();


        }catch(\Exception $ex){

            $MODEL=SpendProfits::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=SpendProfits::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }

    }

    public function PrintSpendProfits($id){
        $item=SpendProfits::find($id);
        return view('admin.Accounts.SpendProfitsPrint',[
            'item'=>$item,
        ]);
    }


    //CapitalReport
    public function CapitalReport(){
        $item=Capital::orderBy('id','desc')->first();

        $day_jan    = strtotime('Jan Y');
        $last_day_jan  = date('Y-m-t', $day_jan);
        $first_day_jan=date('Y-01-01');
        $xJan=$this->NEWTOTALCAPITAL($first_day_jan,$last_day_jan);
        $CapitalJan=$xJan['capital'];
        $InvestJan=$xJan['invest'];

        $day_feb    = strtotime('Feb Y');
        $last_day_feb  = date('Y-m-t', $day_feb);
        $first_day_feb=date('Y-02-01');
        $xFeb=$this->NEWTOTALCAPITAL($first_day_feb,$last_day_feb);
        $CapitalFeb=$xFeb['capital'];
        $InvestFeb=$xFeb['invest'];

        $day_mar    = strtotime('March Y');
        $last_day_mar  = date('Y-m-t', $day_mar);
        $first_day_mar=date('Y-03-01');
        $xMar=$this->NEWTOTALCAPITAL($first_day_mar,$last_day_mar);
        $CapitalMar=$xMar['capital'];
        $InvestMar=$xMar['invest'];

        $day_april    = strtotime('April Y');
        $last_day_april  = date('Y-m-t', $day_april);
        $first_day_april=date('Y-04-01');
        $xApril=$this->NEWTOTALCAPITAL($first_day_april,$last_day_april);
        $CapitalApril=$xApril['capital'];
        $InvestApril=$xApril['invest'];

        $day_may    = strtotime('May Y');
        $last_day_may  = date('Y-m-t', $day_may);
        $first_day_may=date('Y-05-01');
        $xMay=$this->NEWTOTALCAPITAL($first_day_may,$last_day_may);
        $CapitalMay=$xMay['capital'];
        $InvestMay=$xMay['invest'];

        $day_jun    = strtotime('June Y');
        $last_day_jun  = date('Y-m-t', $day_jun);
        $first_day_jun=date('Y-06-01');
        $xJun=$this->NEWTOTALCAPITAL($first_day_jun,$last_day_jun);
        $CapitalJun=$xJun['capital'];
        $InvestJun=$xJun['invest'];


        $day_jul    = strtotime('Jul Y');
        $last_day_jul  = date('Y-m-t', $day_jul);
        $first_day_jul=date('Y-07-01');
        $xJul=$this->NEWTOTALCAPITAL($first_day_jul,$last_day_jul);
        $CapitalJul=$xJul['capital'];
        $InvestJul=$xJul['invest'];

        $day_aug    = strtotime('Aug Y');
        $last_day_aug  = date('Y-m-t', $day_aug);
        $first_day_aug=date('Y-08-01');
        $xAug=$this->NEWTOTALCAPITAL($first_day_aug,$last_day_aug);
        $CapitalAug=$xAug['capital'];
        $InvestAug=$xAug['invest'];


        $day_sep    = strtotime('Sep Y');
        $last_day_sep  = date('Y-m-t', $day_sep);
        $first_day_sep=date('Y-09-01');
        $xSep=$this->NEWTOTALCAPITAL($first_day_sep,$last_day_sep);
        $CapitalSep=$xSep['capital'];
        $InvestSep=$xSep['invest'];



        $day_oct    = strtotime('Oct Y');
        $last_day_oct  = date('Y-m-t', $day_oct);
        $first_day_oct=date('Y-10-01');
        $xOct=$this->NEWTOTALCAPITAL($first_day_oct,$last_day_oct);
        $CapitalOct=$xOct['capital'];
        $InvestOct=$xOct['invest'];


        $day_nov    = strtotime('Nov Y');
        $last_day_nov  = date('Y-m-t', $day_nov);
        $first_day_nov=date('Y-11-01');
        $xNov=$this->NEWTOTALCAPITAL($first_day_nov,$last_day_nov);
        $CapitalNov=$xNov['capital'];
        $InvestNov=$xNov['invest'];



        $day_dec    = strtotime('Dec Y');
        $last_day_dec  = date('Y-m-t', $day_dec);
        $first_day_dec=date('Y-12-01');
        $xDec=$this->NEWTOTALCAPITAL($first_day_dec,$last_day_dec);
        $CapitalDec=$xDec['capital'];
        $InvestDec=$xDec['invest'];




        $Capital_IncreaseJan=CapitalIncrease::where('Month',date('Y-01'))->get()->sum('Value');
        $Capital_IncreaseFeb=CapitalIncrease::where('Month',date('Y-02'))->get()->sum('Value');
        $Capital_IncreaseMar=CapitalIncrease::where('Month',date('Y-03'))->get()->sum('Value');
        $Capital_IncreaseApril=CapitalIncrease::where('Month',date('Y-04'))->get()->sum('Value');
        $Capital_IncreaseMay=CapitalIncrease::where('Month',date('Y-05'))->get()->sum('Value');
        $Capital_IncreaseJun=CapitalIncrease::where('Month',date('Y-06'))->get()->sum('Value');
        $Capital_IncreaseJul=CapitalIncrease::where('Month',date('Y-07'))->get()->sum('Value');
        $Capital_IncreaseAug=CapitalIncrease::where('Month',date('Y-08'))->get()->sum('Value');
        $Capital_IncreaseSep=CapitalIncrease::where('Month',date('Y-09'))->get()->sum('Value');
        $Capital_IncreaseOct=CapitalIncrease::where('Month',date('Y-10'))->get()->sum('Value');
        $Capital_IncreaseNov=CapitalIncrease::where('Month',date('Y-11'))->get()->sum('Value');
        $Capital_IncreaseDec=CapitalIncrease::where('Month',date('Y-12'))->get()->sum('Value');

        return view('admin.Accounts.CapitalReport',get_defined_vars());
    }


//OrderPay

    public function Order_PaySechdule(){


        $items=OrderPay::paginate(100);


        return view('admin.Accounts.Order_PaySechdule',get_defined_vars());
    }

    public function Order_Pay(){
        $Emps = Employess::type()->get();
        $Accounts = AcccountingManual::where('Type',1)->get();
        $Code=$this->ReturnCode(OrderPay::class);
        return view('admin.Accounts.Order_Pay',get_defined_vars());
    }

    public function AddOrder_Pay(Request $request){

        try {

            DB::beginTransaction();




            $data['Code']=request('Code');
            $data['Date']=request('Date');
            $data['Responsible']=request('Responsible');
            $data['Account']=request('Account');
            $data['Amount']=request('Amount');
            $data['Note']=request('Note');
            $data['Status']=0;


            OrderPay::create($data);



            $dataUser=[
                'screen_ar'=>'امر دفع',
                'screen_en'=>'Order Pay',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];

            $this->UserCreateMoves($dataUser);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();



        }catch(\Exception $ex){

            $MODEL=OrderPay::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=OrderPay::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }

    public function EditOrder_Pay($id){
        $item = OrderPay::find($id);
        $Emps = Employess::type()->get();
        $Accounts = AcccountingManual::where('Type',1)->get();
        return view('admin.Accounts.EditOrder_Pay',get_defined_vars());
    }

    public function PostEditOrder_Pay(Request $request,$id){

        try {

            DB::beginTransaction();




            $data['Code']=request('Code');
            $data['Date']=request('Date');
            $data['Responsible']=request('Responsible');
            $data['Account']=request('Account');
            $data['Amount']=request('Amount');
            $data['Note']=request('Note');
            $data['Status']=0;


            OrderPay::where('id',$id)->update($data);



            $dataUser=[
                'screen_ar'=>'امر دفع',
                'screen_en'=>'Order Pay',
                'explain_ar'=>request('Code'),
                'explain_en'=>request('Code'),
            ];

            $this->UserUpdateMoves($dataUser);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();



        }catch(\Exception $ex){

            $MODEL=OrderPay::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){


            $MODEL=OrderPay::class;
            DB::rollBack();
            Log::channel('custom')->error(' Model => '.$MODEL.' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }

    public function DeleteOrder_Pay($id){

        $del=OrderPay::find($id);


        $dataUser=[
            'screen_ar'=>'امر دفع',
            'screen_en'=>'Order Pay',
            'explain_ar'=>$del->Code,
            'explain_en'=>$del->Code,
        ];

        $this->UserDeleteMoves($dataUser);


        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

    }

    public function DoneOrder_Pay($id){

        OrderPay::where('id',$id)->update(['Status'=>1]);

        session()->flash('success',trans('admin.Updated'));
        return back();

    }

    public function PrintOrder_Pay($id){
        $item = OrderPay::find($id);
        $Def=CompanyData::orderBy('id','desc')->first();
        $title=trans('admin.Order_Pay');
        $place='OrderPay';
        return view('admin.Accounts.PrintOrder_Pay',get_defined_vars());
    }







}
