<?php

namespace App\Http\Controllers\Settings;

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


class VoucherSeriesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:voucher-series-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = VoucherSeries::select([
                    'voucher_series.*',
                ])
                ->leftJoin('voucher_types','voucher_types.id','voucher_series.voucher_type_id')
                ->leftJoin('voucher_masters','voucher_masters.id','voucher_series.voucher_master_id')
                ->with('voucherType')
                ->with('voucherMaster');

        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('series_name', 'like', '%'.$search_query.'%');
                    })
                ->paginate($sort_by);
            return view('voucher-series.table', compact('data'));
        }
        else
        {
            $search_query = $request->get('search');
            $data         = $data->when(!empty($search_query), function ($query) use ($search_query) {
                                // $query->whereHas('voucherType', function ($q) use ($search_query) {
                                    $query->where('voucher_types.name', 'like', '%'.$search_query.'%');
                                    $query->OrWhere('voucher_masters.voucher_name', 'like', '%'.$search_query.'%');
                                // });

                                // $query->whereHas('voucherMaster', function ($q) use ($search_query) {
                                //     $q->OrWhere('voucher_name', 'like', '%'.$search_query.'%');
                                // });
                            });
            // $data         = $data->when(!empty($search_query), function ($query) use ($search_query) {
            //                     $query->whereHas('voucherMaster', function ($q) use ($search_query) {
            //                         $q->where('voucher_name', 'like', '%'.$search_query.'%');
            //                     });
            //                 });
                            
            $data      =  $data->paginate(10);

            return view('voucher-series.index',compact('data'));
        }
    }



    



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

        return view('voucher-series.create', compact('voucher_types','voucher_masters'));
    }


   

    /**
     * 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(), [
            'series_name'     => 'required',
            'frequency'       => 'required',
            // 'voucher_type_id' => 'required',
            'length'          => 'required|numeric'
        ]);

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

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $length             = (16 - ($request->length ?? 0)) - strlen($request->start_from);
        $concatenatedString = $request->prefix . $request->separator . $request->separator . $request->postfix;
        $concatenated_ID = $request->prefix . $request->separator . str_pad($request->start_from, $request->length, '0', STR_PAD_LEFT) . $request->separator . $request->postfix;

        if (strlen($concatenatedString) > $length) {
            return response()->json([
                'success' => false,
                'message' =>  'Your ID will look like ' . $concatenated_ID . '.<br> Total length of ID can not be greater than 16 char.',
                'data'    => []
            ]);
        }

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

        $voucher_series = VoucherSeries::create($data);

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

        return view('voucher-series.edit', compact('voucher_types','voucher_masters','series'));
    }

    /**
     * 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(), [
            'series_name'     => 'required',
            'frequency'       => 'required',
            // 'voucher_type_id' => 'required',
            'length'          => 'required|numeric'
        ]);

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

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $length             = (16 - ($request->length ?? 0)) - strlen($request->start_from);
        $concatenatedString = $request->prefix . $request->separator . $request->separator . $request->postfix;
        $concatenated_ID = $request->prefix . $request->separator . str_pad($request->start_from, $request->length, '0', STR_PAD_LEFT) . $request->separator . $request->postfix;

        if (strlen($concatenatedString) > $length) {
            return response()->json([
                'success' => false,
                'message' =>  'Your ID will look like ' . $concatenated_ID . '.<br> Total length of ID can not be greater than 16 char.',
                'data'    => []
            ]);
        }

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

        $voucher_series = VoucherSeries::find($id);

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

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

        $voucher_series->update($data);

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

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

        $data->delete();

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