<?php
include "auth.php";
include "db.php";
include "geo_check.php";
include "stripe_api_keys.php";
require_once 'stripe-php/init.php';

$title = $_POST['title'];
$price = $_POST['price'];
$merchant = $_POST['merchant'];
$currency= $_POST['currency'];
$username = $_SESSION['user'];
$userCountry = getUserCountry();

// ✅ Country restriction check
$allowed = ($merchant == "IBT" && $userCountry == "Canada") || ($merchant == "LMT" && $userCountry == "United States");

if (!$allowed) {
    echo "<div style='color:red; font-weight:bold; font-size:18px; padding:20px;'>❌ Payment link creation is only allowed from: 
          <ul>
              <li>🇨🇦 Canada for IBT</li>
              <li>🇺🇸 USA for LMT</li>
          </ul>
          Your current location is <b>$userCountry</b>.<br>Please open this panel using a VPS or system from the correct country.
          <br><br><a href='create.php'>⏪ Go Back</a>
          </div>";
    exit;
}

// ✅ Upload image to server
$image = $_FILES['image']['name'];
$targetDir = "uploads/";
$target = $targetDir . basename($image);
move_uploaded_file($_FILES['image']['tmp_name'], $target);

// ✅ Generate full public HTTPS image URL
$imageUrl = "https://digital-cloud-server.com/payment_links/uploads/" . str_replace(' ', '%20', $image);

// ✅ Set Stripe API key
\Stripe\Stripe::setApiKey($stripeKeys[$merchant]);

try {
    // ✅ Create Stripe Checkout Session with image
    // $session = \Stripe\Checkout\Session::create([
    //     'payment_method_types' => ['card'],
    //     'line_items' => [[
    //         'price_data' => [
    //             'currency' => $currency,
    //             'product_data' => [
    //                 'name' => $title,
    //                 'images' => [$imageUrl],
    //             ],
    //             'unit_amount' => $price * 100,
    //         ],
    //         'quantity' => 1,
    //     ]],
    //     'mode' => 'payment',
    //     'success_url' => 'https://digital-cloud-server.com/payment_links/list.php',
    //     'cancel_url' => 'https://digital-cloud-server.com/payment_links/create.php',
    // ]);



$product = \Stripe\Product::create([
        'name' => $title,
        'images' => [$imageUrl],
    ]);

    // Step 2: Create Price for product
    $priceObj = \Stripe\Price::create([
        'product' => $product->id,
        'unit_amount' => $price * 100,
        'currency' => $currency,
    ]);

    // Step 3: Create Payment Link
    $paymentLink = \Stripe\PaymentLink::create([
        'line_items' => [[
            'price' => $priceObj->id,
            'quantity' => 1,
        ]],
        'after_completion' => [
            'type' => 'redirect',
            'redirect' => ['url' => 'https://digital-cloud-server.com/payment_links/list.php'] // ✅ Replace
        ],
    ]);



    $paymentUrl = $paymentLink->url;
    $paymentLinkId = $paymentLink->id;
    //   echo "<pre>";
    //   print_r($paymentLink);
    //   echo "</pre>";
    // //   exit();
    // ✅ Save to database
    $stmt = $conn->prepare("INSERT INTO payment_links (title, price, image, merchant, username, stripe_link, stripe_link_id,currency) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sdssssss", $title, $price, $image, $merchant, $username, $paymentUrl, $paymentLinkId,$currency);
    $stmt->execute();

    // Redirect to Stripe Checkout
    header("Location: $paymentUrl");
    exit;

} catch (Exception $e) {
    echo "<div style='color: red;'>Stripe Error: " . htmlspecialchars($e->getMessage()) . "</div>";
}