<?php
require_once(__DIR__ . '/../config/config.php');
require_once(__DIR__ . '/../classes/Database.php');
require_once(__DIR__ . '/../classes/Payment.php');

session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

$userId = $_SESSION['user_id'];
$db = Database::getInstance();
$payment = new Payment();

// API endpoint to get payment details
if (isset($_GET['action']) && $_GET['action'] === 'get_details') {
    header('Content-Type: application/json; charset=utf-8');
    
    $orderId = $_GET['order_id'] ?? null;
    if (!$orderId) {
        echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
        exit;
    }
    
    // Get payment details (QR + UPI from admin settings)
    $paymentDetails = $payment->getPaymentDetails();
    
    // Log for debugging
    error_log('Payment Details Retrieved: ' . json_encode($paymentDetails));
    
    if (empty($paymentDetails)) {
        echo json_encode(['success' => false, 'message' => 'No payment details configured by admin']);
        exit;
    }
    
    if (empty($paymentDetails['qr_code_path']) && empty($paymentDetails['upi_id'])) {
        echo json_encode(['success' => false, 'message' => 'Admin needs to set QR code and UPI ID in Payment Settings']);
        exit;
    }
    
    // Build absolute URLs for images
    $qrCodeUrl = '';
    if (!empty($paymentDetails['qr_code_path'])) {
        $qrCodeUrl = '/extract/' . $paymentDetails['qr_code_path'];
    }
    
    echo json_encode([
        'success' => true,
        'qr_code' => $qrCodeUrl,
        'upi_id' => $paymentDetails['upi_id'] ?? '',
        'debug' => [
            'qr_code_path' => $paymentDetails['qr_code_path'] ?? 'NOT SET',
            'upi_id' => $paymentDetails['upi_id'] ?? 'NOT SET'
        ]
    ]);
    exit;
}

// Regular page for standalone access (if needed)
$orderId = $_GET['order_id'] ?? null;

if (!$orderId) {
    die('Invalid order ID');
}

$order = $db->fetch(
    'SELECT * FROM payment_orders WHERE order_id = ? AND user_id = ?',
    [$orderId, $userId]
);

if (!$order) {
    die('Order not found');
}

$paymentDetails = $payment->getPaymentDetails();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; display: flex; align-items: center; }
        .payment-card { background: white; border-radius: 16px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; }
        .payment-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; }
        .payment-body { padding: 40px; }
        .qr-section { text-align: center; margin-bottom: 30px; }
        .qr-image { max-width: 250px; border-radius: 8px; border: 2px solid #f0f0f0; }
        .upi-section { background: #f8f9fa; padding: 20px; border-radius: 12px; margin-bottom: 20px; }
        .upi-label { font-size: 12px; color: #666; margin-bottom: 8px; font-weight: 600; }
        .upi-display { display: flex; gap: 10px; }
        .upi-input { flex: 1; background: white; border: 2px solid #e0e0e0; padding: 12px; border-radius: 8px; font-weight: 600; }
        .copy-btn { background: #007AFF; color: white; border: none; padding: 12px 16px; border-radius: 8px; cursor: pointer; font-weight: 600; }
        .form-section { margin-top: 30px; }
        .upload-area { border: 2px dashed #007AFF; padding: 40px 20px; border-radius: 12px; text-align: center; cursor: pointer; transition: all 0.3s; }
        .upload-area:hover { background: #f0f7ff; }
        .preview-img { max-width: 100%; border-radius: 8px; margin-top: 15px; }
        .submit-btn { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border: none; padding: 14px 20px; border-radius: 8px; width: 100%; font-weight: 600; font-size: 16px; cursor: pointer; margin-top: 20px; }
        .submit-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(16, 185, 129, 0.3); }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <div class="payment-card">
                    <div class="payment-header">
                        <h3>Complete Your Payment</h3>
                        <p class="mb-0">Amount: <strong>₹<?php echo number_format($order['amount'], 2); ?></strong></p>
                    </div>
                    
                    <div class="payment-body">
                        <!-- QR Code Section -->
                        <?php if (!empty($paymentDetails['qr_code_path'])): ?>
                        <div class="qr-section">
                            <h6>Scan this QR to pay</h6>
                            <img src="<?php echo htmlspecialchars($paymentDetails['qr_code_path']); ?>" alt="QR Code" class="qr-image">
                        </div>
                        <?php endif; ?>

                        <!-- UPI ID Section -->
                        <?php if (!empty($paymentDetails['upi_id'])): ?>
                        <div class="upi-section">
                            <div class="upi-label">Or pay using UPI ID</div>
                            <div class="upi-display">
                                <input type="text" class="upi-input" value="<?php echo htmlspecialchars($paymentDetails['upi_id']); ?>" readonly id="upi-id">
                                <button class="copy-btn" onclick="copyUPI()">
                                    <i class="fas fa-copy"></i> Copy
                                </button>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Payment Instructions -->
                        <div class="alert alert-info">
                            <strong>After payment:</strong><br>
                            1. Come back to this page<br>
                            2. Enter the Transaction ID/UTR<br>
                            3. Upload payment screenshot<br>
                            4. Submit for verification
                        </div>

                        <!-- Form Section -->
                        <div class="form-section">
                            <form id="payment-form">
                                <div class="mb-3">
                                    <label class="form-label">Transaction ID / UTR</label>
                                    <input type="text" class="form-control" id="utr" placeholder="Enter UTR from your bank" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Payment Screenshot</label>
                                    <div class="upload-area" onclick="document.getElementById('screenshot').click()">
                                        <i style="font-size: 40px; color: #007AFF;">📸</i>
                                        <p class="mt-2 mb-0">Click to upload or drag and drop</p>
                                        <small>PNG, JPG, GIF (Max 5MB)</small>
                                        <input type="file" id="screenshot" accept="image/*" style="display: none;">
                                    </div>
                                    <img id="preview" class="preview-img" style="display: none;">
                                </div>

                                <button type="submit" class="submit-btn">✓ Submit Payment</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function copyUPI() {
            const upiId = document.getElementById('upi-id');
            upiId.select();
            document.execCommand('copy');
            alert('UPI ID copied!');
        }

        // Screenshot preview
        document.getElementById('screenshot').addEventListener('change', function(e) {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    document.getElementById('preview').src = event.target.result;
                    document.getElementById('preview').style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });

        // Form submission
        document.getElementById('payment-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const utr = document.getElementById('utr').value.trim();
            const screenshot = document.getElementById('screenshot').files[0];
            
            if (!utr) {
                alert('Please enter Transaction ID/UTR');
                return;
            }
            
            if (!screenshot) {
                alert('Please upload payment screenshot');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'submit_manual_payment');
            formData.append('order_id', '<?php echo htmlspecialchars($orderId); ?>');
            formData.append('transaction_id', utr);
            formData.append('payment_screenshot', screenshot);
            
            const btn = this.querySelector('button[type="submit"]');
            btn.disabled = true;
            btn.innerText = 'Submitting...';
            
            fetch('../user/dashboard.php', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    alert('Payment submitted! Admin will verify within 1-2 hours.');
                    window.location.href = 'dashboard.php';
                } else {
                    alert('Error: ' + (data.message || 'Failed to submit'));
                    btn.disabled = false;
                    btn.innerText = '✓ Submit Payment';
                }
            })
            .catch(err => {
                alert('Error: ' + err.message);
                btn.disabled = false;
                btn.innerText = '✓ Submit Payment';
            });
        });
    </script>
</body>
</html>
