<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
use App\Models\EmailVerifier;
use App\Http\Helper\Helper;
use Auth;
use Crypt;

class EmailVerifierController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        Helper::checkPermissions('email_verifiers');
        $page = "lists_email_verifiers";
        $page_title = __('app.email_verifiers');
        $breadcrumbs = [
            __('app.email_verifiers') => route('email_verifiers.index'),
            __('app.manage') => '#'
        ];  
        return view('email_verifiers.index',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
    * Retrun JSON datatable data
    */
    public function getEmailVerifiers(Request $request): void
    {
        $result = EmailVerifier::select('id', 'name', 'type', 'attributes', 'is_active', 'total_verified', 'created_at')
          ->whereAppId(Auth::user()->app_id);

        $columns = ['id', 'id', 'name', 'type', 'total_verified', 'is_active', 'created_at'];

        $data = Helper::dataFilters($request, $result, $columns);

        $result = $data['result'];
        $email_verifiers = $result->get();

        $data =  Helper::datatableTotals($data['total']);

        foreach($email_verifiers as $email_verifier) {
          $checkbox = "<input type=\"checkbox\" value=\"{$email_verifier->id}\" class=\"form-check-input\">";

          $actions = '<div class="btn-group">';
          $actions .= '<button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">'.__('app.actions').'</button>';
          $actions .= '<ul class="dropdown-menu" style="">';

          $actions.= '<li><a class="dropdown-item"  href="javascript:;" onclick="viewModal(\'modal\', \''.route('email_verifiers.edit', [$email_verifier->id]).'\')"><i class="bi bi-pencil-square"></i> '.__('app.edit').'</a></li>';
          $actions.= '<li><a class="dropdown-item"  href="javascript:;" onclick="viewModal(\'modal\', \''.route('verify.email', ['id' => $email_verifier->id]).'\')"><i class="bi bi-envelope-check"></i> '.__('app.verify_email').'</a></li>';
          $actions.= '<li><a class="dropdown-item"  href="javascript:;" onclick="viewModal(\'modal\', \''.route('verify.email.list', ['id' => $email_verifier->id]).'\')"><i class="bi bi-card-checklist"></i> '.__('app.verify_list').'</a></li>';
          $actions .= '<li><a class="dropdown-item text-danger" href="javascript:;" onclick="destroy(\''.$email_verifier->id.'\', \''.route('email_verifiers.destroy', [$email_verifier->id]).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';
          $actions .= '</ul>
            </div>';

          $status = $email_verifier->is_active 
                ? "<span class='badge bg-success-gradient'>".__('app.yes')."</small>"
                : "<span class='badge bg-danger-gradient'>".__('app.no')."</small>";

          $data['data'][] = [
            "DT_RowId" => "row_{$email_verifier->id}",
            $checkbox,
            $email_verifier->id,
            $email_verifier->name,
            $email_verifier->type,
            $email_verifier->total_verified,
            $status,
            Helper::datetimeDisplay($email_verifier->created_at),
            $actions
          ];
        }
        echo json_encode($data);
    }

    /**
    * Retrun create view
    */
    public function create(): View
    {
        Helper::checkPermissions('email_verifiers'); // check user permission
        return view('email_verifiers.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
        'name' => 'required|string',
        ]);
        $data = $this->_emailVerifierData($request);

        EmailVerifier::create($data);

        activity('create')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.email_verifiers') . " ({$request->name}) ". __('app.log_create')); // log
        
        return redirect()->back()
            ->with('success', __('app.email_verifiers') . ' ' . __('app.log_create'));

    }

    /**
    * Retrun edit view
    */
    public function edit(EmailVerifier $email_verifier): view
    {
        Helper::checkPermissions('email_verifiers'); // check user permission
        return view('email_verifiers.edit')->with(compact('email_verifier'));
    }

    /**
    * Update data
    */
    public function update(Request $request, $id)
    {
        $request->validate([
          'name' => 'required|string',
        ]);

        $data = $this->_emailVerifierData($request);

        $email_verifier = EmailVerifier::findOrFail($id);
        $email_verifier->fill($data)->save();

        activity('update')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.email_verifiers') . " ({$request->name}) ". __('app.log_update')); // log
        return redirect()->back()
            ->with('success', __('app.email_verifiers') . ' ' . __('app.log_create'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $id, Request $request): JsonResponse
    {
        if(!empty($request->action)) {
          $ids = array_values($request->ids);
          $names = json_encode(array_values(EmailVerifier::whereIn('id', $ids)->pluck('name')->toArray()));
          $destroy = EmailVerifier::whereIn('id', $ids)->delete();
        } else {
          $names = EmailVerifier::whereId($id)->value('name');
          $destroy = EmailVerifier::destroy($id);
        }
        
        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.email_verifiers') . " ({$names}) ". __('app.log_delete'));

        $data = [
            'success' => true,
            'message' => __('app.deleted_successfully')
        ];

        return response()->json($data, 200); 
    }

    /**
    * Retrun data for store or update
    */
    public function _emailVerifierData($request)
    {
        $input = $request->except('_token');
        $input['attributes'] = $this->_emailVerifierAttributes($input);
        $input['app_id'] = Auth::user()->app_id;
        $input['user_id'] = Auth::user()->id;
        return $input;
    }

    /**
    * Retrun JSON data for sending server
    */
    public function _emailVerifierAttributes($data)
    {
        switch($data['type']) {
          case 'relayzo':
          case 'kickbox':
          case 'neverbounce':
          case 'sendgrid':
          case 'mailgun':
          case 'bulkemailchecker':
            $attributes = [
              'api_key' => !empty($data['api_key']) ? Crypt::encrypt($data['api_key']) : null
            ];
          break;
          case 'emailoversight':
            $attributes = [
              'api_key' => !empty($data['api_key']) ? Crypt::encrypt($data['api_key']) : null,
              'list_id' => !empty($data['list_id']) ? $data['list_id'] : null,
            ];
          break;
          default: 
            $attributes = null;
          break;
        }
        return json_encode($attributes);
    }

    /**
    * Retrun email verifiers fields respectively
    */
    public function getEmailVerifiersFields($type, $action, $id=null): view
    {
        if(!empty($id)) {
          $data = json_decode(EmailVerifier::whereId($id)->app()->value('attributes'));
        }
        return view('email_verifiers.attributes')->with(compact('type', 'action', 'data'));
    }

    /**
    * Verify Email
    */
    public function verifyEmail(Request $request)
    {
        Helper::checkPermissions('email_verifiers'); // check user permission
        $email_verifier = EmailVerifier::whereId($request->id)->first();
        if ($request->isMethod('get')) {
            $email = $request->email ?? null;  
            return view('email_verifiers.verify_email')->with(compact('email_verifier', 'email'));
        } else {
            if(filter_var($request->email, FILTER_VALIDATE_EMAIL) === false) {
                return response()->json([
                    'verify' => false,
                    'message' => __('app.valid_email_required')
                ], 200); // HTTP 200 OK
            }        
            
            $data_verifier = json_decode($email_verifier->attributes, true);
            $data_verifier['type'] = $email_verifier->type;
            $data_verifier['email'] = $request->email;

            $response = Helper::verifyEmail($data_verifier, $encrypt=true);

            if($response['increment']) {
                \App\Models\Contact::whereEmail($request->email)->update(['is_verified' => $response['success']]);
                $verifier = \App\Models\EmailVerifier::whereId($request->id)->first();
                $verifier->increment('total_verified');
            } 

            return response()->json([
                'verify' => $response['success'],
                'message' => $response['message']
            ], 200); // HTTP 200 OK

        }
    }

    /**
    * Verify Email List
    */
    public function verifyEmailList(Request $request)
    {
        Helper::checkPermissions('email_verifiers'); // check user permission
        $email_verifier = EmailVerifier::whereId($request->id)->first();

        if($request->isMethod('post')) {
          $request->validate([
            'list_ids' => 'required'
          ],
          [
            'list_ids.required' => 'Please select at least one List.',
          ]);

          \App\Jobs\ListVerify::dispatch($request->list_ids, $request->id, Auth::user()->id)
            ->delay(now()->addSeconds(10));
          \Artisan::call('queue:work', ['--once' => true]); // execute queue

          $list_names = json_encode(array_values(\App\Models\Lists::whereIn('id', $request->list_ids)->pluck('name')->toArray()));

          // Save activity log
          activity('verify')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.list') . " ({$list_names}) ". __('app.log_verify_list')); // log
        } else {
          $list_id = $request->list_id ?? null;  
          return view('email_verifiers.verify_list')->with(compact('email_verifier', 'list_id'));
        }
    }
}
