<?php

namespace App\Http\Controllers\APIManagement;

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

class EmailApiController extends Controller
{
    function __construct()
    {
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = EmailApi::select
        ([          
            'id',  
            'host',
            'user_name',
            'form_email',
            'form_name',
            '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 = EmailApi::select([
                'id',
                'host',
                'user_name',
                'form_email',
                'form_name',
                'api_type',
                'is_default',
                'status',
            ])
                ->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('user_name', 'like', '%' . $search_query . '%')
                    ->orWhere('host', 'like', '%'.$search_query.'%')
                    ->orWhere('form_email', 'like', '%'.$search_query.'%')
                    ->orWhere('form_name', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

            return view('e-mail-apis.table', compact('data'));
        } 
        else
        {
            return view('e-mail-apis.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-mail-apis.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(), [
            'host'          => 'required',
            'user_name'     => 'required',
            'form_email'    => 'required|email',
            'form_name'     => 'required',
            'api_type'      => 'required',
        ]);

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

        EmailApi::create($data);

        return response()->json([
            'success' => true,
            'message' => 'E Mail Api has been stored successfully',
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // $api = EmailApi::find($id);

        // return view('api-management.show', compact('api'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $api = EmailApi::find($id);

        return view('e-mail-apis.edit', compact('api'));
    }

    /**
     * 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(), [
            'host'          => 'required',
            'user_name'     => 'required',
            'form_email'    => 'required|email',
            'form_name'     => 'required',
        ]);

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

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

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

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

        $api->update($data);

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

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

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['E-Mail 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  = EmailApi::where(['is_default' => $request->status])->count();

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

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

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

