<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require_once __DIR__ . '/config.php';

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

$userId = $_SESSION['user_id'];
$msg = '';
$show_success_popup = false;
$success_qty = 0;
$success_amt = 0;

// ==========================================
// 🛠️ AUTO FIX: Add columns to withdrawals table
// ==========================================
$conn->query("CREATE TABLE IF NOT EXISTS withdrawals (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    method VARCHAR(50) NOT NULL,
    status ENUM('pending','approved','rejected') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$checkCols = $conn->query("SHOW COLUMNS FROM withdrawals LIKE 'account_title'");
if ($checkCols && $checkCols->num_rows == 0) {
    $conn->query("ALTER TABLE withdrawals ADD COLUMN account_title VARCHAR(100) DEFAULT NULL");
}
$checkCols2 = $conn->query("SHOW COLUMNS FROM withdrawals LIKE 'account_number'");
if ($checkCols2 && $checkCols2->num_rows == 0) {
    $conn->query("ALTER TABLE withdrawals ADD COLUMN account_number VARCHAR(100) DEFAULT NULL");
}
$checkCols3 = $conn->query("SHOW COLUMNS FROM withdrawals LIKE 'quantity'");
if ($checkCols3 && $checkCols3->num_rows == 0) {
    $conn->query("ALTER TABLE withdrawals ADD COLUMN quantity INT DEFAULT 0");
}
$checkCols4 = $conn->query("SHOW COLUMNS FROM withdrawals LIKE 'bank_name'");
if ($checkCols4 && $checkCols4->num_rows == 0) {
    $conn->query("ALTER TABLE withdrawals ADD COLUMN bank_name VARCHAR(100) DEFAULT NULL");
}
// ==========================================

// Fetch User Data
$stmtUser = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmtUser->bind_param("i", $userId);
$stmtUser->execute();
$user = $stmtUser->get_result()->fetch_assoc();

if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit;
}

$userEggs = (int)$user['total_eggs'];

// 🛑 NAYA CHECK: Kya user ke paas koi Active Hen (Approved Investment) hai? 🛑
$checkActivePlan = $conn->query("SELECT COUNT(*) as active_plans FROM investments WHERE user_id = $userId AND status = 'approved'");
$activePlansCount = $checkActivePlan->fetch_assoc()['active_plans'];
$hasActivePlan = ($activePlansCount > 0);

// Fetch Shops
$shops = [];
$res = $conn->query("SELECT * FROM egg_shop_prices ORDER BY egg_price ASC");
if ($res && $res->num_rows > 0) {
    while ($row = $res->fetch_assoc()) {
        $shops[] = $row;
    }
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sell_egg_submit'])) {
    
    // 🛑 SECURITY: Agar active plan nahi hai toh form submit na ho 🛑
    if (!$hasActivePlan) {
        $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> You need to buy a Hen (Active Plan) first to sell eggs!</div>";
    } else {
        $shop_id = (int)$_POST['shop_id'];
        $quantity = (int)$_POST['quantity'];
        
        $payment_method = $conn->real_escape_string(trim($_POST['payment_method']));
        $account_title = $conn->real_escape_string(trim($_POST['account_title']));
        $account_number = $conn->real_escape_string(trim($_POST['account_number']));
        $bank_name = isset($_POST['bank_name']) ? $conn->real_escape_string(trim($_POST['bank_name'])) : '';
        
        $selectedShop = null;
        foreach ($shops as $s) {
            if ($s['id'] == $shop_id) {
                $selectedShop = $s;
                break;
            }
        }

        if (!$selectedShop) {
            $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> Please select a valid shop!</div>";
        } elseif ($quantity <= 0) {
            $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> Quantity must be greater than 0!</div>";
        } elseif ($quantity < $selectedShop['min_eggs']) {
            $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> Minimum " . $selectedShop['min_eggs'] . " eggs required!</div>";
        } elseif ($quantity > $userEggs) {
            $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> You only have $userEggs eggs.</div>";
        } else {
            $pricePerUnit = $selectedShop['egg_price'];
            $totalAmount = $pricePerUnit * $quantity;

            // 1. Deduct Eggs from User
            $conn->query("UPDATE users SET total_eggs = total_eggs - $quantity WHERE id = $userId");

            // 2. Save Transaction
            $txType = 'Sell Egg';
            $txStatus = 'Completed';
            $conn->query("INSERT INTO transactions (user_id, type, quantity, amount, status) VALUES ($userId, '$txType', $quantity, $totalAmount, '$txStatus')");

            // 3. Create Withdrawal Request
            $conn->query("INSERT INTO withdrawals (user_id, amount, method, account_title, account_number, bank_name, quantity, status) VALUES ($userId, $totalAmount, '$payment_method', '$account_title', '$account_number', '$bank_name', '$quantity', 'pending')");

            // Setup for Popup
            $show_success_popup = true;
            $success_qty = $quantity;
            $success_amt = $totalAmount;
            
            // Refresh user eggs
            $userEggs = $userEggs - $quantity;
        }
    }
}

