<?php

namespace App\Http\Controllers;

use Maatwebsite\Excel\Facades\Excel;
use App\Helpers\Helpers;
use App\Exports\OutboxExport;
use App\Models\Device;
use App\Models\Outbox;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// use Illuminate\Support\Collection;

class OutboxController extends Controller
{
  public function list()
  {
    // $user_id = auth()->user()->id;
    // $outbox = Outbox::where('user_id', '=', $user_id)->get();
    // $pendingCount = $outbox->where('status', '=', 'PENDING')->count();
    // $sentCount = $outbox->where('status', '=', 'SENT')->count();
    // $failedCount = Outbox::where('user_id', '=', $user_id)
    //   ->where('status', 'like', 'FAILED%')
    //   ->count();
    // $allCount = $pendingCount + $sentCount + $failedCount;

    // $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'job_id', DB::raw('count(*) as total'))
    //   ->groupBy('job_id')
    //   ->where('user_id', '=', $user_id)
    //   ->orderBy('job_id', 'desc')
    //   ->get();

    // // $jobs = Collection::make($jobs);
    // return view('/outbox-list', compact('jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
    $user_id = auth()->user()->id;
    // $outbox = Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->get();
    $pendingCount = Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', '=', 'PENDING')->count();
    $sentCount = Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', '=', 'SENT')->count();
    $failedCount = Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', 'like', 'FAILED%')->count();
    $allCount = $pendingCount + $sentCount + $failedCount;
    $listAll = false;

    $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'job_id', DB::raw('count(*) as total'))
        ->groupBy('job_id')
        ->where('user_id', '=', $user_id)
        ->where('recurring', '=', NULL)
        ->orderBy('job_id', 'desc')
        ->paginate();
    return view('/outbox-list', compact('listAll', 'jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
  }

  public function listAll()
  {
    $pendingCount = Outbox::where('recurring', '=', NULL)->where('status', '=', 'PENDING')->count();
    $sentCount = Outbox::where('recurring', '=', NULL)->where('status', '=', 'SENT')->count();
    $failedCount = Outbox::where('recurring', '=', NULL)->where('status', 'like', 'FAILED%')->count();
    $allCount = $pendingCount + $sentCount + $failedCount;
    $listAll = true;

    $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'job_id', DB::raw('count(*) as total'))
        ->groupBy('job_id')
        ->where('recurring', '=', NULL)
        ->orderBy('job_id', 'desc')
        ->paginate();
    return view('/outbox-list', compact('listAll', 'jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
  }

  public function listRecurring()
  {
    $user_id = auth()->user()->id;
    // $outbox = Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->get();
    $pendingCount = Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', '=', 'PENDING')->count();
    $sentCount = Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', '=', 'SENT')->count();
    $failedCount = Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', 'like', 'FAILED%')->count();
    $allCount = $pendingCount + $sentCount + $failedCount;

    $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'schedule', 'recurring', 'job_id', DB::raw('count(*) as total'))
        ->groupBy('job_id')
        ->where('user_id', '=', $user_id)
        ->where('recurring', '<>', NULL)
        ->orderBy('job_id', 'desc')
        ->paginate();
    return view('/outbox-listrecurring', compact('jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
  }

  public function show(Request $request)
  {
    $job_id = $request->job_id;
    // $outboxes = Helpers::paginate(Outbox::where('job_id', '=', $job_id)->get(), 100);
    // $outboxes->withPath(url("/outbox-show?job_id={$job_id}"));
    $outboxes = Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->get();
    $pendingCount = Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', '=', 'PENDING')->count();
    $sentCount = Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', '=', 'SENT')->count();
    $failedCount = Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', 'like', 'FAILED%')->count();
    return view('/outbox-show', compact('job_id', 'outboxes', 'pendingCount', 'sentCount', 'failedCount'));
  }

  public function showRecurring(Request $request)
  {
    $job_id = $request->job_id;
    // $outboxes = Helpers::paginate(Outbox::where('job_id', '=', $job_id)->get(), 100);
    // $outboxes->withPath(url("/outbox-show?job_id={$job_id}"));
    $outboxes = Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->get();
    $pendingCount = Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', '=', 'PENDING')->count();
    $sentCount = Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', '=', 'SENT')->count();
    $failedCount = Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', 'like', 'FAILED%')->count();
    return view('/outbox-show', compact('job_id', 'outboxes', 'pendingCount', 'sentCount', 'failedCount'));
  }

  public function filterStatus(Request $request)
  {
    if (!empty($request->job_id)) {
      $job_id = $request->job_id;
      // $outboxes = Helpers::paginate(Outbox::where('job_id', '=', $job_id)->where('status', 'like', "$request->status%")->get(), 100);
      // $outboxes->withPath(url("/outbox-show?job_id={$job_id}"));
      $outboxes = Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', 'like', "$request->status%")->get();
      $pendingCount = $request->pendingCount;//Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', '=', 'PENDING')->count();
      $sentCount = $request->sentCount;//Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', '=', 'SENT')->count();
      $failedCount = $request->failedCount;//Outbox::where('job_id', '=', $job_id)->where('recurring', '=', NULL)->where('status', 'like', 'FAILED%')->count();
      return view('/outbox-show', compact('job_id', 'outboxes', 'pendingCount', 'sentCount', 'failedCount'));
    } else {
      // $user_id = auth()->user()->id;
      // $outbox = Outbox::where('user_id', '=', $user_id)
      //   ->where('status', 'like', "$request->status%")
      //   ->get();
      // $pendingCount = $request->pendingCount;
      // $sentCount = $request->sentCount;
      // $failedCount = $request->failedCount;
      // $allCount = $pendingCount + $sentCount + $failedCount;

      // $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'job_id', DB::raw('count(*) as total'))
      //   ->groupBy('job_id')
      //   ->where('user_id', '=', $user_id)
      //   ->where('status', 'like', "$request->status%")
      //   ->orderBy('job_id', 'desc')
      //   ->get();
      // return view('/outbox-list', compact('jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
      $user_id = auth()->user()->id;
      // $outbox = Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', 'like', "$request->status%")->get();
      $pendingCount = $request->pendingCount;//Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', '=', 'PENDING')->count();
      $sentCount = $request->sentCount;//Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', '=', 'SENT')->count();
      $failedCount = $request->failedCount;//Outbox::where('user_id', '=', $user_id)->where('recurring', '=', NULL)->where('status', 'like', 'FAILED%')->count();
      $allCount = $pendingCount + $sentCount + $failedCount;
      $listAll = false;

      $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'job_id', DB::raw('count(*) as total'))
      ->groupBy('job_id')
      ->where('user_id', '=', $user_id)
      ->where('recurring', '=', NULL)
      ->where('status', 'like', "$request->status%")
      ->orderBy('job_id', 'desc')
      ->paginate();
      return view('/outbox-list', compact('listAll', 'jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
    }
  }

  public function filterStatusRecurring(Request $request)
  {
    if (!empty($request->job_id)) {
      $job_id = $request->job_id;
      // $outboxes = Helpers::paginate(Outbox::where('job_id', '=', $job_id)->where('status', 'like', "$request->status%")->get(), 100);
      // $outboxes->withPath(url("/outbox-show?job_id={$job_id}"));
      $outboxes = Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', 'like', "$request->status%")->get();
      $pendingCount = $request->pendingCount;//Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', '=', 'PENDING')->count();
      $sentCount = $request->sentCount;//Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', '=', 'SENT')->count();
      $failedCount = $request->failedCount;//Outbox::where('job_id', '=', $job_id)->where('recurring', '<>', NULL)->where('status', 'like', 'FAILED%')->count();
      return view('/outbox-show', compact('job_id', 'outboxes', 'pendingCount', 'sentCount', 'failedCount'));
    } else {
      $user_id = auth()->user()->id;
      // $outbox = Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', 'like', "$request->status%")->get();
      $pendingCount = $request->pendingCount;//Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', '=', 'PENDING')->count();
      $sentCount = $request->sentCount;//Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', '=', 'SENT')->count();
      $failedCount = $request->failedCount;//Outbox::where('user_id', '=', $user_id)->where('recurring', '<>', NULL)->where('status', 'like', 'FAILED%')->count();
      $allCount = $pendingCount + $sentCount + $failedCount;

      $jobs = Outbox::select('sender', 'receiver', 'rec_name', 'msgtext', 'schedule', 'recurring', 'job_id', DB::raw('count(*) as total'))
      ->groupBy('job_id')
      ->where('user_id', '=', $user_id)
      ->where('recurring', '<>', NULL)
      ->where('status', 'like', "$request->status%")
      ->orderBy('job_id', 'desc')
      ->paginate(10);
      return view('/outbox-listrecurring', compact('jobs', 'pendingCount', 'sentCount', 'failedCount', 'allCount'));
    }
  }

  public function pause(Request $request)
  {
    Outbox::where('job_id', '=', $request->job_id)
      ->where(function ($query) {
        $query->where('status', '=', 'PENDING')->orWhere('status', '=', 'SENDING');
      })
      ->update(['status' => 'PAUSED']);
    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully update Outbox Pause')]);
  }

  public function resume(Request $request)
  {
    Device::where('user_id', $request->user_id)->update(['busy' => false]);
    Outbox::where('job_id', '=', $request->job_id)
      ->where(function ($query) {
        $query->where('status', '=', 'PAUSED')->orWhere('status', '=', 'SENDING');
      })
      ->update(['status' => 'PENDING']);
    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully update Outbox Resume')]);
  }

  public function resendFailed(Request $request)
  {
    if (!empty($request->user_id)) {
      if (
        Outbox::where('user_id', '=', $request->user_id)
          ->where('status', 'like', 'FAILED%')
          ->count() == 0
      ) {
        return redirect()
          ->back()
          ->with(['danger_alert' => __('You do not have FAILED outbox to resend')]);
      } else {
        // Update FAILED messages to SENDING status for immediate processing
        Outbox::where('user_id', '=', $request->user_id)
          ->where('status', 'like', 'FAILED%')
          ->whereNull('schedule')
          ->update(['status' => 'SENDING']);
        
        // Update scheduled FAILED messages to PENDING
        Outbox::where('user_id', '=', $request->user_id)
          ->where('status', 'like', 'FAILED%')
          ->whereNotNull('schedule')
          ->update(['status' => 'PENDING']);
        
        return redirect()
          ->back()
          ->with(['success_alert' => __('Successfully queued FAILED messages for resending')]);
      }
    } elseif (!empty($request->job_id)) {
      if (
        Outbox::where('job_id', '=', $request->job_id)
          ->where('status', 'like', 'FAILED%')
          ->count() == 0
      ) {
        return redirect()
          ->back()
          ->with(['danger_alert' => __('You do not have FAILED outbox to resend')]);
      } else {
        // Update FAILED messages to SENDING status for immediate processing
        Outbox::where('job_id', '=', $request->job_id)
          ->where('status', 'like', 'FAILED%')
          ->whereNull('schedule')
          ->update(['status' => 'SENDING']);
        
        // Update scheduled FAILED messages to PENDING
        Outbox::where('job_id', '=', $request->job_id)
          ->where('status', 'like', 'FAILED%')
          ->whereNotNull('schedule')
          ->update(['status' => 'PENDING']);
        
        return redirect()
          ->back()
          ->with(['success_alert' => __('Successfully queued FAILED messages for resending')]);
      }
    }
  }

  public function export(Request $request)
  {
    return Excel::download(new OutboxExport($request->job_id, $request->status), 'outboxes.xlsx');
  }

  public function destroyJob(Request $request)
  {
    $user_id = auth()->user()->id;
    $outboxes = Outbox::where('job_id', '=', $request->input('job_id'))->get();
    foreach ($outboxes as $outbox) {
      if (!empty($outbox->mediaurl)) {
        $arrMediaurl = explode('/', $outbox->mediaurl);
        $mediafile = end($arrMediaurl);
        if (file_exists(public_path("users/{$user_id}/outbox/{$mediafile}"))) {
          unlink(public_path("users/{$user_id}/outbox/{$mediafile}"));
        }
      }
      $outbox->delete();
    }
    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully delete Job ID') . ': ' . $request->input('job_id')]);
  }

  public function destroyObx(Request $request)
  {
    $user_id = auth()->user()->id;
    $outbox = Outbox::where('id', '=', $request->input('outbox_id'))->first();
    $outbox->delete();
    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully delete Outbox ID') . ': ' . $request->input('outbox_id')]);
  }

  public function destroyAll(Request $request)
  {
    $outbox = Outbox::where('user_id', '=', $request->user_id)->first();
    if (auth()->user()->id != $outbox->user_id && auth()->user()->role !== 'admin') {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You are not allowed to delete Outbox')]);
    }
    Outbox::where('user_id', '=', $request->user_id)->delete();
    return redirect()
      ->back()
      ->with(['success_alert' => __('Successfully delete Outbox')]);
  }

  public function destroyStatus(Request $request)
  {
    $outbox = Outbox::where('user_id', '=', $request->user_id)->first();
    if (auth()->user()->id != $outbox->user_id && auth()->user()->role !== 'admin') {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You are not allowed to delete Outbox')]);
    }
    if (
      Outbox::where('user_id', '=', $request->user_id)
        ->where('status', 'like', "$request->status%")
        ->count() == 0
    ) {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You do not have') . ' ' . $request->status . ' ' . __('outbox to delete')]);
    } else {
      Outbox::where('user_id', '=', $request->user_id)
        ->where('status', 'like', "$request->status%")
        ->delete();
      return redirect()
        ->back()
        ->with(['success_alert' => __('Successfully delete Outbox')]);
    }
  }

  public function destroyFilter(Request $request)
  {
    $outbox = Outbox::where('user_id', '=', $request->user_id)->first();
    if (auth()->user()->id != $outbox->user_id && auth()->user()->role !== 'admin') {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You are not allowed to delete Outbox')]);
    }
    if (
      Outbox::where('user_id', '=', $request->user_id)
        ->where('job_id', '=', $request->job_id)
        ->where('status', 'like', "$request->status%")
        ->count() == 0
    ) {
      return redirect()
        ->back()
        ->with(['danger_alert' => __('You do not have') . ' ' . $request->status . ' ' . __('outbox to delete')]);
    } else {
      Outbox::where('user_id', '=', $request->user_id)
        ->where('job_id', '=', $request->job_id)
        ->where('status', 'like', "$request->status%")
        ->delete();
      return redirect()
        ->back()
        ->with(['success_alert' => __('Successfully delete Outbox')]);
    }
  }
}
