<?php
require_once __DIR__ . '/../../config/db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$fingerprint = $input['fingerprint'] ?? null;
$plan = $input['plan'] ?? null;
$amount = $input['amount'] ?? null;

if (!$fingerprint || !$plan || !$amount) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

// Expire old pending payments for this user to avoid confusion
try {
    $stmt = $pdo->prepare("UPDATE cliq_payments SET status = 'expired' WHERE fingerprint = :fingerprint AND status = 'pending'");
    $stmt->execute([':fingerprint' => $fingerprint]);

    // Generate a unique 6-character reference code (e.g. JB-1A2B3C)
    $refCode = 'JB-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 6));

    // Insert new pending payment
    $stmt = $pdo->prepare("INSERT INTO cliq_payments (fingerprint, reference_code, amount, plan, status) VALUES (:fingerprint, :refCode, :amount, :plan, 'pending')");
    $stmt->execute([
        ':fingerprint' => $fingerprint,
        ':refCode' => $refCode,
        ':amount' => $amount,
        ':plan' => $plan
    ]);

    echo json_encode([
        'success' => true,
        'reference_code' => $refCode,
        'amount' => $amount,
        'cliq_alias' => 'JordanBot', // Change this to the actual CliQ alias
        'expires_in_minutes' => 10
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
