<?php

namespace App\Helpers\Customer;

use App\Entities\Equipment\CodeEntity;
use App\Models\Customer\ServiceModel;
use CodeIgniter\HTTP\IncomingRequest;

class ServiceHelper extends CustomerHelper
{
    protected ?IncomingRequest $request = null;
    public function __construct(?IncomingRequest $request = null)
    {
        parent::__construct($request);
        $this->setTitleField(field: ServiceModel::TITLE);
    }
    public function getFieldLabel(string $field, array $viewDatas, array $extras = []): string
    {
        switch ($field) {
            case "LINE":
            case "IP":
            case "SERVER":
            case "CPU":
            case "RAM":
            case "STORAGE":
            case "SOFTWARE":
            case "DEFENCE":
            case "DOMAIN":
                $label = form_label(lang("{$viewDatas['class_path']}.label.{$field}"), $field, $extras);
                $extras = ["class" => "btn btn-light btn-circle", "target" => "_self", ...$extras];
                $label .= form_label(
                    ICONS['SETUP'],
                    $field,
                    [
                        "data-src"       => "/admin/customer/serviceitem?serviceinfo_uid={$viewDatas['entity']->getPK()}&item_type={$field}",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#index_action_form",
                        ...$extras
                    ]
                );
                break;
            default:
                $label = parent::getFieldLabel($field, $viewDatas, $extras);
                break;
        }
        return $label;
    }
    public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
    {
        if (in_array($viewDatas['control']['action'], ['create', 'modify', 'create_form', 'modify_form'])) {
            $extras = (strpos($viewDatas['control']['field_rules'][$field], 'required') !== false) ? ["class" => "form-control", "required" => "", ...$extras] : ["class" => "form-control", ...$extras];
        }
        switch ($field) {
            case 'code':
                if (!is_array($viewDatas['control']['filter_optons'][$field])) {
                    throw new \Exception(__METHOD__ . "에서 {$field}의 field_options가 array형태가 아닙니다.");
                }
                //CodeIgniter 4의 form_dropdown()은 options 배열로만 값을 받기 때문에, disabled 속성 같은 개별 옵션에 대한 HTML 속성 추가는 기본적으로 지원하지 않습니다.
                $form_temps = ["<select name=\"{$field}\" class=\"select-field\"" . (isset($extras['onChange']) ? " onChange=\"{$extras['onChange']}\"" : "") . ">"];
                $form_temps[] = "<option value=\"\">" . lang($viewDatas['class_path'] . '.label.' . $field) . " 선택</option>";
                foreach ($viewDatas['control']['filter_optons'][$field]  as $key => $filterEntity) {
                    $disabled = "";
                    if (!array_key_exists('index_content_top_filter', $extras)) {
                        $disabled = $filterEntity->getStatus() === CodeEntity::STATUS_OCCUPIED ? 'disabled="disabled"' : '';
                    }
                    $selected = ($value === $key) ? 'selected="selected"' : '';
                    $form_temps[] = "<option value=\"{$key}\"{$selected} {$disabled}>{$filterEntity->getTitle()}</option>";
                }
                $form_temps[] = '</select>';
                $form = implode("", $form_temps);
                break;
            default:
                $form = parent::getFieldForm($field, $value, $viewDatas, $extras);
                break;
        }
        return $form;
    }
    public function getFieldView(string $field, mixed $value, array $viewDatas, array $extras = []): string|null
    {
        switch ($field) {
            case "LINE":
            case "IP":
            case "SERVER":
            case "CPU":
            case "RAM":
            case "STORAGE":
            case "SOFTWARE":
            case "DEFENCE":
            case "DOMAIN":
                $temps = ["<ul>"];
                foreach ($viewDatas['entity']->getItemEntities($field) as $itemEntity) {
                    // dd($viewDatas['control']['filter_optons'][$field]);
                    $temps[] = sprintf(
                        "<li title=\"%s\">%s&nbsp;%s&nbsp;%s</li>",
                        $itemEntity->getView_Price(),
                        $viewDatas['control']['filter_optons'][$field][$itemEntity->getItemUid()]->getTitle(),
                        $itemEntity->getView_BillingCycle(),
                        $itemEntity->getView_Sale()
                    );
                }
                $temps[] = "</ul>";
                $value = implode("", $temps);
                break;
            default:
                $value = parent::getFieldView($field, $value, $viewDatas, $extras);
                break;
        }
        if (is_array($value)) {
            echo __METHOD__ . "에서 오류: {$field}의 값이 Array형태입니다";
            exit;
        }
        return $value;
    }

    public function getListButton(string $action, array $viewDatas, array $extras = []): string
    {
        switch ($action) {
            case 'history':
                $extras = ["class" => "btn btn-outline btn-primary btn-circle", "target" => "_self", ...$extras];
                $action = form_label(
                    ICONS['HISTORY'],
                    $action,
                    [
                        "data-src" => "/admin/customer/servicehistory?serviceinfo_uid={$viewDatas['entity']->getPK()}",
                        "data-bs-toggle" => "modal",
                        "data-bs-target" => "#index_action_form",
                        ...$extras
                    ]
                );
                break;
            default:
                $action = parent::getListButton($action, $viewDatas, $extras);
                break;
        }
        return $action;
    }
}
