<?php

namespace App\Http\Controllers\Admin;

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

class VendorController extends BaseResourceController
{
  protected $model = Vendor::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" => "vendors",
      "inertia" => "Admin/Vendor",
      "label" => "Vendor",
      "url" => "/admin/vendors",
      "fields" => Helper::getFormFields($this->validation($request)),
    ];

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [
        "name" => "required|string",
        "company_name" => "required|string",
        "phone" => "required|string",
        "address" => "required|string",
        "city" => "required|string",
        "status" => "required|string",
      ],
      "default" => [
        "status" => \App\Enums\OriginStatusType::Active,
      ],
    ];
  }

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

    return [
      "status" => $status,

      ...parent::getFormData($request, $model),
      ...$formData,
    ];
  }
  protected function afterSave($model, Request $request)
  {
    $department = Department::active($request)->first();
    $model->userVendors()->updateOrCreate(
      ['user_id' => auth()->id()],
      ['department_id' => $department?->id]
    );
  }
}
