<?php

namespace App\Http\Controllers\Admin\Module;

use App\Models\ApprovalLog;
use App\Utils\Helper;
use Illuminate\Http\Request;
use App\Http\Controllers\Core\BaseResourceController;

class ApprovalLogController extends BaseResourceController
{
  protected $model = ApprovalLog::class;

  protected function indexQuery($query, Request $request)
  {
    $query->with("user:id,name,role", "payment", "budget", "approvalDepartment", "department");
    $query->when($request->route("budget_id"), fn($q) => $q->where("budget_id", $request->route("budget_id")));
    $query->withSelectAll();

    return $query;
  }

  public function index(Request $request)
  {
    $query = $this->model::query();
    $query = $this->indexQuery($query, $request)
      ->whereNull('parent_id')
      ->with([
        'children' => function ($q) {
          $q->withDetail();
        }
      ]);
    $query = $this->selectParams($query, $request);

    $this->mainQuery = clone $query;
    $instance = $query->orderBy('id', 'desc')->get();
    $this->modelInstance = $instance;

    $budget = \App\Models\Budget::findOrFail($request->route('budget_id'));
    $data = [
      "title" => $this->page["label"],
      "page" => $this->page,
      $this->page["name"] => [
        'data' => $instance->toArray()
      ],
      "budget" => $budget,
      "isAdmin" => $this->isAdmin,
      ...$this->indexData($request),
    ];

    return $this->inertiaRender("Index", $data);
  }

  protected function getPage(Request $request, $id = null): array
  {
    $url = "/admin/budgets/{$request->route('budget_id')}/approval_logs";

    $page = [
      "name" => "approval_logs",
      "inertia" => "Admin/Module/ApprovalLog",
      "label" => "Approval Log",
      "url" => $url,
      "fields" => Helper::getFormFields($this->validation($request)),
    ];

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [
        "user_id" => "required|integer|exists:users,id",
        "budget_id" => "nullable|integer|exists:budgets,id",
        "budget_detail_id" => "nullable|integer|exists:budget_details,id",
        "payment_id" => "nullable|integer|exists:payments,id",
        "module_type" => "required|string",
        "action" => "required|string",
        "level" => "required|string",
        "is_finance" => "required|boolean",
        "note" => "nullable|string",
        "ip_address" => "required|string",
        "user_agent" => "required|string",
      ],
      "default" => [
        "module_type" => \App\Enums\ModuleType::Budget,
        "action" => \App\Enums\ActionStatusType::Submit,
        "level" => \App\Enums\UserDepartmentType::Manager,
        "is_finance" => false,
      ],
    ];
  }

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

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