<?php
include 'header.php';

// Fetch staking plans from database
$stakingPlans = [];
$sql = "SELECT * FROM coin_staking_plans";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $stakingPlans[] = $row;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Validate required fields
        if (empty($_POST['coin_id'])) {
            throw new Exception("Coin selection is required");
        }
        
        if (empty($_POST['amount']) || $_POST['amount'] <= 0) {
            throw new Exception("Amount must be greater than 0");
        }

        // Get coin details
        $coinSql = "SELECT * FROM coin_staking_plans WHERE id = ?";
        $coinStmt = $conn->prepare($coinSql);
        if (!$coinStmt) throw new Exception("Prepare failed: " . $conn->error);
        
        $coinStmt->bind_param("i", $_POST['coin_id']);
        $coinStmt->execute();
        $coin = $coinStmt->get_result()->fetch_assoc();
        
        if (!$coin) throw new Exception("Invalid coin selected");

        // Validate amount
        $amount = floatval($_POST['amount']);
        if ($amount < $coin['min_stake']) throw new Exception("Amount below minimum of " . $coin['min_stake']);
        if ($amount > $coin['max_stake']) throw new Exception("Amount exceeds maximum of " . $coin['max_stake']);
        if ($balance < $amount) throw new Exception("Insufficient balance");

        // Start transaction
        $conn->begin_transaction();

        try {
            // 1. Deduct from user wallet
            $deductStmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            if (!$deductStmt) throw new Exception("Prepare failed: " . $conn->error);
            $deductStmt->bind_param("di", $amount, $user_id);
            $deductStmt->execute();
            if ($deductStmt->affected_rows === 0) throw new Exception("Failed to deduct from wallet");

            // 2. Create staking record
            $dailyReturn = ($amount * $coin['apr'] / 100) / 365;
            $stakingStmt = $conn->prepare("INSERT INTO user_stakings 
                (user_id, coin_id, amount, duration_days, apr, daily_return, start_date, end_date, status) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), DATE_ADD(NOW(), INTERVAL ? DAY), 'active')");
            
            if (!$stakingStmt) throw new Exception("Prepare failed: " . $conn->error);
            $stakingStmt->bind_param("iiddddi", $user_id, $coin['id'], $amount, $coin['duration_days'], 
                                   $coin['apr'], $dailyReturn, $coin['duration_days']);
            $stakingStmt->execute();
            

          
            $userName = $full_name;
            $endDate = date('Y-m-d', strtotime("+{$coin['duration_days']} days"));
           
            
            $subject = "Staking Confirmation - $sitename";
            $body = "
            <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/images/emaillogo.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;'>
                            Staking Confirmation
                        </h1>
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            Dear <b>$userName</b>, your staking has been successfully created.
                        </p>
                        
                        <div style='text-align: left; margin-bottom: 24px;'>
                            <h3 style='color: #1e293b;'>Staking Details:</h3>
                            <p><strong>Coin:</strong> {$coin['coin_name']}</p>
                            <p><strong>Amount Staked:</strong> " . number_format($amount, 2) . "</p>
                            <p><strong>APR:</strong> {$coin['apr']}%</p>
                            <p><strong>Duration:</strong> {$coin['duration_days']} days</p>
                            <p><strong>End Date:</strong> $endDate</p>
                            
                        </div>
                        
                        <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                            You will start earning rewards immediately. Rewards are calculated daily.
                        </p>
                        
                        <div style='margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: left;'>
                            <p style='color: #4b5563; margin-bottom: 8px;'>Thanks,</p>
                            <p style='color: #4b5563; font-weight: bold;'>Staking Team, $sitename</p>
                        </div>
                        <div style='margin-top: 32px; font-size: 12px; color: #6b7280; text-align: left;'>
                            <p style='margin-bottom: 4px;'>Please consider all emails from us as confidential.</p>
                        </div>
                    </div>
                </div>
            </div>";

            // Send email to user
            $sendUser = sendMail($email, $subject, $body);

            // Optionally send notification to admin
            $adminSubject = "New Staking Created - $userName";
            $adminBody = "
            <div style='font-family: Arial, sans-serif;'>
                <h2>New Staking Created</h2>
                <p><strong>User:</strong> $userName</p>
                <p><strong>Email:</strong> $email</p>
                <p><strong>Coin:</strong> {$coin['coin_name']}</p>
                <p><strong>Amount:</strong> " . number_format($amount, 2) . "</p>
                <p><strong>Duration:</strong> {$coin['duration_days']} days</p>
                <p><strong>APR:</strong> {$coin['apr']}%</p>
            </div>";

            // Assuming you have an admin email in your config
            if (!empty($admin_email)) {
                $sendAdmin = sendMail($admin_email, $adminSubject, $adminBody);
            }

            $conn->commit();

            echo "<script>
                alert('Staking created successfully!');
                window.location.href = 'coin-stakings.php';
            </script>";
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            throw new Exception("Staking failed: " . $e->getMessage());
        }

    } catch (Exception $e) {
        echo "<script>
            alert('Error: " . addslashes($e->getMessage()) . "');
            window.history.back();
        </script>";
        exit();
    }
}
?>

