<?php
// function/generate-license.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../include/conn.php';
require_once __DIR__ . '/../include/function.php';

// Si usas sesión para el admin_id
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

$response = [];

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new RuntimeException('Invalid request method.');
    }

    // Entradas del formulario
    $wnumber      = isset($_POST['wnumber'])  ? trim((string)$_POST['wnumber']) : '';
    $cname        = isset($_POST['cname'])    ? trim((string)$_POST['cname'])   : '';
    $email        = isset($_POST['email'])    ? trim((string)$_POST['email'])   : '';
    $password     = isset($_POST['password']) ? (string)$_POST['password']      : '';
    $endDateInput = isset($_POST['endDate'])  ? trim((string)$_POST['endDate']) : '';
    $orderid      = isset($_POST['orderid'])  ? trim((string)$_POST['orderid']) : '';

    // user_id desde la sesión; por defecto "2" (en tu schema user_id es VARCHAR)
    $admin_id = (isset($_SESSION['id']) && $_SESSION['id'] !== '') ? (string)$_SESSION['id'] : '2';

    // Validaciones
    if ($wnumber === '' || $cname === '' || $email === '' || $password === '' || $endDateInput === '') {
        throw new InvalidArgumentException('Please fill in all required fields.');
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new InvalidArgumentException('Invalid email format.');
    }

    // Número de WhatsApp: permite +, espacios, -, ()
    if (!preg_match('/^\+?[0-9\s\-()]{6,20}$/', $wnumber)) {
        throw new InvalidArgumentException('Invalid WhatsApp number. Include country code, e.g. +34123456789');
    }

    // Chequeo de número duplicado (usa tu helper si existe)
    if (function_exists('check_number') && check_number($wnumber) === true) {
        throw new InvalidArgumentException('WhatsApp Number Already Exists.');
    }

    // Fechas: usamos la fecha fin exacta del formulario
    try {
        // Si recibes "YYYY-MM-DD", extiéndela al final del día
        $fin = new DateTime($endDateInput . (strlen($endDateInput) === 10 ? ' 23:59:59' : ''));
        $now = new DateTime();
    } catch (Exception $e) {
        throw new InvalidArgumentException('Invalid end date.');
    }

    if ($fin < $now) {
        throw new InvalidArgumentException('End date cannot be in the past.');
    }

    $todayStr   = $now->format('Y-m-d H:i:s');
    $endDateStr = $fin->format('Y-m-d H:i:s');

    // Clave de licencia (tu helper)
    if (!function_exists('generate_license')) {
        throw new RuntimeException('generate_license() not found.');
    }
    $licenseKey = generate_license();

    // CONTRASEÑA EN TEXTO PLANO (según tu solicitud; NO se hace hash)
    $passwordToStore = $password;

    // Conexión MySQLi
    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new RuntimeException('Database connection ($conn) not found.');
    }

    // Charset (tabla utf8mb4; token en latin1, pero UUID() es ASCII)
    if (method_exists($conn, 'set_charset')) {
        $conn->set_charset('utf8mb4');
    }

    // Si orderid llega vacío, lo mandamos como NULL
    $orderidForDb = ($orderid === '') ? null : $orderid;

    // INSERT: incluimos token con UUID() para evitar el error NOT NULL
    $sql = "INSERT INTO `users`
            (`user_id`, `orderid`, `customer_name`, `whatsapp_number`, `license_key`,
             `token`, `act_date`, `end_date`, `plan_expiry_date`, `life_time`, `plan_type`,
             `email`, `password`)
            VALUES
            (?, ?, ?, ?, ?, UUID(), ?, ?, ?, 'false', 'Premium', ?, ?)";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new RuntimeException('Failed to prepare statement: ' . $conn->error);
    }

    // Todas como string; pasar NULL en $orderidForDb es válido
    $stmt->bind_param(
        'ssssssssss',
        $admin_id,        // user_id (VARCHAR)
        $orderidForDb,    // orderid (NULL o string)
        $cname,           // customer_name
        $wnumber,         // whatsapp_number
        $licenseKey,      // license_key
        $todayStr,        // act_date (VARCHAR)
        $endDateStr,      // end_date (VARCHAR)
        $endDateStr,      // plan_expiry_date (VARCHAR)
        $email,           // email
        $passwordToStore  // password (texto plano)
    );

    if (!$stmt->execute()) {
        if ($conn->errno === 1062) {
            // Por si tienes índices únicos en email/whatsapp/token
            throw new RuntimeException('Duplicate key. Email, whatsapp_number or token already exists.');
        }
        throw new RuntimeException('Failed to insert data: ' . $conn->error);
    }

    $stmt->close();

    $response['status']  = true;
    $response['message'] = "License key generated: $licenseKey";

} catch (Throwable $e) {
    $response['status']  = false;
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
