<?php

namespace App\Http\Controllers\Admin;

use App\Models\Category;
use App\Utils\Helper;
use Illuminate\Http\Request;
use App\Enums\PublishStatusType;
use App\Http\Controllers\Core\BaseResourceController;
use App\Models\Department;

class CategoryController extends BaseResourceController
{
  protected $model = Category::class;

  protected function indexQuery($query, Request $request)
  {
    $query->when($request->filled("period_type"), fn($q) => $q->where("period_type", $request->period_type));
    $query->when($request->filled("status"), fn($q) => $q->where("status", $request->status));
    $query->orderByRaw("COALESCE(parent_id, id) ASC")->orderBy("level", "ASC");

    return $query;
  }

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

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [
        "parent_id" => "nullable|exists:categories,id",
        "name" => "required|string",
        "period_type" => "required|string",
        "status" => "required|string",
      ],
      "default" => [
        "period_type" => \App\Enums\PeriodType::Other,
        "status" => \App\Enums\OriginStatusType::Active,
      ],
    ];
  }

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

    $parentCategories = null;
    if ($this->isFormPage) {
      $parentCategories = Category::selectOptions()
        ->where('status', \App\Enums\OriginStatusType::Active)
        ->when($model, fn($q) => $q->whereNot("id", $model->id))
        ->orderByRaw("COALESCE(parent_id, id) ASC")
        ->orderBy("level", "ASC")
        ->orderBy("name", "ASC")
        ->get();
    }

    return [
      "status" => $status,
      "period_types" => $periodTypes,
      "parent_categories" => $parentCategories,

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

  protected function beforeSave(array $validatedData, Request $request): array
  {
    $validatedData['level'] = 1;
    if ($validatedData['parent_id']) {
      $parentCategory = Category::find($validatedData['parent_id']);
      $validatedData['level'] = intval($parentCategory->level) + 1;
    }

    return $validatedData;
  }
  protected function afterSave($model, Request $request)
  {
    $department = Department::active($request)->first();
    $model->userCategories()->updateOrCreate(
      ['user_id' => auth()->id()],
      ['department_id' => $department?->id]
    );
  }
}
