<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\VoucherType;
use App\Models\VoucherMaster;
use App\Models\VoucherSeries;
use App\Models\LetterHead;

class VoucherTypesController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:voucher-types-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id = '')
    {
        $data = VoucherType::select([
                    '*',
                ])
                ->with('voucherMaster')
                ->where('voucher_master_id', $id);

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

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

            return view('voucher-types.table', compact('data','id'));
        }
        else
        {
            $data           = $data->paginate(10);
            $voucher_master = VoucherMaster::find($id);

            return view('voucher-types.index',compact('data','id', 'voucher_master'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority        = VoucherType::max('priority');
        $priority        = $priority != '' ? $priority : 0;
        // $voucher_masters = VoucherMaster::where('status', 1)->get();

        return view('voucher-types.create', compact('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:voucher_types,name,NULL,id,voucher_master_id,'.$request->voucher_master_id,
            'code'                  => 'required|unique:voucher_types,code,NULL,id,voucher_master_id,'.$request->voucher_master_id,
            'priority'              => 'required',
            'voucher_master_id'     => 'required',
            'default_price_type'    => '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'
        ]);

        $default_check = VoucherType::where(['is_default' => 1,'status' => 1, 'voucher_master_id' => $request->voucher_master_id])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        $voucher_master = VoucherType::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Voucher Type 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_type = VoucherType::find($id);
        // $voucher_masters = VoucherMaster::where('status', 1)->get();

        return view('voucher-types.edit', compact('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(), [
            'name'                  => 'required|unique:voucher_types,name,' . $id . ',id,voucher_master_id,'.$request->voucher_master_id,
            'code'                  => 'required|unique:voucher_types,code,' . $id . ',id,voucher_master_id,'.$request->voucher_master_id,
            'priority'              => 'required',
            'voucher_master_id'     => 'required',
            'default_price_type'    => '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'
        ]);

        $voucher_type = VoucherType::find($id);

        if (!$voucher_type) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Voucher Type not found!',
                ]);
            }

            return redirect()->back()
                ->with('error','Voucher Type not found!');
        }

        $voucher_type->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Voucher Type updated successfully.',
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $series = VoucherSeries::where('voucher_type_id', $request->id)->count();

        if ($series > 0) {
            return response()->json([
                'success' => false,
                'message' => ['Sub record found. You can not deleted this Voucher Type.']
            ]);
        }

        $data = VoucherType::find($request->id);

        if ($data->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        return response()->json([
            'success' => true,
            'message' => ['Voucher Type deleted successfully'],
        ]);
    }

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

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Voucher Type status changed successfully.'],
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                ]);
            }
        }
    }

    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = VoucherType::where(['is_default' => $request->status, 'voucher_master_id' => $request->voucher_master_id])->count();

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

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

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Voucher Type default status successfully changed.'],
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                ]);
            }
        }
    }

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

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Voucher Type status changed successfully.'],
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                ]);
            }
        }
    }

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

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Voucher Type status changed successfully.'],
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                ]);
            }
        }
    }

    public function editLetterHead($id)
    {
        $letter_heads = LetterHead::get();
        $voucher_type = VoucherType::find($id);

        return view('voucher-types.letter-head-settings', compact('letter_heads','id','voucher_type'));
    }

    public function updateLetterHead(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'letterhead_id' => '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 = [
            'letter_head_id' => $request->letterhead_id
        ];

        $voucher_type = VoucherType::find($id);

        if (!$voucher_type) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Letter Head settings not found!',
                ]);
            }
        }

        $voucher_type->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Letter Head settings updated successfully.',
            ]);
        }
    }
}
