<?php namespace App\Controllers\Api\Customer\Payment\Paystack;

use App\Controllers\PrivateController;
use App\Libraries\PaystackClient;
use App\Models\SubscribesModel;
use App\Models\TransactionsModel;
use App\Models\UsersModel;
use CodeIgniter\HTTP\ResponseInterface;

class CancelSubscribe extends PrivateController
{
    public function index(): ResponseInterface
    {
        $subscribe_uid = esc($this->request->getGet("uid"));

        $users = new UsersModel();

        $user = $users
            ->where("id", $this->userId)
            ->select("admin")
            ->first();

        $subscribes = new SubscribesModel();

        if ($user["admin"]) {
            $subscribe = $subscribes
                ->where("is_disable", 0)
                ->where("uid", $subscribe_uid)
                ->where("is_active", 1)
                ->first();
        } else {
            $subscribe = $subscribes
                ->where("user_id", $this->userId)
                ->where("is_disable", 0)
                ->where("uid", $subscribe_uid)
                ->where("is_active", 1)
                ->first();
        }

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

        $transactions = new TransactionsModel();

        $transaction = $transactions
            ->where("subscribe_external_id", $subscribe["subscribe_external_id"])
            ->select("data_json")
            ->first();

        $data = json_decode($transaction["data_json"], true);
        $token = $data["email_token"];

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

        $paystack = new PaystackClient();

        try {
            $paystack->cancel_subscription($subscribe["subscribe_external_id"], $token);
            $subscribes->update($subscribe["id"], [
                "is_active" => 0
            ]);
            return $this->respond(["status" => "ok"], 200);
        } catch (\Exception $e) {
            return $this->respond(["message" => $e->getMessage()], 400);
        }
    }
}