<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
date_default_timezone_set('Asia/Karachi');
session_start();
require_once __DIR__ . '/config.php';

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

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

// User Data
$stmtUser = $conn->prepare("SELECT username FROM users WHERE id = ?");
$stmtUser->bind_param("i", $userId);
$stmtUser->execute();
$userData = $stmtUser->get_result()->fetch_assoc();
$currentUsername = $userData['username'] ?? 'User';

// FETCH HEN PRICES FROM 'plans' TABLE
$henPrices = [];
$resHens = $conn->query("SELECT id, name as breed_name, price, duration as duration_days FROM plans");
if ($resHens && $resHens->num_rows > 0) {
    while ($row = $resHens->fetch_assoc()) {
        $henPrices[] = $row;
    }
}

// Fetch Deposit Methods
$dbMethods = [];
$resMethods = $conn->query("SELECT * FROM deposit_methods");
if ($resMethods && $resMethods->num_rows > 0) {
    while ($row = $resMethods->fetch_assoc()) {
        $dbMethods[] = $row;
    }
}

// Handle Order Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buy_hen_submit'])) {
    $hen_id = (int)$_POST['hen_id'];
    $quantity = (int)$_POST['quantity'];
    $payment_method = trim($_POST['payment_method']);
    
    $selectedHen = null;
    foreach ($henPrices as $h) {
        if ($h['id'] == $hen_id) {
            $selectedHen = $h;
            break;
        }
    }

    if (!$selectedHen || $quantity <= 0) {
        $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> Please select a valid hen!</div>";
    } else {
        $pricePerUnit = $selectedHen['price'];
        $totalAmount = $pricePerUnit * $quantity;
        $breedName = $selectedHen['breed_name'];

        $proofImage = '';
        if (isset($_FILES['proof_image']) && $_FILES['proof_image']['error'] === UPLOAD_ERR_OK) {
            $fileName = time() . '_' . basename($_FILES['proof_image']['name']);
            $uploadDir = 'uploads/';
            if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); }
            if (move_uploaded_file($_FILES['proof_image']['tmp_name'], $uploadDir . $fileName)) {
                $proofImage = $fileName;
            }
        }

        if (empty($proofImage)) {
            $msg = "<div class='alert danger'><i class='fa-solid fa-circle-exclamation'></i> Please upload payment proof!</div>";
        } else {
            
            // Insert Investment (Pending Status)
            $stmt = $conn->prepare("INSERT INTO investments (user_id, item_type, amount, status, item_name, price, quantity, total_amount, payment_method, proof_image) VALUES (?, 'Hen', ?, 'pending', ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("idssdiss", $userId, $totalAmount, $breedName, $pricePerUnit, $quantity, $totalAmount, $payment_method, $proofImage);
            
            if ($stmt->execute()) {
                // ❌ Yahan se Referral wala code hata diya gaya hai.
                // Ab eggs tabhi milenge jab Admin is order ko Approve karega.
                $show_success_popup = true;
            } else {
                $msg = "<div class='alert danger'>Error: " . $conn->error . "</div>";
            }
        }
    }
}

