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

use App\Controllers\PrivateController;
use App\Libraries\PaypalClient;
use App\Models\SubscribesModel;
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);
        }

        $paypal = new PaypalClient();

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