<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\CreateFblRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use App\Models\Fbl;
use App\Http\Helper\Helper;
use Illuminate\View\View;
use Webklex\PHPIMAP\ClientManager;
use Auth;
use Crypt;

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

    /**
    * Retrun JSON datatable data
    */
    public function getfbls(Request $request)
    {
        $result = Fbl::select('id', 'email', 'host', 'method', 'is_active', 'is_validate', 'created_at')
          ->app();

        $columns = ['id', 'id', 'email', 'host', 'method', 'is_active', 'is_validate', 'created_at'];

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

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

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

        foreach($fbls as $fbl) {
          $checkbox = "<input class=\"form-check-input\" type=\"checkbox\" value=\"{$fbl->id}\">";
          $actions = '<div class="btn-group">
            <button type="button" class="btn btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">'.__('app.actions').' <span class="caret"></span></button><ul class="dropdown-menu" role="menu">';
          $actions.= '<li><a class="dropdown-item" href="'.route('fbls.edit', [$fbl->id]).'"><i class="bi bi-pencil-square"></i> '.__('app.edit').'</a></li>';          
          $actions .= '<li><a class="dropdown-item" href="'.route('fbl.copy', [$fbl->id]).'"><i class="bi bi-copy"></i> '.__('app.copy').'</a></li>';
          $actions .= '<li><a class="dropdown-item text-danger" href="javascript:;" onclick="destroy(\''.$fbl->id.'\', \''.route('fbls.destroy', [$fbl->id]).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';
          $actions .= '</ul>
            </div>';

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

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

          $data['data'][] = [
            "DT_RowId" => "row_{$fbl->id}",
            $checkbox,
            $fbl->id,
            $fbl->email,
            $fbl->host,
            $fbl->method,
            $status,
            $validate,
            Helper::datetimeDisplay($fbl->created_at),
            $actions
          ];
        }
        echo json_encode($data);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        Helper::checkPermissions('fbl_servers');
        $page = "fbl_servers";
        $page_title = __('app.add_new_fbl_server');
        $breadcrumbs = [
            __('app.fbl_servers') => route('fbls.index'),
            __('app.add_new_fbl_server') => '#'
        ];

        return view('fbls.create',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(CreateFblRequest $request): RedirectResponse
    {
        $data = $this->_fblData($request);
        $fbl = Fbl::create($data);

        activity('create')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.fbl') . " ({$request->email}) ". __('app.log_create'));

        if(isset($data['save_continue']))
            return redirect()->route('fbls.create')
            ->with('success', ($request->email . ' ' . __('app.created_successfully')));
        elseif(isset($data['save_validate']))
            return redirect()->route('fbls.edit', $fbl->id)
            ->with('success', ($request->email . ' ' . __('app.created_successfully')));
        else
            return redirect()->route('fbls.index')
            ->with('success', ($request->email . ' ' . __('app.created_successfully')));
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Fbl $fbl): View
    {
        Helper::checkPermissions('fbl_servers');
        $page = "fbl_servers";
        $page_title = __('app.edit_fbl_server');
        $breadcrumbs = [
            __('app.fbl_servers') => route('fbls.index'),
            __('app.edit_fbl_server') => '#'
        ];

        return view('fbls.edit',compact('page', 'page_title', 'breadcrumbs', 'fbl'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(CreateFblRequest $request, Fbl $fbl): RedirectResponse
    {
        $data = $this->_fblData($request);
        $fbl->fill($data)->save();

        activity('update')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.fbl') . " ({$fbl->email}) ". __('app.log_update'));

        return redirect()->back()
            ->with('success', ($request->email . ' ' . __('app.updated_successfully')));
    }

    /**
     * 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(Fbl::whereIn('id', $ids)->pluck('email')->toArray()));
          $destroy = Fbl::whereIn('id', $ids)->delete();
        } else {
          $names = Fbl::whereId($id)->value('email');
          $destroy = Fbl::destroy($id);
        }

        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.fbl') . " ({$names}) ". __('app.log_delete')); 

        $data = [
                'success' => true,
                'message' => __('app.deleted_successfully')
            ];
        return response()->json($data, 200); 
    }

    /**
    * Retrun data for store or update
    */
    private function _fblData($request)
    {
        $input = $request->except('_token');
        $input['password'] = !empty($request->password) ? Crypt::encrypt($request->password) : null;
        $input['is_validate'] = false;
        $input['app_id'] = Auth::user()->app_id;
        $input['user_id'] = Auth::user()->id;
        return $input;
    }

    /**
    * Return after validate for IMAP or POP3
    */
    public function validateImap(Request $request)
    {
        $validate_cert = $request->validate_cert == 'Yes' ? true : false;

        // Create a new ClientManager instance
        $clientManager = new ClientManager();

        // Set up the client configuration
        $client = $clientManager->make([
            'host'          => $request->host,
            'port'          => $request->port,
            'encryption'    => $request->encryption,
            'validate_cert' => $validate_cert,
            'username'      => $request->username,
            'password'      => $request->password,
            'protocol'      => $request->method
        ]);

        try {
            // Connect to the IMAP server
            $client->connect();

            // update is_validate value
            $fbl = Fbl::findOrFail($request->id);
            $fbl->update([
                'is_validate' => true,
            ]);

            return '<span class="text-success">'.__('app.successfully_connected').'</span>';
        } catch (\Exception $e) {
            // Handle connection errors
            $msg = $e->getMessage();
            return "<span class='text-danger'>{$msg}</span>";
        }
    }

    /**
     * Retrun index after copy fbl server
    */
    public function copy(int $id): RedirectResponse
    {
        Helper::checkPermissions('bounce_servers');
        $fbl = Fbl::whereId($id)->app()->first();
        $fbl->email = $fbl->email .' - copy ';
        $fbl->is_active = false;
        $copied_fbl = $fbl->replicate();
        $copied_fbl->save();

        activity('copy')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.fbl') . " ({$fbl->email}) ". __('app.log_copy'));

        return redirect()->route('fbls.index')
                ->with('success', ($fbl->email . ' ' . __('app.copied_successfully')));
    }
}
