<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\VoucherType;
use App\Models\VoucherTypeTerm;

class VoucherTypeTermsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id = '')
    {
        $voucher_name = VoucherType::where('id',$id)->first();

        $data = VoucherTypeTerm::when(!empty($id), function ($query) use ($id) {
                    return $query->where('voucher_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('terms_and_condition', 'like', '%'.$search_query.'%')
                            ->orWhere('position', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

            return view('voucher-type-terms.table', compact('data', 'id','voucher_name'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('voucher-type-terms.index',compact('data', 'id','voucher_name'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id = '')
    {
        $voucher_name = VoucherType::where('id',$id)->first();
        $priority = VoucherTypeTerm::max('priority');
        $priority = $priority != '' ? $priority + 1 : 1;

        return view('voucher-type-terms.create', compact('priority', 'id','voucher_name'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id = '')
    {
        $validator = \Validator::make($request->all(), [
            'position'            => 'required',
            'priority'            => 'required',
            'terms_and_condition' => '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'
        ]);
        $data['voucher_id'] = $id;

        $default_check = VoucherTypeTerm::where(['is_default' => 1, 'voucher_id' => $id])->first();

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

        $data_store = VoucherTypeTerm::create($data);

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

        return redirect()->route('voucher-type-terms.index', $id)->with('success', 'Voucher Type Term has been stored 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)
    {
        $record = VoucherTypeTerm::find($id);

        if (!$record) {
            return redirect()->back()->with('error', "Invalid Voucher Type Term ID");
        }
        $voucher_name = VoucherType::where('id',$record->voucher_id)->first();

        return view('voucher-type-terms.edit',compact('record', 'id','voucher_name'));
    }

    /**
     * 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(), [
            'position'            => 'required',
            'priority'            => 'required',
            'terms_and_condition' => '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());
        }

        $record = VoucherTypeTerm::find($id);

        if (!$record) {
            return redirect()->back()->with('error', "Invalid Voucher Type Term ID");
        }

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

        $record->update($data);

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

        return redirect()->route('voucher-type-terms.index', $record->voucher_id)->with('success', 'Voucher Type Term has been updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = VoucherTypeTerm::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 Term deleted successfully'],
        ]);
    }

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

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

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

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

    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );

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

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