<?php

namespace App\Http\Controllers\Admin;

use App\Models\Bank;
use App\Utils\Helper;
use App\Enums\UserType;
use App\Enums\ActionType;
use App\Models\Department;
use Illuminate\Http\Request;
use App\Enums\OriginStatusType;
use App\Enums\PublishStatusType;
use App\Http\Controllers\Core\BaseResourceController;

class BankController extends BaseResourceController
{
  protected $model = Bank::class;

  protected function indexQuery($query, Request $request)
  {
    $query->when($request->filled("status"), fn($q) => $q->where("status", $request->status));

    return $query;
  }

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

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [
        'code' => 'required|string|max:10|unique:' . Bank::class . ',code,' . $id,
        'name' => 'required',
        'limit_transfer_amount' => 'nullable',
        'bi_fast' => 'nullable',
        'status' => 'nullable',
      ],
      'default' => [
        'status' => OriginStatusType::Active,
        'bi_fast' => 0
      ]
    ];
  }

  protected function getFormData(Request $request, $model = null): array
  {
    $formData = [];
    $status = \App\Enums\OriginStatusType::getValues();

    return [
      "status" => $status,

      ...parent::getFormData($request, $model),
      ...$formData,
    ];
  }
  protected function getAuthorize(Request $request, $data = null, $action = ActionType::Read)
  {
    $user = auth()->user();
    $department = Department::active($request)->first();
    if ($department->is_finance && in_array($user->role, [UserType::Director, UserType::Manager]))
      return true;

    $actionLabels = Helper::getEnumTranslation(ActionType::class, "id");
    return Helper::redirectBack("error", "Anda tidak diperbolehkan {$actionLabels[$action]} {$this->page["label"]} ini");
  }
}
