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

use Exception;
use App\Controllers\PrivateController;
use App\Libraries\PaypalClient;
use App\Libraries\Payment;
use CodeIgniter\HTTP\ResponseInterface;

class CreatePaymentRequest extends PrivateController
{
    public function index(): ResponseInterface
    {
        if (!$this->validate($this->create_validation_type())) {
            return $this->respond(["message" => $this->validator->getErrors()], 400);
        }

        try {
            $uid = esc($this->request->getGet("uid"));
            $plan_id = (int)$this->request->getJsonVar("plan_id");
            $user_id = $this->userId;

            $payment = new Payment([
                "user_id" => $user_id,
                "app_uid" => $uid,
                "plan_id" => $plan_id
            ]);

            $requestData = $payment->get_payment_request_data();

            if (!$requestData["event"]) {
                return $this->respond(["message" => $requestData["message"]], 400);
            }

            $paypal = new PaypalClient();

            $order = $paypal->create_order($requestData["data"]);

            if (!$order["event"]) {
                return $this->respond(["message" => $order["message"]], 400);
            }

            return $this->respond(["url" => $order["approval_url"]], 200);
        } catch (Exception $exception) {
            log_message("error", $exception->getMessage());
            return $this->respond(["message" => lang("Message.message_93")], 500);
        }
    }

    private function create_validation_type(): array
    {
        return [
            "plan_id" => [
                "label" => lang("Fields.field_148"),
                "rules" => "required|numeric"
            ],
        ];
    }
}
