<?php namespace App\Controllers\Api\Customer\Profile\SubscribeExtra;

use App\Controllers\PrivateController;
use App\Libraries\Common;
use App\Models\AppsModel;
use App\Models\DepositMethodsModel;
use App\Models\SubscribesExtraModel;
use App\Models\TransactionsExtraModel;
use App\Models\PlansExtraModel; // Thêm model PlansExtraModel
use CodeIgniter\HTTP\ResponseInterface;

define("LIMIT", 20);

class TransactionsExtra extends PrivateController
{
    /**************************************************************************************
     * PUBLIC FUNCTIONS
     **************************************************************************************/

    /**
     * Get subscribe transactions
     * @return ResponseInterface
     */
    public function index(): ResponseInterface
    {
        $offset = (int) $this->request->getGet("offset");
      
      	// Thêm mới: Lấy app_uid và plan_id từ request
        $app_uid = esc($this->request->getVar("uid"));
        $plan_extra_id = esc($this->request->getVar("plan_extra_id"));
      
      	// Tìm app dựa trên uid
        $app = $projects->where("uid", $app_uid)->first();
      
      	$plansExtra = new PlansExtraModel();

        $subscribes_extra = new SubscribesExtraModel();

        $subscribe_extra = $subscribes_extra
            ->where("user_id", $this->userId)
            ->where("is_disable", 0)
          	->where("app_id", $app['id'])
            ->orderBy("id", "DESC")
            ->first();

      	// Nếu không tìm thấy subscribe_extra và có đủ thông tin để tạo mới
        if (!$subscribe_extra && $uid && $plan_extra_id) {

            $plan_extra = $plansExtra->find($plan_extra_id);

            if (!$plan_extra) {
                return $this->respond(["message" => lang("Message.message_99")], 404);
            }

        }

        $transactions_extra = new TransactionsExtraModel();

        $transactions_extra_list = $transactions_extra
            ->where("subscribe_extra_external_id", $subscribe_extra["subscribe_extra_external_id"])
            ->select("uid,amount,created_at,method_id,id")
            ->orderBy("id", "DESC")
            ->findAll(LIMIT, $offset);

        $items = [];

        if ($transactions_extra_list) {
            $method_ids = [];
            foreach ($transactions_extra_list as $item) {
                $method_ids[] = $item["method_id"];
            }

            $deposit_methods = new DepositMethodsModel();

            $methods = $deposit_methods
                ->whereIn("id", $method_ids)
                ->select("id,name,logo")
                ->findAll();

            foreach ($transactions_extra_list as $item) {
                $method = null;
                foreach ($methods as $pay_method) {
                    if ($pay_method["id"] == $item["method_id"]) {
                        $method = $pay_method;
                        break;
                    }
                }
                $items[] = [
                    "uid" => $item["uid"],
                    "amount" => $item["amount"],
                    "method" => [
                        "name" => $method["name"],
                        "logo" => base_url("deposit/".$method["logo"])
                    ],
                    "created_at" => date('d-m-Y H:i', $item['created_at']),
                ];
            }
        }

        $total = $transactions_extra
            ->where("subscribe_extra_external_id", $subscribe_extra["subscribe_extra_external_id"])
            ->countAllResults();

        $projects = new AppsModel();

        $app = $projects
            ->where("id", $subscribe_extra["app_id"])
            ->select("uid, name, link")
            ->first();

        $common = new Common();

		// Lấy thông tin plan
        $plan_extra = $plansExtra->find($subscribe_extra['plan_extra_id'] ?? null);

        $subscribe_extra_item = [
            "uid"        => $subscribe_extra["uid"],
            "created_at" => date('d-m-Y H:i', $subscribe_extra['created_at']),
            "price"      => $subscribe_extra["price"],
            "app"        => [
                "name" => $app["name"],
                "uid"  => $app["uid"],
                "icon" => $common->get_icon($app["uid"]),
                "link" => $app["link"]
            ],
            "is_active"  => (bool) $subscribe_extra["is_active"],
            "build_count_extra" => $plan_extra["build_count_extra"] ?? 0
        ];

        return $this->respond([
            "list" => $items,
            "total" => $total,
            "subscribe_extra" => $subscribe_extra_item
        ], 200);
    }
}