$bgURL = 'bg.png?v=' . (file_exists('bg.png') ? filemtime('bg.png') : time());
?>
<!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>Buy Hens - 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; z-index: -999; }
        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); }
        .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); margin-bottom: 15px; }
        .section-title { font-size: 1rem; color: #facc15; margin-bottom: 15px; display: flex; align-items: center; gap: 8px; font-weight: 700; }
        
        .hen-grid { display: flex; flex-direction: column; gap: 12px; margin-bottom: 20px; }
        .hen-radio { display: none; }
        .hen-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; }
        .hen-info h4 { font-size: 1rem; color: #fff; margin-bottom: 4px; }
        .hen-info p { font-size: 0.75rem; color: #cbd5e1; }
        .hen-price { font-size: 1.1rem; font-weight: 800; color: #facc15; text-align: right; }
        .hen-price span { display: block; font-size: 0.65rem; color: #cbd5e1; font-weight: normal; margin-top: 2px;}
        .hen-radio:checked + .hen-card-label { border-color: #eab308; background: rgba(250, 204, 21, 0.15); }

        .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; }
        .qty-input { width: 40px; text-align: center; background: transparent; border: none; color: #fff; font-size: 1.1rem; font-weight: bold; }
        .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: #facc15; }

        .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: 15px 10px; border-radius: 12px; cursor: pointer; }
        .pay-card-label i { font-size: 1.5rem; color: #cbd5e1; }
        .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; }

        .account-info { display: none; background: rgba(255,255,255,0.05); border-left: 4px solid #facc15; padding: 15px; border-radius: 8px; font-size: 0.85rem; margin-bottom: 20px; }
        .account-info.active { display: block; }
        .acc-row { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; padding-top: 8px; border-top: 1px dashed rgba(255,255,255,0.1); }
        .copy-wrap { display: flex; align-items: center; gap: 8px; background: rgba(0,0,0,0.4); padding: 5px 10px; border-radius: 6px; border: 1px solid rgba(255,255,255,0.1); width: 100%; justify-content: space-between; }
        .acc-num { color: #facc15; font-weight: 700; }
        .copy-btn { background: #eab308; color: #000; border: none; padding: 6px 10px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; cursor: pointer; }

        .upload-wrap { border: 2px dashed rgba(255,255,255,0.3); border-radius: 12px; padding: 20px; text-align: center; cursor: pointer; margin-bottom: 20px; background: rgba(0,0,0,0.3); position: relative; }
        .upload-wrap input[type="file"] { position: absolute; width: 100%; height: 100%; top: 0; left: 0; opacity: 0; cursor: pointer; }
        .upload-wrap i { font-size: 2rem; color: #cbd5e1; margin-bottom: 10px; }
        #fileNameDisplay { display: none; color: #22c55e; font-size: 0.85rem; margin-top: 5px; }
        .btn-submit { width: 100%; background: linear-gradient(135deg, #facc15, #eab308); color: #000; border: none; padding: 15px; border-radius: 12px; font-weight: 800; font-size: 1rem; cursor: pointer; }

        .alert { padding: 12px; border-radius: 10px; margin-bottom: 15px; text-align: center; }
        .alert.danger { background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #fca5a5; }

        .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; }
        .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; }
        .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; }
        .success-icon-wrap i { font-size: 40px; color: #4CAF50; }
        .success-card h3 { font-size: 1.3rem; color: #333; margin-bottom: 10px; }
        .success-card p { font-size: 0.9rem; color: #666; margin-bottom: 25px; }
        .btn-continue { background: #4CAF50; color: #fff; text-decoration: none; display: block; width: 100%; padding: 14px; border-radius: 12px; font-weight: bold; }
    </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">Buy Hens</div>
        <div style="width:38px;"></div>
    </div>

    <?= $msg ?>

    <form method="POST" enctype="multipart/form-data" id="buyForm">
        
        <div class="card-box">
            <div class="section-title"><i class="fa-solid fa-kiwi-bird"></i> Select Hen Breed</div>
            
            <div class="hen-grid">
                <?php if (empty($henPrices)): ?>
                    <p style="text-align: center; color: #fca5a5; font-size: 0.9rem;">No Hen prices set by Admin yet.</p>
                <?php else: ?>
                    <?php foreach ($henPrices as $index => $h): ?>
                        <div>
                            <input type="radio" name="hen_id" id="hen_<?= $h['id'] ?>" value="<?= $h['id'] ?>" class="hen-radio" data-price="<?= $h['price'] ?>" required <?= $index === 0 ? 'checked' : '' ?>>
                            <label for="hen_<?= $h['id'] ?>" class="hen-card-label">
                                <div class="hen-info">
                                    <h4><?= htmlspecialchars($h['breed_name']) ?></h4>
                                    <p>Duration: <?= $h['duration_days'] ?> Days</p>
                                </div>
                                <div class="hen-price">
                                    PKR <?= number_format($h['price']) ?>
                                    <span>Per Hen</span>
                                </div>
                            </label>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="qty-total-wrap">
                <div class="qty-row">
                    <span class="qty-label">Select Quantity</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">Total Payable:</span>
                    <span class="total-amount" id="totalDisplay">PKR 0.00</span>
                </div>
            </div>
        </div>

        <div class="card-box">
            <div class="section-title"><i class="fa-solid fa-wallet"></i> Payment Method</div>
            
            <?php if (empty($dbMethods)): ?>
                <p style="text-align: center; color: #fca5a5;">No payment methods set by Admin.</p>
            <?php else: ?>
                <div class="payment-grid">
                    <?php foreach ($dbMethods as $index => $m): 
                        $icon = 'fa-wallet';
                        if (strpos(strtolower($m['method_type']), 'jazz') !== false || strpos(strtolower($m['method_type']), 'easy') !== false) $icon = 'fa-mobile-screen';
                        if (strpos(strtolower($m['method_type']), 'bank') !== false) $icon = 'fa-building-columns';
                    ?>
                        <div>
                            <input type="radio" name="payment_method" id="pay_<?= $m['id'] ?>" value="<?= htmlspecialchars($m['method_type']) ?>" class="pay-radio" required <?= $index === 0 ? 'checked' : '' ?> onchange="updateAccountDetails(<?= $m['id'] ?>)">
                            <label for="pay_<?= $m['id'] ?>" class="pay-card-label">
                                <i class="fa-solid <?= $icon ?>"></i>
                                <span><?= htmlspecialchars($m['wallet_name']) ?></span>
                            </label>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <div class="account-info" id="accDetails">
                <?php foreach ($dbMethods as $index => $m): ?>
                    <div id="acc-box-<?= $m['id'] ?>" class="acc-box" style="display: <?= $index === 0 ? 'block' : 'none' ?>;">
                        <div style="font-weight:bold; margin-bottom:5px;"><i class="fa-solid fa-circle-info"></i> <?= htmlspecialchars($m['method_type']) ?> Details</div>
                        <div>Account Title: <span style="color:#fff;"><?= htmlspecialchars($m['account_title']) ?></span></div>
                        <div class="acc-row">
                            <div class="copy-wrap">
                                <span class="acc-num"><?= htmlspecialchars($m['account_number']) ?></span>
                                <button type="button" class="copy-btn" onclick="copyToClipboard('<?= htmlspecialchars($m['account_number']) ?>', this)"><i class="fa-solid fa-copy"></i> Copy</button>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="section-title" style="margin-top: 10px;"><i class="fa-solid fa-camera"></i> Upload Payment Proof</div>
            <div class="upload-wrap">
                <input type="file" name="proof_image" accept="image/*" required onchange="updateFileName(this)">
                <i class="fa-solid fa-cloud-arrow-up"></i>
                <p>Click to browse or drag & drop</p>
                <div id="fileNameDisplay"></div>
            </div>

            <button type="submit" name="buy_hen_submit" class="btn-submit"><i class="fa-solid fa-check-circle"></i> Submit Order</button>
        </div>
    </form>
</div>

<?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>Aapka order kamyabi se submit ho gaya hai.</p>
        <a href="dashboard.php" class="btn-continue">Continue</a>
    </div>
</div>
<?php endif; ?>

<script>
    function changeQty(amount) {
        let qtyInput = document.getElementById('quantityInput');
        let newQty = parseInt(qtyInput.value) + amount;
        if(newQty >= 1) { qtyInput.value = newQty; calculateTotal(); }
    }
    function calculateTotal() {
        let selectedHen = document.querySelector('.hen-radio:checked');
        let price = selectedHen ? parseFloat(selectedHen.getAttribute('data-price')) : 0;
        let qty = parseInt(document.getElementById('quantityInput').value) || 0;
        document.getElementById('totalDisplay').innerText = 'PKR ' + (price * qty).toLocaleString('en-US', {minimumFractionDigits: 2});
    }
    document.querySelectorAll('.hen-radio').forEach(radio => radio.addEventListener('change', calculateTotal));
    function updateFileName(input) {
        if (input.files && input.files.length > 0) {
            let display = document.getElementById('fileNameDisplay');
            display.style.display = 'block';
            display.innerText = 'Selected: ' + input.files[0].name;
        }
    }
    function updateAccountDetails(methodId) {
        document.getElementById('accDetails').classList.add('active');
        document.querySelectorAll('.acc-box').forEach(box => box.style.display = 'none');
        document.getElementById('acc-box-' + methodId).style.display = 'block';
    }
    function copyToClipboard(text, btnElement) {
        navigator.clipboard.writeText(text).then(() => {
            let original = btnElement.innerHTML;
            btnElement.innerHTML = '<i class="fa-solid fa-check"></i> Copied!';
            btnElement.style.background = '#22c55e';
            setTimeout(() => { btnElement.innerHTML = original; btnElement.style.background = '#eab308'; }, 2000);
        });
    }
    window.onload = function() {
        calculateTotal();
        let firstMethod = document.querySelector('.pay-radio:checked');
        if(firstMethod) {
            let id = firstMethod.id.replace('pay_', '');
            updateAccountDetails(id);
        }
    };
</script>
</body>
</html>