<?php
session_start();
header('Content-Type: application/json');
require_once "../includes/functions.php";

$user_id = $_SESSION['user_id'] ?? 0;

$data = ($_POST);
$planId  = ($data['plan_id']);
if(!$user_id){
    echo json_encode(["status"=>"error","message"=>"Unauthorized"]);
    exit;
}

if(!$planId){
    echo json_encode(["status"=>"error","message"=>"no plan"]);
    exit;
}
$canBuy = canUserPurchasePlan($user_id, $planId);
if(!$canBuy['can_purchase']){
    echo json_encode(["status"=>"error","message"=>$canBuy['reason']]);
    exit;
}

$response = buyPlan($user_id, $planId);
if ($response["status"] === "success") {
    echo json_encode($response);
} else {
    echo json_encode($response);
}