<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">
        
        <!-- Header 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">
                        <h2 class="text-[#ebedf2] font-medium capitalize">Coin Staking</h2>
                        <a href="dashboard.php" class="flex items-center text-xs text-gray-400 hover:text-white">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" 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>

        <!-- Staking Form (Hidden by default) -->
        <div class="staking-form hidden">
            <div class="w-full py-5">    
                <div class="w-full flex justify-center">
                    <div class="w-11/12 md:w-12/12 rounded-md bg-[#0e1726] text-[#d3d6df] p-2 md:p-4 box-shadow">
                        <div class="flex justify-between mb-2">
                            <h2 class="text-[#ebedf2] font-medium capitalize">New Staking</h2>
                            <a role="button" class="stake-button text-red-600" data-type="close">
                                <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                                </svg>
                            </a>
                        </div>
                        
                        <hr class="w-full border-b border-dotted border-gray-600 mb-4"> 
                        
                        <div class="p-2 md:p-4">
                            <form class="mt-2 p-2 md:p-4" action="" method="post">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                    <div>
                                        <label class="font-medium block">Coin:</label>
                                        <span id="coin" class="text-blue-400 text-sm">Bitcoin</span>
                                    </div>
                                    <div>
                                        <label class="font-medium block">Symbol:</label>
                                        <span id="symbol" class="text-blue-400 text-sm">BTC</span>
                                    </div>
                                    <div>
                                        <label class="font-medium block">Staking Period:</label>
                                        <span id="duration" class="text-blue-400 text-sm">30 Days</span>
                                    </div>
                                    <div>
                                        <label class="font-medium block">APR:</label>
                                        <span id="apr" class="text-blue-400 text-sm">10%</span>
                                    </div>
                                </div>
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                    <div>
                                        <label class="font-medium block">Minimum Stake:</label>
                                        <span id="min_stake" class="text-blue-400 text-sm">100</span>
                                    </div>
                                    <div>
                                        <label class="font-medium block">Maximum Stake:</label>
                                        <span id="max_stake" class="text-blue-400 text-sm">10000</span>
                                    </div>
                                </div>
                                
                                <div class="relative w-full mb-4">
                                    <span class="cred-hyip-theme1-input-icon h-8 w-8 font-semibold" id="amount_unit">USD</span>
                                    <input type="hidden" name="coin_id" id="coin_id">
                                    <input id="amount" name="amount" type="number" step='any' min="" max="" value="" required 
                                           class="cred-hyip-theme1-text-input" placeholder="Enter amount to stake">
                                </div>
                                
                                <button type="submit" class="w-full text-sm text-[#d1d5db] text-center px-5 py-3 bg-[#1b2e4b] hover:bg-gray-700 rounded-md">
                                    Stake Now
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Staking Plans Table -->
        <div class="py-5">
            <div class="w-full flex justify-center">
                <div class="w-11/12 rounded-sm bg-[#0e1726] p-1 md:p-4">
                    <table id="datatable-skeleton-table" class="text-[#bfc9d4] text-xs md:text-sm w-full">
                        <thead>
                            <tr>
                                <th>#</th>                        
                                <th>Icon</th>                        
                                <th>Type</th>
                                <th>Period</th>
                                <th>APR</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($stakingPlans as $index => $plan): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td>
                                    <img src="<?= htmlspecialchars($plan['icon_url']) ?>" 
                                         alt="<?= htmlspecialchars($plan['coin_name']) ?>" 
                                         width="40" class="rounded-full">
                                </td>
                                <td><?= htmlspecialchars($plan['coin_name']) ?> (<?= htmlspecialchars($plan['symbol']) ?>)</td>
                                <td><?= $plan['duration_days'] ?> days</td>
                                <td><?= $plan['apr'] ?>%</td>
                                <td>
                                    <button class="stake-button bg-green-500 hover:bg-green-600 text-white px-3 py-1 rounded text-sm"
                                        data-type="open" 
                                        data-coin_id="<?= $plan['id'] ?>"
                                        data-coin="<?= htmlspecialchars($plan['coin_name']) ?>"
                                        data-symbol="<?= htmlspecialchars($plan['symbol']) ?>"
                                        data-duration="<?= $plan['duration_days'] ?>"
                                        data-apr="<?= $plan['apr'] ?>"
                                        data-min_stake="<?= $plan['min_stake'] ?>"
                                        data-max_stake="<?= $plan['max_stake'] ?>">
                                        Stake Now
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

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

<script>
$(document).ready(function(){
    $(".skiptranslate").text("");
    
    // Staking form handling
    $('.stake-button').on('click', function(){
        var type = $(this).data('type');

        if (type == 'open') {
            var data = $(this).data();
            
            $('.staking-form').show('slow');
            
            // Update form fields
            $("#coin").text(data.coin);
            $("#coin_id").val(data.coin_id);
            $("#symbol").text(data.symbol);
            $("#duration").text(data.duration + " Days");
            $("#apr").text(data.apr + "%");
            $("#min_stake").text(data.min_stake);
            $("#max_stake").text(data.max_stake);
            $("#amount_unit").text(data.symbol);
            
            // Set input constraints
            $('#amount').attr({
                'min': data.min_stake,
                'max': data.max_stake
            }).val('');
        } else {
            $('.staking-form').hide('slow');
        }
    });
});
</script>

<style>
.staking-form {
    width: 40vw;
    z-index: 10000;
    top: 0;
    right: 0;
    position: fixed;
}

@media only screen and (max-width: 700px) {
    .staking-form {
        width: 90vw;
    }
}

.box-shadow {
    box-shadow: -7px 3px 3px -3px rgb(100 130 181 / 74%);
}
</style>