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

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

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

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

            $current_user = $payment->get_current_user();
            $requestData["data"]["email"] = $current_user["email"];

            $paystack = new PaystackClient();

            $order = $paystack->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) {
            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"
            ],
        ];
    }
}
