<?php
/**
 * create_static_paylink.php
 * Public API endpoint (see /api/create-static-paylink in root .htaccess).
 * Same shape/style as payment/create_order.php - auth is via user_token,
 * just like every other API this project exposes.
 */
define('PROJECT_ROOT', realpath(dirname(__FILE__)) . '/../');
include PROJECT_ROOT . 'pages/dbFunctions.php';
include PROJECT_ROOT . 'pages/dbInfo.php';
include PROJECT_ROOT . 'auth/config.php';
include PROJECT_ROOT . 'includes/subscription_lib.php';
include PROJECT_ROOT . 'includes/static_paylink_lib.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
header("Content-Type: application/json");

$userToken = $_POST['user_token'] ?? '';
if ($userToken === '') {
    echo json_encode(["status" => false, "message" => "user_token is required"]);
    exit;
}

$userRes = mysqli_query($conn, "SELECT id, user_token FROM users WHERE user_token = '" . mysqli_real_escape_string($conn, $userToken) . "' LIMIT 1");
if (!$userRes || mysqli_num_rows($userRes) === 0) {
    echo json_encode(["status" => false, "message" => "Invalid user_token"]);
    exit;
}
$user = mysqli_fetch_assoc($userRes);

$result = sp_create_link($conn, (int)$user['id'], $user['user_token'], [
    'title'          => $_POST['title'] ?? '',
    'description'    => $_POST['description'] ?? '',
    'amount'         => $_POST['amount'] ?? 0,
    'validity'       => $_POST['validity'] ?? '7d',
    'paylink_type'   => $_POST['paylink_type'] ?? 'normal',
    'redirect_url'   => $_POST['redirect_url'] ?? '',
    'collect_name'   => !empty($_POST['collect_name']),
    'collect_mobile' => !empty($_POST['collect_mobile']),
    'collect_email'  => !empty($_POST['collect_email']),
]);

if (!$result['ok']) {
    echo json_encode(["status" => false, "message" => $result['message']]);
    exit;
}

include_once PROJECT_ROOT . 'includes/white_label_lib.php';
$linkDomain = get_merchant_domain($conn, (int)$user['id']);
$paylinkUrl = 'https://' . $linkDomain . '/s/' . $result['link_id'];

echo json_encode([
    "status"  => true,
    "message" => "Static Paylink Created Successfully",
    "result"  => [
        "link_id"      => $result['link_id'],
        "paylink_url"  => $paylinkUrl,
    ],
]);
