<?php

namespace App\Http\Controllers;

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

class BlacklistController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function systemBounced(): View
    {
        Helper::checkPermissions('system_bounced');
        $page = "miscellaneous_system_bounced";
        $page_title = __('app.system_bounced');
        $breadcrumbs = [
            __('app.system_bounced') => '#',
            __('app.manage') => route('system.bounced')
        ];  
        return view('blacklists.system_bounced',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
    * Retrun JSON datatable data
    */
    public function getSystemBounced(Request $request)
    {
        $result = GlobalBounce::whereNotNull('email');

        $columns = ['id', 'email', 'type', 'code', 'detail', 'created_at'];
        $data = Helper::dataFilters($request, $result, $columns);

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

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

        foreach($bounced as $bounce) {
          $checkbox = "<input class=\"form-check-input\" type=\"checkbox\" value=\"{$bounce->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 text-danger" href="javascript:;" onclick="destroy(\''.$bounce->id.'\', \''.route('system.bounced.destroy', [$bounce->id]).'\')"><i class="bi bi-trash"></i> '.__('app.delete').'</a></li>';
          $actions .= '</ul>
            </div>';

          $detail = json_decode($bounce->detail)->short_detail ?? '---';
          $detail = "<pre>".wordwrap($detail, 50, "\n")."</pre>";
          $data['data'][] = [
            "DT_RowId" => "row_{$bounce->id}",
            $checkbox,
            $bounce->email,
            $bounce->type,
            $bounce->code,
            $detail,
            Helper::datetimeDisplay($bounce->created_at),
            $actions
          ];
        }
        echo json_encode($data);
    }

    /**
    * Delete global bounced
    */
    public function destroySystemBounced($id, Request $request)
    {
        if(!empty($request->action)) {
          $ids = array_values($request->ids);

          // get emails
          $emails = json_encode(array_values(GlobalBounce::whereIn('id', $ids)->pluck('email')->toArray()));

          $emails_array = json_decode($emails);

          foreach($emails_array as $email){
            \App\Models\Contact::whereEmail($email)->update([
              'is_bounced' => false
            ]);
          }

          $destroy = GlobalBounce::whereIn('id', $ids)->delete();
        } else {
          // get email
          $emails = GlobalBounce::whereId($id)->value('email');

          // update contact set is_bounced to false again
          \App\Models\Contact::whereEmail($emails)->update([
            'is_bounced' => false
          ]);

          $destroy = GlobalBounce::destroy($id);
        }
        activity('delete')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.global_bounced') . " ({$emails}) ". __('app.log_delete'));

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

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

    /**
    * Import System Bounced
    */
    public function importSystemBounced(Request $request)
    {
        if($request->isMethod('post')) {
          if(!empty($request->fieldMapping)) {
            $path_import_blacklist = str_replace('[user-id]', Auth::user()->id, config('custom.path_import_blacklist'));
            $file = $path_import_blacklist.'bounces-header.csv';

            $file_header = Helper::getCsvFileHeader($file);

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

            $string = '';
            $string .= "<div class='row mt-2'>
                  <label class='col-md-2 from-label'>Email</label>
                  <div class='col-md-10'>{$drop_down}</div>
                </div>";
            $string .= "<div class='row mt-2'>
                  <label class='col-md-2 from-label'>Type</label>
                  <div class='col-md-10'>
                  <select name='bounce_fields[]' class='form-select'>
                    <option value='Soft'>".__('app.soft')."</option>
                    <option value='Hard'>".__('app.hard')."</option>
                  </select>
                  </div>
                </div>";
            $string .= "<div class='row mt-2'>
                  <label class='col-md-2 from-label'>Code</label>
                  <div class='col-md-10'>{$drop_down}</div>
                </div>";
            $string .= "<div class='row mt-2'>
                  <label class='col-md-2 from-label'>Detail</label>
                  <div class='col-md-10'>{$drop_down}</div>
                </div>";
            return $string;
          } elseif($request->do_import) {
            $attributes = $request->except('_token', 'file', 'do_import');
            try{
              $path_import_blacklist = str_replace('[user-id]', Auth::user()->id, config('custom.path_import_blacklist'));
              $file_name = md5(uniqid()).'.csv';
              $file_path = $path_import_blacklist.$file_name;

              $file = $request->file('file');
              $file->move($path_import_blacklist, $file_name); // save original file to import

              $reader = \League\Csv\Reader::createFromPath($file_path, 'r');
              $records = $reader->getRecords();
              foreach ($records as $offset => $record) {
                $email = !empty($record[$request->bounce_fields[0]]) ? $record[$request->bounce_fields[0]] : null;
                if (filter_var($record[$request->bounce_fields[0]], FILTER_VALIDATE_EMAIL) &&
                !GlobalBounce::whereEmail($email)->exists() ) {
                  $type = !empty($request->bounce_fields[1]) ? $request->bounce_fields[1] : 'Hard';
                  $code = !empty($record[$request->bounce_fields[2]]) ? $record[$request->bounce_fields[2]] : null;                  
                  $detail = !empty($record[$request->bounce_fields[3]]) ? 
                  json_encode(['short_detail' => $record[$request->bounce_fields[3]], 'full_detail' => $record[$request->bounce_fields[3]] ]) : null;


                  $bounce_data = [
                    'stat_id' => 0,
                    'schedule_campaign_stat_log_id' => 0,
                    'section' => 'Campaign',
                    'email'  => $email,
                    'code'   => $code,
                    'type'   => $type,
                    'detail' => $detail,
                    'created_at' => \Carbon\Carbon::now(),
                  ];
                  GlobalBounce::create($bounce_data);
                }
              }

              // update contact set is_bounced to true
              \App\Models\Contact::whereEmail($email)->update([
                'is_bounced' => true
              ]);

              unlink($path_import_blacklist.'bounces-header.csv'); // delete header file
              unlink($path_import_blacklist.$file_name); // delete header file
            } catch(\Exception $e) {
              //echo $e->getMessage();
            }
          } else {
            $request->validate([
              'file' => 'required|mimes:csv,txt|max:'.Helper::getMaxFileSizeMB()
            ]);
            $file = $request->file('file');
            //echo $file->originalName();
            $header = Helper::getCsvFileHeader($file);
            $path_import_blacklist = str_replace('[user-id]', Auth::user()->id, config('custom.path_import_blacklist'));
            Helper::dirCreateOrExist($path_import_blacklist); // create dir if not exist

            $file = $path_import_blacklist.'bounces-header.csv';

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

    /**
     * Export Bounced
    */
    public function exportBounced()
    {
      \App\Jobs\BouncedExport::dispatch(Auth::user()->app_id, Auth::user()->id)
        ->delay(now()->addSeconds(10));

      activity('export')->withProperties(['app_id' => Auth::user()->app_id])->log(__('app.global_bounced') .' ' . __('app.log_export')); // log
    }
}
