<?php

namespace App\Http\Controllers\APIManagement;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\EWayBillApi;
use Illuminate\Http\Request;

class EWayBillApiSettingsController extends Controller
{
    function __construct()
    {
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = EWayBillApi::select
        ([            
            'id',
            'base_url',
            'email',
            'user_name',
            'password',
            'client_id',
            'client_secret',
            'gstin',
            'company_id',
            'api_type',
            'is_default',
            'status',
        ])
        ->paginate(10);

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

            $data = EWayBillApi::select([
                'id',
                'base_url',
                'email',
                'user_name',
                'password',
                'client_id',
                'client_secret',
                'gstin',
                'company_id',
                'api_type',
                'is_default',
                'status',
            ])
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('user_name', 'like', '%' . $search_query . '%');
                    // ->orWhere('enquiry_sources.enquiry_source_code', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

            return view('e-way-bill-api-settings.table', compact('data'));
        } 
        else
        {
            return view('e-way-bill-api-settings.index',compact('data'));
        }
        // api-management
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $company = Company::select('id','name')->get();
        return view('e-way-bill-api-settings.create',compact('company'));
    }

    /**
     * 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(), [
            'base_url'      => 'required',
            'email'         => 'required|email',
            'user_name'     => 'required',
            'password'      => 'required',
            'client_id'     => 'required',
            'client_secret' => 'required',
            'gstin'         => 'required',
            'api_type'      => 'required',
            'company_id'    => 'required',
        ]);

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

        EWayBillApi::create($data);

        return response()->json([
            'success' => true,
            'message' => 'E-Way Bill API 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)
    {
        $company = Company::select('id','name')->get();
        $api = EWayBillApi::find($id);

        return view('e-way-bill-api-settings.edit', compact('api','company'));
    }

    /**
     * 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(), [
            'base_url'      => 'required',
            'email'         => 'required|email',
            'user_name'     => 'required',
            'password'      => 'required',
            'client_id'     => 'required',
            'client_secret' => 'required',
            'gstin'         => 'required',
            'company_id'    => 'required',
        ]);

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

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

        $api = EWayBillApi::find($id);

        if (!$api) {
            return redirect()->back()
                ->with('error','E-Way Bill API data not found!');
        }

        $api->update($data);

        return response()->json([
            'success' => true,
            'message' => 'E-Way Bill API has been updated successfully',
        ]);
    }

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

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'reload' => true,
                'redirect' => false,
            ]
        ]);
    }
    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = EWayBillApi::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['E-Invoice Api status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = EWayBillApi::where(['is_default' => $request->status])->count();

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

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

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['EWay Bill Api default status successfully changed.'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change default'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
}