// Image Cache Bust
function getImgUrl($filename) {
    $path = __DIR__ . '/' . $filename;
    $ver = file_exists($path) ? filemtime($path) : time();
    return $filename . '?v=' . $ver;
}
$bgURL = getImgUrl('bg.png');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Sell Eggs - MUQADAS POULTRY</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        
        .fixed-bg {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background-color: #0f172a;
            background-image: linear-gradient(rgba(15, 23, 42, 0.7), rgba(15, 23, 42, 0.7)), url('<?php echo $bgURL; ?>');
            background-size: cover; background-position: center center; background-repeat: no-repeat; 
            z-index: -999; pointer-events: none;
        }

        body { color: #fff; display: flex; justify-content: center; min-height: 100vh; padding: 15px; }
        .container { width: 100%; max-width: 480px; display: flex; flex-direction: column; gap: 15px; }
        
        .header { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; }
        .back-btn { background: rgba(255,255,255,0.15); border:1px solid rgba(255,255,255,0.3); color:#fff; width:38px; height:38px; border-radius:50%; display:flex; align-items:center; justify-content:center; text-decoration:none; backdrop-filter:blur(4px); transition: 0.3s; }
        .brand-title { font-weight: 800; font-size: 1.1rem; color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.6); }
        
        .card-box { background: rgba(0, 0, 0, 0.6); border: 1px solid rgba(255, 255, 255, 0.15); border-radius: 20px; padding: 20px; backdrop-filter: blur(10px); box-shadow: 0 8px 32px rgba(0,0,0,0.5); margin-bottom: 15px; }
        .section-title { font-size: 1rem; color: #facc15; margin-bottom: 15px; display: flex; align-items: center; gap: 8px; font-weight: 700; }
        
        .available-eggs { background: rgba(250, 204, 21, 0.15); border: 1px dashed #eab308; padding: 15px; border-radius: 12px; text-align: center; margin-bottom: 20px; }
        .available-eggs p { font-size: 0.85rem; color: #cbd5e1; margin-bottom: 5px; }
        .available-eggs h2 { font-size: 1.8rem; color: #facc15; text-shadow: 0 0 10px rgba(250,204,21,0.4); }
        .available-eggs i { font-size: 1.5rem; color: #facc15; margin-right: 8px; vertical-align: middle; }

        .shop-grid { display: flex; flex-direction: column; gap: 12px; margin-bottom: 20px; }
        .shop-radio { display: none; }
        .shop-card-label { display: flex; justify-content: space-between; align-items: center; background: rgba(255, 255, 255, 0.05); border: 2px solid rgba(255, 255, 255, 0.1); padding: 15px; border-radius: 14px; cursor: pointer; transition: all 0.3s ease; }
        .shop-card-label:hover { background: rgba(255, 255, 255, 0.1); }
        .shop-info h4 { font-size: 1rem; color: #fff; margin-bottom: 4px; }
        .shop-info p { font-size: 0.75rem; color: #cbd5e1; }
        .shop-price { font-size: 1.1rem; font-weight: 800; color: #facc15; text-align: right; }
        .shop-price span { display: block; font-size: 0.65rem; color: #cbd5e1; font-weight: normal; margin-top: 2px;}
        .shop-radio:checked + .shop-card-label { border-color: #eab308; background: rgba(250, 204, 21, 0.15); box-shadow: 0 0 15px rgba(250, 204, 21, 0.2); }

        .qty-total-wrap { background: rgba(15, 23, 42, 0.8); border-radius: 14px; padding: 15px; margin-bottom: 20px; border: 1px solid rgba(250, 204, 21, 0.3); }
        .qty-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .qty-label { font-size: 0.9rem; color: #cbd5e1; font-weight: 600; }
        .qty-controls { display: flex; align-items: center; gap: 10px; background: rgba(0,0,0,0.5); border-radius: 8px; padding: 5px; }
        .qty-btn { width: 32px; height: 32px; border-radius: 6px; border: none; background: rgba(255,255,255,0.1); color: #fff; font-size: 1.2rem; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: 0.2s; }
        .qty-btn:hover { background: #eab308; color: #000; }
        .qty-input { width: 50px; text-align: center; background: transparent; border: none; color: #fff; font-size: 1.1rem; font-weight: bold; outline: none; }
        .total-row { display: flex; justify-content: space-between; align-items: center; border-top: 1px dashed rgba(255,255,255,0.2); padding-top: 15px; }
        .total-label { font-size: 0.9rem; color: #cbd5e1; font-weight: 600; }
        .total-amount { font-size: 1.4rem; font-weight: 800; color: #22c55e; text-shadow: 0 0 10px rgba(34,197,94,0.4); }

        .payment-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px; }
        .pay-radio { display: none; }
        .pay-card-label { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; background: rgba(255, 255, 255, 0.05); border: 2px solid rgba(255, 255, 255, 0.1); padding: 12px 10px; border-radius: 12px; cursor: pointer; transition: all 0.3s; text-align: center; }
        .pay-card-label i { font-size: 1.3rem; color: #cbd5e1; }
        .pay-card-label span { font-size: 0.75rem; font-weight: 600; color: #fff; }
        .pay-radio:checked + .pay-card-label { border-color: #eab308; background: rgba(250, 204, 21, 0.15); }
        .pay-radio:checked + .pay-card-label i { color: #facc15; }

        .acc-input-group { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; }
        .form-control { width: 100%; padding: 12px 15px; border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 10px; background: rgba(0, 0, 0, 0.4); font-size: 0.9rem; color: #fff; outline: none; }
        .form-control::placeholder { color: rgba(255,255,255,0.5); }
        .form-control:focus { border-color: #facc15; }

        .btn-submit { width: 100%; background: linear-gradient(135deg, #22c55e, #16a34a); color: #fff; border: none; padding: 15px; border-radius: 12px; font-weight: 800; font-size: 1rem; cursor: pointer; box-shadow: 0 4px 15px rgba(34, 197, 94, 0.4); transition: transform 0.2s; }
        .btn-submit:active { transform: scale(0.98); }
        .btn-submit:disabled { background: #555; cursor: not-allowed; opacity: 0.6; box-shadow: none; }

        .alert { padding: 12px; border-radius: 10px; margin-bottom: 15px; font-size: 0.85rem; text-align: center; display: flex; align-items: center; justify-content: center; gap: 8px; }
        .alert.danger { background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #fca5a5; }

        /* 🛑 KHUBSURAT SUCCESS POPUP 🛑 */
        .modal-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.8); backdrop-filter: blur(5px);
            display: flex; justify-content: center; align-items: center;
            z-index: 1000; opacity: 0; pointer-events: none; transition: 0.3s;
        }
        .modal-overlay.active { opacity: 1; pointer-events: auto; }
        
        .success-card {
            background: #fff; width: 90%; max-width: 340px;
            border-radius: 20px; padding: 30px 20px; text-align: center;
            transform: scale(0.8); transition: 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            box-shadow: 0 10px 40px rgba(0,0,0,0.5);
        }
        .modal-overlay.active .success-card { transform: scale(1); }

        .success-icon-wrap {
            width: 80px; height: 80px; background: #E8F5E9; border-radius: 50%;
            display: flex; justify-content: center; align-items: center;
            margin: 0 auto 20px auto; position: relative;
        }
        .success-icon-wrap i { font-size: 40px; color: #4CAF50; animation: popIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        
        .success-icon-wrap::before, .success-icon-wrap::after {
            content: ''; position: absolute; border-radius: 50%; border: 2px solid #4CAF50; opacity: 0;
        }
        .success-icon-wrap::before { width: 100%; height: 100%; animation: ripple 1s ease-out infinite; }
        .success-icon-wrap::after { width: 100%; height: 100%; animation: ripple 1s ease-out 0.5s infinite; }

        @keyframes ripple { 0% { transform: scale(1); opacity: 0.5; } 100% { transform: scale(1.5); opacity: 0; } }
        @keyframes popIn { 0% { transform: scale(0); } 80% { transform: scale(1.2); } 100% { transform: scale(1); } }

        .success-card h3 { font-size: 1.3rem; color: #333; margin-bottom: 10px; font-weight: 800; }
        .success-card p { font-size: 0.9rem; color: #666; margin-bottom: 25px; line-height: 1.5; }
        
        .btn-continue {
            background: #4CAF50; color: #fff; text-decoration: none;
            display: block; width: 100%; padding: 14px; border-radius: 12px;
            font-size: 1rem; font-weight: bold; border: none; cursor: pointer;
            box-shadow: 0 4px 10px rgba(76, 175, 80, 0.3); transition: 0.2s;
        }
        .btn-continue:hover { background: #43A047; transform: translateY(-2px); }
    </style>
</head>
<body>

<div class="fixed-bg"></div>

<div class="container">
    <div class="header">
        <a href="dashboard.php" class="back-btn"><i class="fa-solid fa-arrow-left"></i></a>
        <div class="brand-title">Sell Eggs</div>
        <div style="width:38px;"></div>
    </div>

    <?= $msg ?>

    <!-- 🛑 ACTIVE PLAN WARNING 🛑 -->
    <?php if (!$hasActivePlan): ?>
        <div class="alert danger">
            <i class="fa-solid fa-triangle-exclamation"></i> Aapke paas koi Active Hen nahi hai. Pehle Hen kharidein phir eggs sale karein.
        </div>
    <?php endif; ?>

    <form method="POST" id="sellForm">
        
        <div class="available-eggs">
            <p>Your Available Eggs</p>
            <h2><i class="fa-solid fa-egg"></i> <?= number_format($userEggs) ?></h2>
        </div>

        <div class="card-box">
            <div class="section-title"><i class="fa-solid fa-store"></i> Select Egg Shop</div>
            
            <div class="shop-grid">
                <?php if(empty($shops)): ?>
                    <p style="text-align:center; color:#cbd5e1; font-size:0.9rem;">No shops available right now.</p>
                <?php else: ?>
                    <?php foreach ($shops as $index => $s): ?>
                        <div>
                            <input type="radio" name="shop_id" id="shop_<?= $s['id'] ?>" value="<?= $s['id'] ?>" class="shop-radio" data-price="<?= $s['egg_price'] ?>" data-min="<?= $s['min_eggs'] ?>" required <?= $index === 0 ? 'checked' : '' ?>>
                            <label for="shop_<?= $s['id'] ?>" class="shop-card-label">
                                <div class="shop-info">
                                    <h4><?= htmlspecialchars($s['shop_name']) ?></h4>
                                    <p>Min Qty: <?= $s['min_eggs'] ?> Eggs</p>
                                </div>
                                <div class="shop-price">
                                    Rs <?= number_format($s['egg_price'], 2) ?>
                                    <span>Per Egg</span>
                                </div>
                            </label>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="qty-total-wrap">
                <div class="qty-row">
                    <span class="qty-label">Quantity to Sell</span>
                    <div class="qty-controls">
                        <button type="button" class="qty-btn" onclick="changeQty(-1)"><i class="fa-solid fa-minus"></i></button>
                        <input type="number" name="quantity" id="quantityInput" class="qty-input" value="1" min="1" readonly>
                        <button type="button" class="qty-btn" onclick="changeQty(1)"><i class="fa-solid fa-plus"></i></button>
                    </div>
                </div>
                <div class="total-row">
                    <span class="total-label">You Will Receive:</span>
                    <span class="total-amount" id="totalDisplay">Rs 0.00</span>
                </div>
            </div>
        </div>

        <div class="card-box">
            <div class="section-title"><i class="fa-solid fa-wallet"></i> Payout Method</div>
            
            <div class="payment-grid">
                <div>
                    <input type="radio" name="payment_method" id="pm_jazz" value="JazzCash" class="pay-radio" required checked>
                    <label for="pm_jazz" class="pay-card-label"><i class="fa-solid fa-mobile-screen"></i> <span>JazzCash</span></label>
                </div>
                <div>
                    <input type="radio" name="payment_method" id="pm_easy" value="EasyPaisa" class="pay-radio" required>
                    <label for="pm_easy" class="pay-card-label"><i class="fa-solid fa-mobile-screen-button"></i> <span>EasyPaisa</span></label>
                </div>
                <div>
                    <input type="radio" name="payment_method" id="pm_naya" value="NayaPay" class="pay-radio" required>
                    <label for="pm_naya" class="pay-card-label"><i class="fa-solid fa-n"></i> <span>NayaPay</span></label>
                </div>
                <div>
                    <input type="radio" name="payment_method" id="pm_sada" value="SadaPay" class="pay-radio" required>
                    <label for="pm_sada" class="pay-card-label"><i class="fa-solid fa-s"></i> <span>SadaPay</span></label>
                </div>
                <div style="grid-column: span 2;">
                    <input type="radio" name="payment_method" id="pm_bank" value="Bank Transfer" class="pay-radio" required>
                    <label for="pm_bank" class="pay-card-label" style="flex-direction: row; gap: 15px;">
                        <i class="fa-solid fa-building-columns"></i> <span>Bank Transfer</span>
                    </label>
                </div>
            </div>

            <!-- ACCOUNT DETAILS INPUTS -->
            <div class="acc-input-group">
                <input type="text" name="bank_name" id="bank_name_input" class="form-control" placeholder="Bank Name (e.g. Meezan Bank)" style="display: none;">
                
                <input type="text" name="account_title" class="form-control" placeholder="Account Title (e.g. Ali Khan)" required>
                <input type="text" name="account_number" class="form-control" placeholder="Account Number / IBAN" required>
            </div>

            <!-- 🛑 BUTTON DISABLED IF NO ACTIVE PLAN 🛑 -->
            <button type="submit" name="sell_egg_submit" class="btn-submit" <?= (!$hasActivePlan || $userEggs <= 0) ? 'disabled' : '' ?>>
                <i class="fa-solid fa-money-bill-transfer"></i> Sell Eggs Now
            </button>
            
            <?php if($userEggs <= 0): ?>
                <p style="text-align:center; color:#fca5a5; font-size:0.8rem; margin-top:10px;">You don't have enough eggs to sell.</p>
            <?php endif; ?>
        </div>

    </form>
</div>

<!-- 🛑 SUCCESS POPUP MODAL 🛑 -->
<?php if ($show_success_popup): ?>
<div class="modal-overlay active" id="successModal">
    <div class="success-card">
        <div class="success-icon-wrap">
            <i class="fa-solid fa-check"></i>
        </div>
        <h3>Order Submitted!</h3>
        <p>Aapne <b><?= $success_qty ?></b> eggs sale ke liye submit kiye hain.<br>Rs <b><?= number_format($success_amt, 2) ?></b> ki withdrawal request admin ko bhej di gayi hai.</p>
        <a href="dashboard.php" class="btn-continue">Continue</a>
    </div>
</div>
<?php endif; ?>

<script>
    let userEggs = <?= $userEggs ?>;

    function changeQty(amount) {
        let qtyInput = document.getElementById('quantityInput');
        let currentQty = parseInt(qtyInput.value) || 1;
        let newQty = currentQty + amount;
        
        if(newQty >= 1 && newQty <= userEggs) {
            qtyInput.value = newQty;
            calculateTotal();
        }
    }

    function calculateTotal() {
        let selectedShop = document.querySelector('.shop-radio:checked');
        let price = selectedShop ? parseFloat(selectedShop.getAttribute('data-price')) : 0;
        let qty = parseInt(document.getElementById('quantityInput').value) || 0;
        
        let total = price * qty;
        document.getElementById('totalDisplay').innerText = 'Rs ' + total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    document.querySelectorAll('.shop-radio').forEach(radio => {
        radio.addEventListener('change', calculateTotal);
    });

    document.getElementById('quantityInput').addEventListener('input', function() {
        let val = parseInt(this.value) || 0;
        if (val > userEggs) { this.value = userEggs; } 
        else if (val < 1) { this.value = 1; }
        calculateTotal();
    });

    // 🛑 BANK SELECT KARNE PAR 3RDA FIELD DIKHANA 🛑
    document.querySelectorAll('.pay-radio').forEach(radio => {
        radio.addEventListener('change', function() {
            let bankField = document.getElementById('bank_name_input');
            if(this.value === 'Bank Transfer') {
                bankField.style.display = 'block';
                bankField.setAttribute('required', 'required');
            } else {
                bankField.style.display = 'none';
                bankField.removeAttribute('required');
            }
        });
    });

    window.onload = function() {
        calculateTotal();
    };
</script>

</body>
</html>