<?php

namespace App\Http\Controllers;

use App\Models\AccountingGroup;
use App\Models\AccountingType;
use App\Models\MasterType;
use App\Models\MenuModelPermission;
use App\Models\TaxMaster;
use App\Models\VoucherMaster;
use App\Models\VoucherTrackStatus;
use App\Models\VoucherType;
use Illuminate\Http\Request;

class VoucherTrackStatusController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:voucher-track-status-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $query = VoucherTrackStatus::select([
            'id',
            'module_code',
            'voucher_code',
            'voucher_type_code',
            'status_name',
            'status_code',
            'detail',
            'priority',
            'status'
        ]);

        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('status_name', 'like', '%' . $search_query . '%');
            });

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

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


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority       = VoucherTrackStatus::max('priority');
        $priority       = $priority != '' ? $priority : 0;
        $module_code    = MenuModelPermission::select('id','code')->get();
        $voucher_type   = VoucherType::select('id','code')->get();
        $voucher_master = VoucherMaster::select('id','voucher_code')->get();

        return view('voucher-track-status.create', compact('module_code','priority','voucher_master','voucher_type'));
    }

    /**
     * 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(), [
            'status_name'          => 'required|unique:voucher_track_statuses',
        ]);

        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'
        ]);

        $source = VoucherTrackStatus::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Voucher Track Status Created successfully',
                'data'    => $source
            ]);
        }
        return redirect()->route('.index')
            ->with('success','Voucher Track Status 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)
    {
        $track   = VoucherTrackStatus::find($id);
        $module_code    = MenuModelPermission::select('id','code')->get();
        $voucher_type   = VoucherType::select('id','code')->get();
        $voucher_master = VoucherMaster::select('id','voucher_code')->get();

        return view('voucher-track-status.edit', compact('track','module_code','voucher_master','voucher_type'));
    }

    /**
     * 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(), [
            'status_name'                  => 'required|unique:voucher_track_statuses,status_name,'.$id,
        ]);

        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_name', 'General')->first();
        // $account_group   = AccountingGroup::where('name', 'Duties & Taxes')->first();
        // $accounting_type = AccountingType::where('name', 'Liabilities')->first();

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

        // Update Account model


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

        $master->update($data);

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

        return redirect()->route('voucher-track-status.index')
            ->with('success','Voucher Track Status updated successfully');
    }

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

        $Redirect = 'voucher-track-status';

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

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