<?php

namespace App\Http\Controllers;

use Illuminate\View\View;
use App\Models\Suppression;
use App\Models\Import;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use App\Http\Helper\Helper;
use Auth;

use Illuminate\Http\Request;

class SuppressionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        Helper::checkPermissions('suppression');
        $page = 'lists_suppression';
        $page_title = __('app.suppressions');
        $breadcrumbs = [
            __('app.suppressions') => route('suppressions.index'),
            __('app.manage') => '#'
        ];
        $groups = \App\Models\Group::groups(config('custom.group_suppression'));
        return view('suppressions.index',compact('page', 'page_title', 'breadcrumbs', 'groups'));
    }

    /**
       * Retrun JSON datatable data
    */
    public function getSuppressions(Request $request): Void
    {
        $result = Suppression::join('groups', 'groups.id', '=', 'suppressions.group_id')
        ->select('suppressions.id', 'suppressions.email as email', 'suppressions.created_at', 'groups.id as group_id', 'groups.name as group_name')
        ->app();

        $columns = ['suppressions.id', 'suppressions.id', 'suppressions.email', 'groups.name', 'suppressions.created_at'];

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

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

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

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

          $group_name = "<span id='{$suppression->group_id}'>$suppression->group_name<span>";

          $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 text-danger" href="javascript:;" onclick="destroy(\''.$suppression->id.'\', \''.route('suppressions.destroy', $suppression->id).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';
          $actions .= '</ul>';

          $data['data'][] = [
            "DT_RowId" => "row_{$suppression->id}",
            $checkbox,
            $suppression->id,
            $suppression->email,
            $group_name,
            Helper::datetimeDisplay($suppression->created_at),
            $actions
            ];
        }
        echo json_encode($data);
    }

    /**
     * Retrun create view
     */
    public function create(): View
    {
        Helper::checkPermissions('suppression');
        $groups = \App\Models\Group::groups(config('custom.group_suppression'));
        return view('suppressions.create', compact('groups'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $file = $request->file('file');
        $input = $request->except('_token');
        $input['user_id'] = Auth::user()->id;
        $input['app_id'] = Auth::user()->app_id;
        if($request->resource == 'emails') {
          $request->validate([
            'group_id' => 'required',
            'emails' => 'required'
          ]);
          $emails = Helper::splitLineBreakWithComma($input['emails']);
          foreach($emails as $email) {
            $input['email'] = trim($email);

            // Added an exception to handle duplicates for group_id and email.
            try {
                if(!Suppression::whereEmail($input['email'])->whereGroupId($input['group_id'])->exists())
                    Suppression::create($input);
            } catch (\Exception $e) { }
          }
        }

        // save log
        activity('create')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.suppression') .' '. __('app.log_create')); // log
    
        return redirect()->route('suppressions.index')
            ->with('success',__('app.suppression') .' '. __('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);
            $emails = json_encode(array_values(Suppression::whereIn('id', $ids)->pluck('email')->toArray()));
            $destroy = Suppression::whereIn('id', $ids)->delete();
        } else {
            $emails = Suppression::whereId($id)->value('email');
            $destroy = Suppression::destroy($id);
        }
        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.suppression') . " ({$emails}) ". __('app.log_delete'));

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

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

    /**
    * Import Suppression
    */
    public function suppressionImport(Request $request)
    {
        if($request->isMethod('post')) {
          if(!empty($request->fieldMapping)) {
            $path_import_suppression = str_replace('[user-id]', Auth::user()->id, config('custom.path_import_suppression'));
            $file = $path_import_suppression.'suppression-header.csv';
            $file_header = Helper::getCsvFileHeader($file);

            $drop_down = '<select name="mapping_fields[]" class="form-select">';
            $drop_down .= "<option value=''>". __('app.none') ."</option>";
            foreach($file_header as $key  => $header) {
              $drop_down .= "<option value='{$key}'>{$header}</option>";
            }
            $drop_down .= '</select>';

            $string = "<div class='row mb-3'>
                  <label class='col-md-2 col-form-label'>Email</label>
                  <div class='col-md-10'>{$drop_down}</div>
                </div>";
            return $string;
          } elseif($request->do_import) {
            $path_import_suppression = str_replace('[user-id]', Auth::user()->id, config('custom.path_import_suppression'));
            $file_name = md5(uniqid()).'.csv';
            $file = $request->file('file');
            $attributes = $request->except('_token', 'file', 'do_import');

            $import = \App\Models\Import::create([
              'type' => 'suppression',
              'file' => $path_import_suppression.$file_name,
              'attributes' => json_encode($attributes),
              'total' => Helper::getCsvCount($file),
              'user_id' => Auth::user()->id,
              'app_id' => Auth::user()->app_id
            ]);

            try{
              $file->move($path_import_suppression, $file_name); // save original file to import
              
              \App\Jobs\SuppressionImport::dispatch($import->id, Auth::user()->id)
                ->delay(now()->addSeconds(10));
              \Artisan::call('queue:work', ['--once' => true]); // execute queue

              // save activity log
              activity('import')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.suppression') .' '. __('app.log_import'));

              unlink($path_import_suppression.'suppression-header.csv'); // delete header file
              return "You can leave the page; the process is running in the background, and you will be notified once it's complete";
            } catch(\Exception $e) {
              // nothing
            }            
          } else {
            $request->validate([
              'file' => 'required|mimes:csv,txt|max:'.Helper::getMaxFileSizeMB()
            ]);
            $file = $request->file('file');
            $header = Helper::getCsvFileHeader($file);
            $path_import_suppression = str_replace('[user-id]', Auth::user()->id, config('custom.path_import_suppression'));
            Helper::dirCreateOrExist($path_import_suppression); // create dir if not exist

            $file = $path_import_suppression.'suppression-header.csv';

            $writer = \League\Csv\Writer::createFromPath($file, 'w'); // create a .csv file to write data
            $writer->insertOne($header); // write file header
          }
        }
    }
}
