<?php

namespace App\Http\Controllers\Admin\Module;

use App\Utils\Helper;
use App\Enums\UserType;
use App\Models\Category;
use App\Enums\ModuleType;
use App\Models\ApprovalLog;
use App\Models\BudgetDetail;
use Illuminate\Http\Request;
use App\Enums\BudgetStatusType;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Core\BaseResourceController;

class BudgetDetailController extends BaseResourceController
{
  protected $model = BudgetDetail::class;

  protected function indexQuery($query, Request $request)
  {
    $relation = ["quantityUnits.unitType"];
    $query->with(["reviewer:id,name", "budgetCategory.category:id,name", "transaction" => [...$relation, "attachments"], ...$relation,]);

    $query->when($request->filled("status"), fn($q) => $q->where("status", $request->status));
    $query->when($request->filled("category_id"), fn($q) => $q->whereRelation("budgetCategory.category", "id", $request->category_id));
    $query->orderByRaw("CASE WHEN status = '" . BudgetStatusType::Revision . "' THEN 0 ELSE 1 END");

    return $query;
  }

  protected function indexData(Request $request, $isFormData = true): array
  {
    $budgetId = $request->route('budget_id');
    $categories = Category::selectOptions()
      ->where('status', \App\Enums\OriginStatusType::Active)
      ->whereRelation('budgetCategories', 'budget_id', $budgetId)
      ->get();

    $budgetCategorySumQuery = clone $this->mainQuery;
    $budgetCategorySum = $budgetCategorySumQuery->select([
      DB::raw("
            COALESCE(SUM(price_total), 0)  AS price_amount_total
        "),
    ])
      ->first();

    $transactionSumQuery = clone $this->mainQuery;
    $transactionPriceTotal = $transactionSumQuery
      ->join('transactions', 'budget_details.id', '=', 'transactions.budget_detail_id')
      ->where('transactions.status', BudgetStatusType::Approved)
      ->sum('transactions.price_total');

    $budgetCategorySum = [
      "price_amount_total" => intval($budgetCategorySum->price_amount_total ?? 0),
      "transaction_price_total" => intval($transactionPriceTotal ?? 0),
    ];

    return [
      'categories' => $categories,
      'budgetCategorySum' => $budgetCategorySum,
      "status" => BudgetStatusType::getValues(),
    ];
  }

  protected function getPage(Request $request, $id = null): array
  {
    $page = [
      "name" => "budget_details",
      "inertia" => "Admin/Module/BudgetDetail",
      "label" => "Detail Anggaran",
      "url" => "/admin/budgets/{$request->route('budget_id')}/budget_details",
      "fields" => Helper::getFormFields($this->validation($request)),
    ];

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [
        "name" => "required|string",
        "description" => "nullable|string",
        "price" => "nullable|integer",
        "price_total" => "required|integer",
        "status" => "required|string",
        "status_message" => "nullable|string",

        "quantity_unit" => "array",
        "quantity_unit.*.quantity" => "required|integer",
        "quantity_unit.*.unit_type_id" => "required|exists:unit_types,id",
      ],
      "default" => [
        "status" => BudgetStatusType::Draft,
      ],
    ];
  }

  protected function afterSave($model, Request $request)
  {
    if ($request->has('quantity_unit') && is_array($request->quantity_unit)) {
      $model->quantityUnits()->delete();

      foreach ($request->quantity_unit as $qu) {
        $model->quantityUnits()->create([
          'quantity' => $qu['quantity'],
          'unit_type_id' => $qu['unit_type_id'],
        ]);
      }
    }
  }


}
