<?php

namespace App\Http\Controllers\TaxMaster;

use App\Http\Controllers\Controller;
use App\Models\TaxMaster;
use App\Models\TaxMasterSub;
use Illuminate\Http\Request;

class TaxMasterSubController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:tax-master-sub-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        $existTaxMaster = TaxMaster::where('id', $id)->exists();

        if (!$existTaxMaster) {
            return redirect()->back()->with('error', 'Tax master not found');
        }

        $data = TaxMasterSub::select([
            'tax_master_subs.id',
            'tax_master_subs.name',
            'tax_master_subs.tax_master_id',
            'tax_master_subs.percentage',
            'tax_master_subs.calculation',
            'tax_master_subs.description',
            'tax_master_subs.priority',
            'tax_master_subs.default',
            'tax_master_subs.status',
        ])
        ->with('getTaxMaster')
        ->where('tax_master_id', $id)
        ->paginate(10);

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

            $data = TaxMasterSub::select([
                'tax_master_subs.id',
                'tax_master_subs.name',
                'tax_master_subs.tax_master_id',
                'tax_master_subs.percentage',
                'tax_master_subs.calculation',
                'tax_master_subs.description',
                'tax_master_subs.priority',
                'tax_master_subs.default',
                'tax_master_subs.status',
            ])

            ->with('getTaxMaster')
            ->where('tax_master_id', $id)
            ->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

            return view('tax-masters-sub.table', compact('data', 'id'));
        } else {
            return view('tax-masters-sub.index', compact('data', 'id'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = TaxMasterSub::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $master   = TaxMaster::all();

        return view('tax-masters-sub.create', compact('master','priority'));
    }

    /**
     * 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|unique:tax_master_subs',
            'tax_master_id' => 'required',
            'calculation'   => 'required',
            'percentage'    => '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'
        ]);

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tax Master Sub created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('tax-masters-sub.index')
            ->with('success', 'Tax Master Sub 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)
    {
        $sub    = TaxMasterSub::find($id);
        $master = TaxMaster::all();

        return view('tax-masters-sub.edit', compact('sub', 'master'));
    }

    /**
     * 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|unique:tax_master_subs,name,'.$id,
            'tax_master_id'      => 'required',
            'calculation'        => 'required',
            'percentage'         => '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'
        ]);

        $sub = TaxMasterSub::find($id);

        if (!$sub) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => "Tax Master Sub Type not found!",
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', "Tax Master Sub not found!");
        }

        $sub->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tax Master Sub has been created successfully',
            ]);
        }

        return redirect()->route('tax-masters-sub.index')
            ->with('success','Tax Master Sub updated successfully');
    }

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

        $Redirect = 'tax-masters-sub';

        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 = TaxMasterSub::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Tax Master Sub Status successfully changed'],
                   'data'=>[
                       'redirect'=>'/buckets/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Tax Master Sub Status for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
    }
}
