<?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 = "health_email_bounced";
        $page_title = __('app.system_bounced');
        $breadcrumbs = [
            __('app.email_health') => '#',
            __('app.system_bounced') => route('system.bounced'),
            __('app.manage') => '#'
        ];  
        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
    }

    /**
     * Display blacklisted IPs
    */
    public function blacklistedIPs()
    {
      Helper::checkPermissions('blacklisted_ips');
      $page = "health_email_ips";
      $page_title = __('app.email_health') . ' => ' .__('app.ips');
      $breadcrumbs = [
          __('app.email_health') => '#',
          __('app.ips') => route('blacklisted.ips'),
          __('app.manage') => '#'
      ];
      return view('blacklists.blacklisted_ips',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
     * Retrurn blacklisted ips
    */
    public function getblacklistedIPs(Request $request)
    {
      $result = \DB::table('blacklisteds')
        ->where('ip_domain', 'ip')
        ->where('app_id', Auth::user()->app_id);

      $columns = ['name', 'counts'];
      $data = Helper::dataFilters($request, $result, $columns);

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

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

      foreach($blacklisteds as $blacklisted) {
        $detail = '<a class="link-info" href="javascript:;" onclick="viewModal(\'modal\', \''.route('blacklisted.detail', ['id' => $blacklisted->id]).'\')">'.__('app.detail').'</a>';
        $data['data'][] = [
          $blacklisted->name,
          $blacklisted->counts,
          $detail
        ];
      }
      echo json_encode($data);
    }

    /**
     * Display blacklisted Domains
    */
    public function blacklistedDomains()
    {
      Helper::checkPermissions('blacklisted_domains');
      $page = "health_email_bdomains";
      $page_title = __('app.email_health') . ' => ' .__('app.domains');
      $breadcrumbs = [
          __('app.email_health') => '#',
          __('app.domains') => route('blacklisted.domains'),
          __('app.manage') => '#'
      ];
      return view('blacklists.blacklisted_domains',compact('page', 'page_title', 'breadcrumbs'));
    }

    /**
     * Retrurn blacklisted ips
    */
    public function getblacklistedDomains(Request $request)
    {
      $result = \DB::table('blacklisteds')
        ->where('ip_domain', 'domain')
        ->where('app_id', Auth::user()->app_id);

      $columns = ['name', 'counts'];
      $data = Helper::dataFilters($request, $result, $columns);

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

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

      foreach($blacklisteds as $blacklisted) {
        $detail = '<a class="link-info" href="javascript:;" onclick="viewModal(\'modal\', \''.route('blacklisted.detail', ['id' => $blacklisted->id]).'\')">'.__('app.detail').'</a>';
        $data['data'][] = [
          $blacklisted->name,
          $blacklisted->counts,
          $detail
        ];
      }
      echo json_encode($data);
    }

    public function blacklistedDetail($id)
    {
      $blacklisted = \DB::table('blacklisteds')->whereId($id)->whereAppId(Auth::user()->app_id)->first();
      return view('blacklists.blacklisted_detail')->with('blacklisted', $blacklisted);
    }
}
