<?php
include 'header.php';

// Handle form submission
if(isset($_POST['subscribe'])) {
    // Get form data
    $whatsapp_number = trim($_POST['whatsapp_number']);
    $transaction_hash = trim($_POST['transaction_hash']);
    $amount = $signals_fee;
    $subscription_date = date('Y-m-d H:i:s');
    $expiry_date = date('Y-m-d H:i:s', strtotime('+1 month'));
    $status = 'pending';
    
    // Initialize variables
    $error = '';
    $success = '';
    $targetFile = '';
    
    // Validate inputs
    if(empty($whatsapp_number)) {
        $error = "WhatsApp number is required";
    }
    elseif(!preg_match('/^\+[1-9]\d{1,14}$/', $whatsapp_number)) {
        $error = "Please enter a valid WhatsApp number with country code (e.g., +1234567890)";
    }
    elseif(empty($transaction_hash)) {
        $error = "Transaction hash is required";
    }
    elseif(!isset($_FILES['payment_proof']) || $_FILES['payment_proof']['error'] == UPLOAD_ERR_NO_FILE) {
        $error = "Payment proof is required";
    }
    else {
        // Process file upload
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
        $fileExtension = strtolower(pathinfo($_FILES['payment_proof']['name'], PATHINFO_EXTENSION));
        
        // Validate file
        $check = getimagesize($_FILES['payment_proof']['tmp_name']);
        if($check === false) {
            $error = "File is not an image";
        }
        elseif(!in_array($fileExtension, $allowedExtensions)) {
            $error = "Only JPG, JPEG, PNG & GIF files are allowed";
        }
        elseif($_FILES['payment_proof']['size'] > 5000000) { // 5MB
            $error = "File size must be less than 5MB";
        }
        else {
            // Create upload directory if not exists
            $uploadDir = '../uploads/payment_proofs/';
            if(!file_exists($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            // Generate unique filename
            $filename = 'proof_' . $user_id . '_' . time() . '.' . $fileExtension;
            $targetFile = $uploadDir . $filename;
            
            // Move uploaded file
            if(!move_uploaded_file($_FILES['payment_proof']['tmp_name'], $targetFile)) {
                $error = "Error uploading payment proof";
            }
        }
    }
    
    // If no errors, insert to database
    if(empty($error)) {
        // Generate subscription ID
        $subscription_id = 'SIG-' . strtoupper(uniqid());
        
        // Prepare SQL statement
        $sql = "INSERT INTO signal_subscriptions 
                (subscription_id, user_id, whatsapp_number, transaction_hash, payment_proof, amount, subscription_date, expiry_date, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        if($stmt === false) {
            $error = "Database error: " . $conn->error;
        }
        else {
            // Bind parameters
            $stmt->bind_param("sisssdsss", 
                $subscription_id,
                $user_id,
                $whatsapp_number,
                $transaction_hash,
                $targetFile,
                $amount,
                $subscription_date,
                $expiry_date,
                $status
            );
            
            // Execute query
            if($stmt->execute()) {
                $success = "Your signal subscription request has been submitted successfully!";
                
                    $userSubject = "Signal Subscription Confirmation - $sitename";
                    $userBody = "
                    <div style='background: #E4E9F0; padding: 20px; font-family: Arial, sans-serif;'>
                        <div style='max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);'>
                            <div style='background-color: #1e293b; padding: 16px; display: flex; align-items: center;'>
                                <div style='display: flex; align-items: center;'>
                                    <center><img src='$site_url/user/image/logo.png' width='100px' style='margin-right: 8px;'></center>
                                </div>
                            </div>
                            <div style='padding: 32px; text-align: center;'>
                                <h1 style='font-size: 28px; color: #1e293b; margin-bottom: 24px; line-height: 1.2;'>
                                    Signal Subscription Received
                                </h1>
                                <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                                    Dear $first_name, thank you for subscribing to our premium trading signals service.
                                </p>
                                
                                <div style='text-align: left; margin-bottom: 24px;'>
                                    <h3 style='color: #1e293b;'>Subscription Details:</h3>
                                    <p><strong>Subscription ID:</strong> $subscription_id</p>
                                    <p><strong>Amount Paid:</strong> \$" . number_format($amount, 2) . "</p>
                                    <p><strong>WhatsApp Number:</strong> $whatsapp_number</p>
                                    <p><strong>Payment Method:</strong> USDT (TRC20)</p>
                                    <p><strong>Transaction Hash:</strong> $transaction_hash</p>
                                    <p><strong>Status:</strong> Pending Verification</p>
                                    <p><strong>Subscription Date:</strong> $subscription_date</p>
                                    <p><strong>Expiry Date:</strong> $expiry_date</p>
                                </div>
                                
                                <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                                    Our team will verify your payment within 24 hours. Once approved, you'll start receiving daily trading signals via WhatsApp.
                                </p>
                                
                                <div style='background: #f0fdf4; border-left: 4px solid #22c55e; padding: 16px; margin-bottom: 24px; text-align: left;'>
                                    <h4 style='color: #166534; margin-top: 0;'>What to Expect:</h4>
                                    <ul style='color: #4b5563; padding-left: 20px;'>
                                        <li>3-5 high-probability signals daily</li>
                                        <li>Detailed entry and exit points</li>
                                        <li>Risk management guidance</li>
                                        <li>Market analysis reports</li>
                                    </ul>
                                </div>
                                
                                <div style='margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: left;'>
                                    <p style='color: #4b5563; margin-bottom: 8px;'>Happy Trading,</p>
                                    <p style='color: #4b5563; font-weight: bold;'>Trading Team, $sitename</p>
                                </div>
                            </div>
                        </div>
                    </div>";
                    
                    
                    sendMail($email, $userSubject, $userBody); // To user
   
            }
            else {
                $error = "Error submitting subscription: " . $stmt->error;
            }
            
            $stmt->close();
        }
    }
    
    // Show JavaScript alert based on result
    if(!empty($error)) {
        echo "<script>
            alert('Error: " . addslashes($error) . "');
            window.history.back();
        </script>";
    } 
    elseif(!empty($success)) {
        echo "<script>
            alert('Success: " . addslashes($success) . "');
            window.location.href = 'dashboard.php';
        </script>";
    }
    exit(); // Stop further execution after showing alert
}
?>

<!-- HTML Form Section -->
<div class="pt-28 md:pt-0 mt-0 md:mt-36 w-full md:w-4/5" id="general-content">
    <div class="w-full md:w-10/12 md:ml-64 2xl:ml-1/5" id="general-content-section">
        <div class="w-full py-5">
            <div class="w-full flex justify-center">
                <div class="w-11/12 rounded-md bg-[#0e1726] p-2 md:p-4">
                    <div class="flex justify-between items-center">
                        <div>
                            <h2 class="bg-transparent text-[#ebedf2] font-medium capitalize">
                                Premium Trading Signals
                            </h2>
                        </div>
                        <div>
                            <a href="dashboard.php" class="flex justify-start items-center text-xs text-gray-400 hover:text-white">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11 17l-5-5m0 0l5-5m-5 5h12" />
                                </svg>
                                <span>back</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="w-full py-5">
            <div class="w-full flex justify-center">
                <div class="w-11/12 md:w-2/3 rounded-md bg-[#0e1726] text-[#d3d6df] p-2 md:p-4">
                    <!-- Display success/error messages -->
                    <?php if(!empty($error)): ?>
                        <div class="mb-4 p-4 bg-red-900 text-red-100 rounded-md">
                            <?php echo htmlspecialchars($error); ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php if(!empty($success)): ?>
                        <div class="mb-4 p-4 bg-green-900 text-green-100 rounded-md">
                            <?php echo htmlspecialchars($success); ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="w-full p-6 md:p-10 flex justify-center">
                        <div class="w-full flex space-x-2 rounded-lg bg-[#131d2c] text-[#d3d6df] p-2 md:p-4 text-xs md:text-sm">
                            <div class="text-orange-500">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M20.618 5.984A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016zM12 9v2m0 4h.01" />
                                </svg>
                            </div>
                            <div>
                                <b class="font-medium">Premium Signals Service: </b> 
                                Subscribe to our exclusive trading signals delivered daily to your WhatsApp. Our signals have a 99% accuracy rate and include:
                                <ul class="list-disc pl-5 mt-2">
                                    <li>Daily forex/crypto trading signals</li>
                                    <li>Entry and exit points</li>
                                    <li>Stop loss and take profit levels</li>
                                    <li>Market analysis</li>
                                </ul>
                                <p class="mt-2">Cost: <b>$<?php echo $signals_fee ?> per month</b></p>
                            </div>
                        </div>
                    </div>

                    <div class="p-2 md:p-4">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="_token" value="<?php echo bin2hex(random_bytes(16)); ?>">
                            
                            <div class="mb-4">
                                <label class="block text-sm font-medium mb-1">Wallet Address</label>
                                <div class="p-3 bg-[#131d2c] rounded-md text-sm break-all">
                                    <?php echo $crypto_addresses['USDT-TRC20']; ?>
                                </div>
                                <p class="text-xs text-gray-400 mt-1">Send exactly $<?php echo $signals_fee ?> to this address</p>
                            </div>

                            <div class="relative w-full mb-4">
                                <svg xmlns="http://www.w3.org/2000/svg" class="cred-hyip-theme1-input-icon h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                </svg>
                                <input type="text" name="whatsapp_number" required class="cred-hyip-theme1-text-input" placeholder="Your WhatsApp number with country code (e.g., +1234567890)">
                            </div>

                            <div class="relative w-full mb-4">
                                <svg xmlns="http://www.w3.org/2000/svg" class="cred-hyip-theme1-input-icon h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                                </svg>
                                <input type="text" name="transaction_hash" required class="cred-hyip-theme1-text-input" placeholder="Transaction hash of your payment">
                            </div>

                            <div class="mb-4">
                                <label class="block text-sm font-medium mb-1">Payment Proof (Screenshot)</label>
                                <input type="file" name="payment_proof" accept="image/*" required class="block w-full text-sm text-gray-400 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-[#1b2e4b] file:text-gray-400 hover:file:bg-gray-700">
                                <p class="text-xs text-gray-400 mt-1">Upload clear screenshot of your payment (Max 5MB, JPG/PNG/GIF)</p>
                            </div>

                            <div class="w-full my-5 px-5">
                                <button type="submit" name="subscribe" class="w-1/3 text-xs md:text-sm text-[#d1d5db] text-center px-5 py-2 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                                    Subscribe ($<?php echo $signals_fee ?>)
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
  

<?php include 'footer.php'; ?>