<?php

namespace App\Http\Controllers;

use App\Utils\Helper;
use App\Models\Payment;
use App\Enums\ModuleType;
use App\Models\Notification;
use Illuminate\Http\Request;
use App\Enums\NotificationType;
use App\Http\Controllers\Core\BaseResourceController;

class NotificationController extends BaseResourceController
{
  protected $model = Notification::class;

  protected function indexQuery($query, Request $request)
  {
    $query->where('user_id', auth()->id());
    $query->when($request->filled("type"), fn($q) => $q->where("type", $request->type));

    return $query;
  }

  public function show($id, Request $request)
  {
    $notification = Notification::where('user_id', auth()->id())->find($id);

    if (!$notification) {
      return redirect()->back()->with('error', 'Notifikasi tidak ditemukan');
    }

    if (!$notification->is_read) {
      $notification->update(['is_read' => true, 'read_at' => now()]);
    }

    if ($notification->module_type == ModuleType::Payment) {
      $payment = Payment::find($notification->payment_id);
      $q = urlencode(urlencode($payment->code));
      return redirect("/admin/budgets/$payment->budget_id/payment_details?q=$q&searchBy=code");
    }

    if ($notification->link && $notification->link !== '#') {
      return redirect($notification->link);
    }

    return redirect()->back();
  }

  public function readAll(Request $request)
  {
    Notification::where('user_id', auth()->id())
      ->where('is_read', false)
      ->update(['is_read' => true, 'read_at' => now()]);

    return redirect()->back()->with('success', 'Semua notifikasi telah ditandai sudah dibaca');
  }

  protected function getPage(Request $request, $id = null): array
  {
    $page = [
      "name" => "notifications",
      "inertia" => "Admin/Notification",
      "label" => "Notifikasi",
      "url" => "/admin/notifications",
      "fields" => Helper::getFormFields($this->validation($request)),
    ];

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [],
      "default" => [],
    ];
  }

  protected function getFormData(Request $request, $model = null): array
  {
    $formData = [];

    return [
      ...parent::getFormData($request, $model),
      ...$formData,
    ];
  }
}
