<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TaxMaster;
use App\Models\PrimaryUnit;
use App\Models\AdditionalCharge;
use App\Models\AccountingGroup;
use App\Models\Account;
use App\Models\VoucherType;

class AdditionalChargesController extends Controller
{
   function __construct()
    {
        // $this->middleware('permission:additional-charge-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = AdditionalCharge::select(
            'tax_masters.name as tax',
            'primary_units.name as unit',
            'additional_charges.*')
        ->leftJoin('tax_masters','tax_masters.id','additional_charges.tax_slab_id')
        ->leftJoin('primary_units','primary_units.id','additional_charges.primary_unit_id');
        

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');
            $search_voucher = $request->get('voucher');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('additional_charges.name', 'like', '%'.$search_query.'%');
                        })
                        ->when(!empty($search_voucher), function ($voucher) use ($search_voucher) {
                            return $voucher->where('additional_charges.voucher_type_code', 'like', '%'.$search_voucher.'%');
                        })
                        ->orderBy('priority', 'ASC')
                        ->paginate($sort_by);

            return view('additional-charge.table', compact('data'));
        }
        else
        {  
            $data   = $data->orderBy('priority', 'ASC')->paginate(10);

            return view('additional-charge.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = AdditionalCharge::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $voucher = VoucherType::select('code')->get();
        $taxname = TaxMaster::select('id','name')->get();
        $primaryunitname = PrimaryUnit::select('id','name')->get();
        $accounting_groups  = AccountingGroup::select(['id','name'])
        ->where('accounting_type_id',3)
        ->orWhere('accounting_type_id',4)
        ->orderBy('name','asc')
        ->whereNull('deleted_at')
        ->get();

        return view('additional-charge.create', compact('priority','taxname','voucher','primaryunitname','accounting_groups'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        
       

        $data = $request->except([
            '_token',
            '_method',
            'accounting_group_id',
        ]);
        $data['code'] = strtoupper($data['name']);

        $quality = AdditionalCharge::create($data);

         $accounts_type = AccountingGroup::select(['id','accounting_type_id'])->where('id',$request->accounting_group_id)->first();

        $account = Account::create([
            'name'                     => $request->name,
            'account_type_id'          => $accounts_type->accounting_type_id,
            'accounting_group_id'      => $request->accounting_group_id,
            'company_id'               => \Auth::user()->company_id ?? '',
            'code'                     => str_replace(' ','-',$request->name),
            'created_by'               => \Auth::user()->id ?? '',

        ]);

        $quality->update(['account_id' => $account->id]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Additional Charge created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('additional-charge.index')
            ->with('success','Additional Charge created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    { 
        $voucher = VoucherType::select('code')->get();
        $taxname = TaxMaster::select('id','name')->get();
        $primaryunitname = PrimaryUnit::select('id','name')->get();
        $accounting_groups  = AccountingGroup::select(['id','name'])
        ->where('accounting_type_id',3)
        ->orWhere('accounting_type_id',4)
        ->orderBy('name','asc')
        ->whereNull('deleted_at')
        ->get();
      

      $type = AdditionalCharge::find($id);

        return view('additional-charge.edit',compact('type','taxname','voucher','primaryunitname','accounting_groups'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'accounting_group_id',
        ]);

        $data['code'] = strtoupper($data['name']);

        $type = AdditionalCharge::find($id);

        if (!$type) {
            return redirect()->route('additional-charge.index')
                ->with('error','Additional Charge not found!');
        }

        $type->update($data);


        $account = Account::findOrFail($type->account_id);

        $account->update([
            'name'                     => $request->name,
            'code'                     => str_replace(' ','-',$request->name),
        ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Additional Charge updated successfully',
                'data'    => $type
            ]);
        }

        return redirect()->route('additional-charge.index')
            ->with('success','Additional Charge updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $account = AdditionalCharge::find($request->id);


        $account->delete();

        $Redirect = 'additional-charge';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = AdditionalCharge::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Additional Charge status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    

    public function isMandatory(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_mandatory' => $request->status );
            $Update = AdditionalCharge::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Is Mandatory status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    } public function isExpense(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_expense' => $request->status );
            $Update = AdditionalCharge::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Is Expense status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }

}

