<?php

namespace App\Http\Controllers\Admin\Module;

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

class PaymentDetailController extends BaseResourceController
{
  protected $model = Payment::class;

  protected function indexQuery($query, Request $request)
  {
    $budgetId = $request->route('budget_id');
    $query->where('budget_id', $budgetId);
    $query->with(["budget", "attachments", "reviewer:id,name", "transaction" => ["quantityUnits.unitType", "attachments", "vendor"]]);
    $query->when($request->filled("type"), fn($q) => $q->where("type", $request->input('type')));
    $query->when($request->filled("method"), fn($q) => $q->where("method", $request->input('method')));
    $query->when($request->filled("status"), fn($q) => $q->where("status", $request->input('status')));

    // Optional: Add sorting or other filters if needed, keeping it simple for now
    $query->latest();

    return $query;
  }

  protected function indexData(Request $request, $isFormData = true): array
  {
    $paymentDetailSumQuery = clone $this->mainQuery;
    $paymentDetailSum = $paymentDetailSumQuery->select([
      \Illuminate\Support\Facades\DB::raw("
            COALESCE(SUM(amount), 0)  AS amount_total
        "),
    ])
      ->first();

    $status = \App\Enums\PaymentStatusType::getValues();
    $type = \App\Enums\PaymentType::getValues();
    $method = \App\Enums\PaymentMethodType::getValues();

    return [
      "status" => $status,
      "type" => $type,
      "method" => $method,
      "paymentDetailSum" => [
        "amount_total" => intval($paymentDetailSum->amount_total ?? 0),
      ],
    ];
  }

  protected function getPage(Request $request, $id = null): array
  {
    $budgetId = $request->route('budget_id');
    $page = [
      "name" => "payment_details",
      "inertia" => "Admin/Module/PaymentDetail", // Points to resources/js/Pages/Admin/PaymentDetail/Index.jsx
      "label" => "Detail Pembayaran",
      "url" => "/admin/budgets/{$budgetId}/payment_details",
      "fields" => Helper::getFormFields($this->validation($request)),
    ];

    return $page;
  }

  protected function validation(Request $request, $id = null): array
  {
    return [
      "validation" => [
        // Minimal validation as this is primarily for display
        // Add full validation if create/update features are enabled later
        "amount" => "required|integer",
        "payment_date" => "required|date",
        "description" => "nullable|string",
      ],
      "default" => [],
    ];
  }
}
