<?php
require_once 'config.php';

header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 0);

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'داده‌ای ارسال نشده است.']);
    exit;
}

$customer_name    = trim($input['customer_name'] ?? 'کاربر ویولکس');
$customer_phone   = trim($input['customer_phone'] ?? '');
$product_name     = trim($input['product_name'] ?? '');
$price            = (int)($input['price'] ?? 0);
$quantity         = (int)($input['quantity'] ?? 1);
$total_amount     = $price * $quantity;
$telegram_chat_id = trim($input['telegram_chat_id'] ?? '');
$package_id       = isset($input['package_id']) ? (int)$input['package_id'] : null;
$card_id          = isset($input['card_id']) ? (int)$input['card_id'] : null;

if (empty($customer_name) || empty($customer_phone) || empty($product_name) || $total_amount <= 0) {
    http_response_code(422);
    echo json_encode(['status' => 'error', 'message' => 'اطلاعات ارسالی ناقص یا نامعتبر است.']);
    exit;
}

// تولید توکن یکتا
$token = bin2hex(random_bytes(16));
$now = date('Y/m/d H:i:s');
$expires_at = date('Y/m/d H:i:s', strtotime('+1 hour'));

// === باطل کردن فاکتورهای باز قبلی ===
try {
    $cancel_stmt = $pdo->prepare("UPDATE invoices SET status = 'expired' WHERE user_id = ? AND status = 'pending'");
    $cancel_stmt->execute([$telegram_chat_id]);
} catch (Exception $e) {
}

// ذخیره در دیتابیس — با ستون‌های صحیح
$stmt = $pdo->prepare("
    INSERT INTO invoices
    (token, user_id, payer_name, payer_phone, product_name, price, quantity,
     total_amount, package_id, card_id, status, created_at, expires_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)
");

try {
    $stmt->execute([
        $token, $telegram_chat_id, $customer_name, $customer_phone, $product_name,
        $price, $quantity, $total_amount, $package_id, $card_id,
        $now, $expires_at
    ]);

    $invoice_url = BASE_URL . "/invoice/pay.php?token=" . urlencode($token);

    echo json_encode([
        'status' => 'success',
        'token' => $token,
        'invoice_id' => $token,
        'invoice_url' => $invoice_url,
        'expires_at' => $expires_at,
        'total_amount' => $total_amount
    ], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'خطا در ثبت فاکتور: ' . $e->getMessage()]);
}
