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

use App\Controllers\PrivateController;
use App\Libraries\Payment;
use CodeIgniter\HTTP\ResponseInterface;
use Stripe\Exception\ApiErrorException;
use App\Libraries\StripeClient;

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

    /**
     * Create subscribe request with Stripe
     * @return ResponseInterface
     * @throws ApiErrorException
     */
    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);
            }

            $stripe = new StripeClient();

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

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

            return $this->respond(["url" => $order["approval_url"]], 200);
        } catch (\Exception $e) {
            log_message('error', $e->getMessage());
            return $this->respond(["message" => $e->getMessage()], 400);
        }
    }

    /**************************************************************************************
     * PRIVATE FUNCTIONS
     **************************************************************************************/

    /**
     * Get validation rules for create new payment
     * @return array
     */
    private function create_validation_type(): array
    {
        return [
            "plan_id" => [
                "label" => lang("Fields.field_148"),
                "rules" => "required|numeric"
            ],
        ];
    }
}