<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\AbdmApiCall;
use App\Models\StudentHouse;
use App\Models\AbdmApiCallsUpload;
use App\Imports\AbdmApiCallsExcelImport;
use Maatwebsite\Excel\Facades\Excel;




class AbdmApiCallsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id = "")
    {
        $abdm_api_calls = AbdmApiCall::select(
            'abdm_api_calls.id as id',
            'abdm_api_calls.api_id as api_id',
            'abdm_api_calls.request_name as request_name',
            'abdm_api_calls.request_sandbox_base_url as request_sandbox_base_url',
            'abdm_api_calls.request_production_base_url as request_production_base_url',
            'abdm_api_calls.request_sub_url as request_sub_url',
            'abdm_api_calls.request_type as request_type',
            'abdm_api_calls.status as status'
        )->leftJoin('abdm_apis', 'abdm_apis.id', '=', 'abdm_api_calls.api_id')
        ->when(!empty($id), function ($query) use ($id) {
            return $query->where('abdm_api_calls.api_id', $id)
                         ->whereNotNull('abdm_api_calls.api_id');
        })
        ->orderBy('abdm_api_calls.request_name', 'ASC');

        if (empty($id)) {
            $abdm_api_calls = AbdmApiCall::orderBy('request_name', 'ASC');
        }

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

            $abdm_api_calls = $abdm_api_calls->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('abdm_api_calls.request_name', 'like', '%'.$search_query.'%')
                    ->orWhere('abdm_api_calls.request_production_base_url', 'like', '%'.$search_query.'%')
                    ->orWhere('abdm_api_calls.request_sandbox_base_url', 'like', '%'.$search_query.'%')
                    ->orWhere('abdm_api_calls.request_sub_url', 'like', '%'.$search_query.'%')
                    ->orWhere('abdm_api_calls.request_type', 'like', '%'.$search_query.'%');
            })->paginate($sort_by);

            return view('abdm_api_calls.table', compact('abdm_api_calls', 'id'));
        } else {
            $abdm_api_calls = $abdm_api_calls->paginate(10);

            return view('abdm_api_calls.index', compact('abdm_api_calls', 'id'));
        }
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * 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)
    {
        $abdm_api_calls = AbdmApiCall::findOrFail($id);

        return view('accounts.edit-abdm_api_calls', compact('abdm_api_calls'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $abdm_api_calls = AbdmApiCall::findOrFail($id);
        $abdm_api_calls->delete();

        return response()->json([
            'success' => true,
            'message' => 'API Call deleted successfully',
            'data' => [
                'redirect' => '', 
            ]
        ]);
    }

    public function createAbdmApiCalls($id = "")
    {
        $abdm_api_calls = AbdmApiCall::select(
            'abdm_api_calls.id as id',
            'abdm_api_calls.request_name as request_name',
            'abdm_api_calls.request_sandbox_base_url as request_sandbox_base_url',
            'abdm_api_calls.request_production_base_url as request_production_base_url' ,
            'abdm_api_calls.request_sub_url as request_sub_url' ,
            'abdm_api_calls.request_type as request_type' ,
            'abdm_api_calls.status as status' ,
        )->get();

       $abdm_api_calls_id =  AbdmApiCall::select('abdm_api_calls.id as abdm_api_calls.id')
       ->get();

        return view('accounts.create-abdm_api_calls', compact('abdm_api_calls' , 'abdm_api_calls_id' ,'id'));  
    }

    public function storeAbdmApiCalls(Request $request , $id ="")
    {
        $validator = \Validator::make($request->all(), [
            'request_name'                => 'required',
            'request_sandbox_base_url'    => 'required',
            'request_production_base_url' => 'required',
            'request_sub_url'             => 'required',
            'request_type'                => 'required',
        ]);

        if ($validator->fails()) {

            return response()->json([
                'success'  => false,
                'message'  => $validator->getMessageBag()->first(),
                'data'     => [
                'redirect' => 'abdm-api-calls-index'],
            ]);
        }

        $abdm_api_calls = [
            'api_id'                      => $id,
            'request_name'                => $request->request_name,
            'request_sandbox_base_url'    => $request->request_sandbox_base_url,
            'request_production_base_url' => $request->request_production_base_url,
            'request_sub_url'             => $request->request_sub_url,
            'request_type'                => $request->request_type,
        ];


        AbdmApiCall::create($abdm_api_calls);

        return response()->json([
            'success'  => true,
            'message'  => 'Api Call created successfully',
            'data'     => [
            'redirect' => 'abdm-api-calls-index', 
            ]
        ]);
    }

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

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

    public function updateAbdmApiCalls(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'request_name'                => 'required',
            'request_sandbox_base_url'    => 'required',
            'request_production_base_url' => 'required',
            'request_sub_url'             => 'required',
            'request_type'                => 'required',
        ]);

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

        $abdm_api_calls = AbdmApiCall::findOrFail($id);
        $abdm_api_calls->update($request->all());

        return response()->json([
            'success'  => true,
            'message'  => 'Abdm API Call updated successfully',
            'data'     => [
            'redirect' => 'abdm-api-calls-index', 
            ]
        ]);
    }

    public function importForm(Request $request)
    {
        return view('abdm_api_calls.import');
    }

    public function importBulkAbdmApiCalls(Request $request)
    {

        ini_set('max_execution_time', 500);

        $validator = \Validator::make($request->all(), [
            'file' => 'required|mimes:xlsx'
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'The file must be latest version of excel after 2003. File of type: xlsx .',
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        
        $records  = [];
        $data     = Excel::toArray(new AbdmApiCallsExcelImport, $request->file('file'));
        $data     = isset($data[0]) ? $data[0] : [];
        $headings = [];

        if (isset($data[0])) {
            $headings = $data[0];
            unset($data[0]);
        }

        if (!empty($data)) {
            // Truncate table.
            \DB::table('abdm_api_calls_uploads')->truncate();

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

                if (empty($record[array_search("Request Name", $headings)])) {
                    continue;
                }

                // Populate the $records array
                $records[$key] = [
                    'request_name'                => $record[array_search("Request Name", $headings)],
                    'request_sandbox_base_url'    => $record[array_search("Sandbox Base Url", $headings)],
                    'request_production_base_url' => $record[array_search("Production Base Url", $headings)],
                    'request_sub_url'             => $record[array_search("Sub Url", $headings)],
                    'request_type'                => $record[array_search("Request Type ", $headings)],
                    'created_at'                  => now(),
                    'updated_at'                  => now(),
                ];
            }

            AbdmApiCallsUpload::insert($records);

            return response()->json([
                'success' => true,
                'message' => 'Abdm Api Calls are uploaded successfully.',
                'data'    => []
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Abdm Api Calls data not found!',
                'data'    => []
            ]);
        }
    }

    public function importAbdmApiCallsForm(Request $request)
{
    $data = AbdmApiCallsUpload::query(); // Start a new query

    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('abdm_api_calls_uploads.request_name', 'like', '%'.$search_query.'%')
                ->orWhere('abdm_api_calls_uploads.request_sandbox_base_url', 'like', '%'.$search_query.'%')
                ->orWhere('abdm_api_calls_uploads.request_production_base_url', 'like', '%'.$search_query.'%')
                ->orWhere('abdm_api_calls_uploads.request_sub_url', 'like', '%'.$search_query.'%')
                ->orWhere('abdm_api_calls_uploads.request_type', 'like', '%'.$search_query.'%');
        })
        ->orderBy('abdm_api_calls_uploads.id', $sort_type ?? 'asc') // Add ordering
        ->paginate($sort_by);

        return view('abdm_api_calls.abdm-api-calls-import-table', compact('data'))->render();
    } else {
        $data = $data->paginate(10);
        return view('abdm_api_calls.bulk-import', compact('data'));
    }
}


    public function clearData()
    {
        AbdmApiCallsUpload::truncate();

        return response()->json([
            'success' => true,
            'message' => 'Temp data cleared successfully.'
        ]);
    }

    public function importDestroy(Request $request)
    {
        AbdmApiCallsUpload::find($request->id)->delete();

        $Redirect = 'abdm-api-calls-import.create';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);

    }


    public function updateAbdmApiCallImport(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'request_name'                => 'required',
            'request_sandbox_base_url'    => 'required',
            'request_production_base_url' => 'required',
            'request_sub_url'             => 'required',
            'request_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_name'                => $request->request_name,
            'request_sandbox_base_url'    => $request->request_sandbox_base_url,
            'request_production_base_url' => $request->request_production_base_url,
            'request_sub_url'             => $request->request_sub_url,
            'request_type'                => $request->request_type,
        ];

        AbdmApiCallsUpload::whereId($id)->update($data);

            return response()->json([
                'success' => true,
                'message' => 'success','Abdm Api Call updated successfully',
                'data' => [
                ],
            ]);
    }

    public function importAbdmApiCalls(Request $request)
    {
        ini_set('max_execution_time', 500);
        $data = AbdmApiCallsUpload::all();
        $duplicate = $unique = $emptyRequestName = $emptySandboxBaseUrl = $recordsDeleted = 0;

        if (count($data) > 0) {
            foreach ($data as $key => $record) {
                if (empty($record->request_name) || empty($record->request_sandbox_base_url)) {
                    if (empty($record->request_name)) {
                        $emptyRequestName += 1;
                    }
                    if (empty($record->request_sandbox_base_url)) {
                        $emptySandboxBaseUrl += 1;
                    }
                    continue;
                }

                $existingAbdmApiCall = AbdmApiCall::where('request_sandbox_base_url', $record->request_sandbox_base_url)
                    ->where('request_name', $record->request_name)
                    ->first();

                if (!$existingAbdmApiCall) {
                    AbdmApiCall::create([
                        'request_name'                => $record->request_name,
                        'request_sandbox_base_url'    => $record->request_sandbox_base_url,
                        'request_production_base_url' => $record->request_production_base_url,
                        'request_sub_url'             => $record->request_sub_url,
                        'request_type'                => $record->request_type,
                    ]);
                    $unique += 1;
                } else {
                    $duplicate += 1;
                }
            }

            return response()->json([
                'success' => true,
                'message' => $unique . 'Abdm Api Calls imported. ' . $duplicate . ' duplicate records skipped.',
                'data' => [
                    'inserted'     => $unique,
                    'deleted'      => $recordsDeleted,
                    'not_inserted' => $emptyRequestName + $emptySandboxBaseUrl,
                ],
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Abdm Api Calls data not found!',
                'data'    => [],
            ]);
        }
    }


    public function editAbdmApiCalls(Request $request, $id)
    {
        $data = AbdmApiCallsUpload::find($id);
        return view('abdm_api_calls.edit-abdm_api_calls_import', compact('data'));
    }

}
