<?php
/**
 * =====================================================================
 * NadiPlayer — nadi.kr/ signup kit
 * =====================================================================
 * Drop this folder at your webroot, e.g.:
 *     /home/koreama/public_html/nadiplayer/   (nadi.kr/)
 *
 * What it does:
 *   • Exposes POST /api/signup.php — called after a successful payment
 *     on your website. Creates a `user` row in the SAME MySQL database
 *     that powers 4kmovies.vip/nadiplayer/api/ (koreama_nadiplayer).
 *   • Sets ads_enabled = 0 (no ads for paying subscriber).
 *   • Sets expiry_at based on the plan code passed by the caller.
 *   • Returns the freshly-created username + password so the storefront
 *     can immediately display them to the buyer AND email them.
 *
 * Security:
 *   • Protected by a shared-secret header `X-Signup-Secret`.  Put the
 *     same secret in config.php → SIGNUP_SECRET and in your payment
 *     gateway post-success webhook.
 *   • Only the server that handled the payment should know the secret,
 *     so a leaked URL alone cannot mint accounts.
 * =====================================================================
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/util.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, X-Signup-Secret');
header('Access-Control-Allow-Methods: POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_error(405, 'Method not allowed');
}

// ── Shared-secret gate ───────────────────────────────────────────
$provided = $_SERVER['HTTP_X_SIGNUP_SECRET'] ?? '';
if (!hash_equals(SIGNUP_SECRET, $provided)) {
    json_error(401, 'Invalid signup secret');
}

$body = read_json_body();

// ── Resolve plan → days ──────────────────────────────────────────
$plan_code = strtolower((string)($body['plan'] ?? 'monthly'));
$plans = [
    'monthly'  => 30,
    'quarter'  => 90,
    'half'     => 180,
    'yearly'   => 365,
    'biyearly' => 730,
];
$days = $plans[$plan_code] ?? 30;
// Allow override if the caller explicitly passes `days`
if (isset($body['days'])) {
    $days = max(1, min(3650, (int)$body['days']));
}

// ── Username & password: auto-generate unless caller provides them ──
$username = isset($body['username']) ? strtolower(trim($body['username'])) : null;
$password = $body['password'] ?? null;

if (!$username) {
    // e.g. "nadi-9F3K2" — short, memorable, collision-unlikely
    do {
        $username = 'nadi-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 5));
        $check = db()->prepare('SELECT 1 FROM users WHERE username = ?');
        $check->execute([$username]);
    } while ($check->fetch());
}
if (!$password) {
    // 10-char alphanumeric password (no ambiguous 0/O/1/l)
    $alphabet = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789';
    $password = '';
    for ($i = 0; $i < 10; $i++) {
        $password .= $alphabet[random_int(0, strlen($alphabet) - 1)];
    }
}

// Sanity validate
if (strlen($username) < 2 || strlen($username) > 40) json_error(400, 'Bad username length');
if (strlen($password) < 6)                         json_error(400, 'Password too short');

// Guard against duplicates if the caller passed their own username
$dup = db()->prepare('SELECT 1 FROM users WHERE username = ?');
$dup->execute([$username]);
if ($dup->fetch()) json_error(409, 'Username already exists');

// ── Insert ───────────────────────────────────────────────────────
ensure_schema();
$now    = new DateTime('now', new DateTimeZone('UTC'));
$expiry = (clone $now)->modify("+{$days} days");

$stmt = db()->prepare(
    'INSERT INTO users
        (id, username, password_hash, role, created_at, expiry_at,
         xtream_mode, xtream_server, xtream_username, xtream_password,
         note, ads_enabled)
     VALUES (?, ?, ?, "user", ?, ?, "shared", "", "", "", ?, 0)'
);
$id = uuid_v4();
$note = 'Auto-created via nadi.kr signup · plan=' . $plan_code
      . ' · payment_ref=' . (string)($body['payment_ref'] ?? '')
      . ' · email=' . (string)($body['email'] ?? '');

$stmt->execute([
    $id,
    $username,
    password_hash($password, PASSWORD_BCRYPT),
    $now->format('Y-m-d\TH:i:s.uP'),
    $expiry->format('Y-m-d\TH:i:s.uP'),
    $note,
]);

// ── Respond with the fresh credentials ───────────────────────────
send_json([
    'ok'         => true,
    'username'   => $username,
    'password'   => $password,
    'plan'       => $plan_code,
    'days'       => $days,
    'expiry_at'  => $expiry->format('c'),
    'ads_enabled'=> false,
    'message'    => "Subscriber created. Welcome to NadiPlayer Premium!",
]);
