<?php

namespace App\Http\Controllers\TaxMaster;

use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AccountingGroup;
use App\Models\AccountingType;
use App\Models\MasterType;
use App\Models\Scopes\GlobalStatusScope;
use App\Models\TaxCategory;
use App\Models\TaxMaster;
use Illuminate\Http\Request;
use Str;

class TaxMasterController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:tax-masters-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = TaxMaster::select([
            'tax_masters.id',
            'tax_masters.name',
            'tax_masters.code',
            'tax_masters.tax_category_id',
            'tax_masters.description',
            'tax_masters.total_percentage',
            'tax_masters.calculation',
            'tax_masters.priority',
            'tax_masters.default',
            'tax_masters.status',
        ])->with('getTaxCategory');

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

            $query->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%' . $search_query . '%');
            });

            $data = $query->paginate($sort_by);

            return view('tax-masters.table', compact('data'));
        } else {
            $data = $query->paginate(10);
            return view('tax-masters.index', compact('data'));
        }
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = TaxMaster::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $category = TaxCategory::select('id', 'name')->where('status','1')->get();
        return view('tax-masters.create', compact('category','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_masters',
            'tax_category_id'    => 'required',
            'calculation'        => 'required',
            'total_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'
        ]);

        $account_type    = MasterType::where('type_code', 'GENERAL')->first();
        $account_group   = AccountingGroup::where('code', 'DUTIES_AND_TAXES')->first();
        $accounting_type = AccountingType::where('code', 'LIABILITIES')->first();

        $taxMaster = TaxMaster::create($data);

        $account = Account::create([
            'name'                     => $request->name,
            'account_type_id'          => $account_type->id,
            'accounting_group_id'      => $account_group->id,
            'account_category_id'      => $accounting_type->id,
            'company_id'               => \Auth::user()->company_id ?? '',
            'tax_register_category_id' => 1,
            'code'                     => str_replace(' ','-',$request->name),
            'primary_account'          => 1,
            'created_by'               => \Auth::user()->id ?? '',
            'opening_balance'          => 0.00,


        ]);

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

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Tax Master created successfully',
                'data'    => $taxMaster
            ]);
        }
        return redirect()->route('tax-masters.index')
            ->with('success', 'Tax Master 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)
    {
        $master   = TaxMaster::find($id);
        $category = TaxCategory::select('id', 'name')->where('status','1')->get();

        return view('tax-masters.edit', compact('category', '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)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'name'                  => 'required|unique:tax_masters,name,'.$id,
            'tax_category_id'       => 'required',
            'calculation'           => 'required',
            'total_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'
        ]);

        $account_type    = MasterType::where('type_code', 'GENERAL')->first();
        $account_group   = AccountingGroup::where('code', 'DUTIES_AND_TAXES')->first();
        $accounting_type = AccountingType::where('code', 'LIABILITIES')->first();

        // $master = TaxMaster::find($id);
        $master = TaxMaster::findOrFail($id);
        $master->update($data);

        // Update Account model
        $account = Account::findOrFail($master->account_id);
        $account->update([
            'name'                => $request->name,
            'account_type_id'     => $account_type->id,
            'accounting_group_id' => $account_group->id,
            'account_category_id' => $accounting_type->id,
        ]);

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

        $master->update($data);

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

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

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

        $Redirect = 'tax-masters';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('default' => $request->status );
            $count  = TaxMaster::where(['default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Task!'],
                    'data'    => []
                ]);
            }

            $Update = TaxMaster::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Tax Master default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/task/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function changeStatus(Request $request)
    {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = TaxMaster::where('id', '=', $request->id)->update($data);

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