<?php

namespace App\Models\Customer;

use App\Entities\Customer\PaymentEntity;
use App\Libraries\LogCollector;

class PaymentModel extends CustomerModel
{
    const TABLE = "payment";
    const PK = "uid";
    const TITLE = "title";
    protected $table            = self::TABLE;
    protected $primaryKey       = self::PK;
    protected $returnType       = PaymentEntity::class;
    protected $allowedFields = [
        "user_uid",
        "clientinfo_uid",
        "serviceinfo_uid",
        "title",
        "amount",
        "billing",
        "billing_at",
        "pay",
        "status",
        "updated_at"
    ];
    public function __construct()
    {
        parent::__construct();
    }
    public function getFormFieldRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            case "user_uid":
            case "clientinfo_uid":
            case "serviceinfo_uid":
            case "amount":
                $rule = "required|numeric";
                break;
            case "title":
            case "billing":
            case "status":
                $rule = "required|trim|string";
                break;
            case "billing_at":
                $rule = "required|valid_date";
                break;
            case "pay":
                $rule = "permit_empty|trim|string";
                break;
            default:
                $rule = parent::getFormFieldRule($action, $field);
                break;
        }
        return $rule;
    }

    /**
     * 서비스(고객)별 미납결제정보
     * @param array<string> checkDate = 'now' , '-1 day' , '-2 day'등
     * @return array<string, array<string,int>> 
     * [serviceinfo_uid => count], [clientinfo_uid => count]
     */
    final public function getUnPaidCount(string $checkDate = 'now', string $idx_field = "serviceinfo_uid"): array
    {
        // strtotime 기준으로 날짜 계산
        $dateTime = date('Y-m-d H:i:s', strtotime($checkDate));
        $rows = $this->asArray()
            ->select("{$idx_field}, COUNT(*) as cnt")
            ->where('billing_at <', $dateTime)
            ->where('amount >', 0)
            ->where('status', PaymentEntity::STATUS_UNPAID)
            ->groupBy($idx_field)
            ->findAll();
        //array_column($rows, 'cnt', 'serviceinfo_uid')는 serviceinfo_uid를 키로 하고 cnt를 값으로 하는 연관 배열을 생성합니다.
        return array_column($rows, 'cnt', $idx_field);
    }
}
