<?php
namespace App\Controllers\Api\Ipn;

use App\Controllers\BaseController;
use App\Libraries\Payment;
use CodeIgniter\HTTP\ResponseInterface;
use App\Libraries\StripeClient;

class Stripe extends BaseController
{
    private $stripe;

    public function __construct()
    {
        $this->stripe = new StripeClient();
    }

    public function index(): ResponseInterface
    {
        $bodyRaw = file_get_contents('php://input');

        $result = $this->stripe->process_webhook($bodyRaw);

        if (!$result["event"]) {
            // Webhook not processed, skip
            return $this->respond(["status" => "ok"], 200);
        }

        $customValues = explode("_", $result["custom_id"]);

        $app_id = $customValues[0];
        $user_id = $customValues[1];
        $plan_id = $customValues[2];

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

        switch ($result["event_type"]) {
            case 'checkout.session.completed':
                $payment->create_subscription([
                    "subscribe_external_id" => $result["order_id"],
                    "customer_external_id" => $result["customer_id"],
                    "price" => (float)$result["amount"],
                    "method_route" => "stripe",
                ]);
                break;
            case 'customer.subscription.updated':
                if ($result["current_period_end"] ) {
                    $payment->update_subscription([
                        "expires_at" => $result["current_period_end"],
                    ], true);
                }
                if ($result["cancel_at"] ) {
                    $payment->cancel_subscription([
                        "cancel_at" => $result["cancel_at"],
                    ]);
                }
                break;
            case 'payment_intent.succeeded':
                $payment->create_transaction([
                    "subscribe_external_id" => $result["order_id"],
                    "external_uid" => $result["resource_id"],
                    "price" => (float)$result["amount"],
                    "method_route" => "stripe",
                    "event_data" => $result,
                ]);
                break;

            default:
                return $this->respond(["message" => "Unhandled event type"], 400);
        }

        return $this->respond(["status" => "ok"], 200);
    }
}
