<?php
session_start();
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}
include '../include/config.php';

$item_type = $_POST['item_type'];
$customer_email = $_POST['customer_email'] ?? '';

$item = $conn->query("SELECT * FROM payment_items WHERE item_type = '$item_type'")->fetch_assoc();

if ($item) {
    $link_token = 'PAY_' . strtoupper(uniqid()) . '_' . time();
    $expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));
    
    $insert = $conn->query("
        INSERT INTO payment_links (link_token, item_type, amount, customer_email, expires_at) 
        VALUES ('$link_token', '$item_type', '{$item['price']}', '$customer_email', '$expires_at')
    ");
    
    if ($insert) {
        $paylink_url = "https://uhd.com.ng/payment/pay.php?token=" . $link_token;
        
        // Show the generated link
        echo "<!DOCTYPE html>
        <html>
        <head><title>PayLink Generated</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css' rel='stylesheet'></head>
        <body class='bg-light'>
        <div class='container mt-5'>
            <div class='card shadow rounded-4'>
                <div class='card-header bg-success text-white'>
                    <h4>PayLink Generated Successfully</h4>
                </div>
                <div class='card-body'>
                    <p><strong>Item:</strong> {$item['item_name']}</p>
                    <p><strong>Amount:</strong> ₦" . number_format($item['price'], 2) . "</p>
                    <p><strong>PayLink URL:</strong></p>
                    <div class='input-group mb-3'>
                        <input type='text' class='form-control' id='paylink_url' value='$paylink_url' readonly>
                        <button class='btn btn-primary' onclick='copyLink()'>Copy</button>
                    </div>
                    <p><strong>QR Code:</strong></p>
                    <img src='https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($paylink_url) . "' alt='QR Code'>
                    <div class='mt-4'>
                        <a href='payment_links.php' class='btn btn-secondary'>View All Payment Links</a>
                        <a href='payment_settings.php' class='btn btn-outline-primary'>Back to Settings</a>
                    </div>
                </div>
            </div>
        </div>
        <script>
        function copyLink() {
            navigator.clipboard.writeText(document.getElementById('paylink_url').value);
            alert('Link copied to clipboard!');
        }
        </script>
        </body>
        </html>";
        exit();
    }
}

header("Location: payment_settings.php");
exit();
?>