<?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\MasterSetting;
use App\Models\AdvanceSetting;

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

        $data = VoucherMaster::select([
            'id',
            'voucher_name',
            'voucher_code',
            'serial_no_format',
            'decimal_length',
            'tax_calculation',
            'status',
        ]);

        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('voucher_name', 'like', '%'.$search_query.'%');
                        })
                        ->paginate($sort_by);
                        // dd($data);
            return view('vouchers-master.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);
            return view('vouchers-master.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('vouchers-master.create');
    }

    /**
     * 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(), [
            'voucher_name'     => 'required|unique:voucher_masters,voucher_name',
            'voucher_code'     => 'required|unique:voucher_masters,voucher_code',
            'serial_no_format' => 'required',
            'decimal_length' => 'required|integer|min:0|max:9',
        ]);

        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_store = VoucherMaster::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Voucher 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)
    {
        $data = VoucherMaster::find($id);

        if (!$data) {
            return response()->json([
                'success' => true,
                'message' => 'Voucher Master not found.',
            ]);
        }

        return view('vouchers-master.edit', compact('data'));
    }

    /**
     * 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(), [
            'voucher_name'     => 'required|unique:voucher_masters,voucher_name,'.$id.',id',
            'voucher_code'     => 'required|unique:voucher_masters,voucher_code,'.$id.',id',
            'serial_no_format' => 'required',
            'decimal_length'   => 'required|integer|min:0|max:9',
        ]);

        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_master = VoucherMaster::find($id);

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

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

        $voucher_master->update($data);

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

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

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

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

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

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

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Voucher Master status changed successfully.'],
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                ]);
            }
        }
    }
    public function changeTaxCalculation(Request $request)
    {
        // dd($request->all());
        if ($request->ajax()) {
            $data   = array('tax_calculation' => $request->status );
            $Update = VoucherMaster::where('id', '=', $request->id)->update($data);

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

    public function voucherMasterSettings(Request $request, $id, $type_id)
    {
        // $master_settings = MasterSetting::where('status',1)->get();

        $existingField = AdvanceSetting::where(['voucher_master_id' => $id, 'voucher_type_id' => $type_id])->get()
                ->pluck('value', 'master_setting_id');


        // Main Query
        $master_settings = AdvanceSetting::leftJoin('master_settings', function($join) use ($id, $type_id) {
            $join->on('advance_settings.master_setting_id', '=', 'master_settings.id')
                ->where('advance_settings.voucher_master_id', '=', $id)
                ->where('advance_settings.voucher_type_id', '=', $type_id);
        })
        ->where('master_settings.status', 1)
        ->select('master_settings.*', 'advance_settings.value as setting_value')
        ->groupBy('master_settings.id')
        ->get();

        $type   = VoucherType::select('name')->where('id', $type_id)->first();
        $master = VoucherMaster::select('voucher_name as name')->where('id', $id)->first();

        return view('advance-settings.voucher-master-settings', compact(
            'id',
            'type',
            'master',
            'type_id',
            'existingField',
            'master_settings',
        ));
    }

    public function storeVoucherMasterSettings(Request $request, $id, $type_id)
    {
        $data = $request->except([
            '_token',
            '_method'
        ]);

        foreach($data as $key => $value) {

            if(!empty($value)){
                AdvanceSetting::updateOrCreate([
                    "master_setting_id" => $key,
                    "voucher_master_id" => $id,
                    "voucher_type_id"   => $type_id,
                ],[
                    "value" => $value
                ]);  
            }
        }

        return redirect()->route('voucher-master-types', $id)->with('success', 'Master Settings updated successfully.');
    }


    public function createVoucherMasterSettings(Request $request, $id, $type_id)
    {
        $master_settings = MasterSetting::leftJoin('advance_settings', function($join) use ($id, $type_id) {
            $join->on('advance_settings.master_setting_id', '=', 'master_settings.id')
                 ->where('advance_settings.voucher_master_id', $id)
                 ->where('advance_settings.voucher_type_id', $type_id);
        })
        ->whereNull('advance_settings.id')
        ->select('master_settings.*')
        ->get();

        return view('accounts.create-voucher-master-settings', compact('master_settings', 'id', 'type_id'));
    }


    public function storeVoucherMasterSetting(Request $request, $id, $type_id)
    {
        $validator = \Validator::make($request->all(), [
            'master_settings' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->getMessageBag()->first(),
                'data'    => []
            ]);
        }

        // Retrieve the single MasterSetting instance
        $master_setting = MasterSetting::find($request->master_settings);

        if (!$master_setting) {
            return response()->json([
                'success' => false,
                'message' => 'Master setting not found',
                'data'    => []
            ]);
        }

        AdvanceSetting::updateOrCreate([
            "master_setting_id" => $request->master_settings,
            "voucher_master_id" => $id,
            "voucher_type_id"   => $type_id,
        ],[
            "value" => $master_setting->default_value
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Voucher Master Setting successfully created',
            'data'    => [
                'redirect' => route('voucher-master-settings', ['id' => $id, 'type_id' => $type_id])
            ]
        ]);
    }




}

