<?php
// modules/sales/ajax/get_product_details.php
session_start();
require_once '../../assets/db_connect.php';

if (!isset($_SESSION['user']['id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

$product_id = $_GET['product_id'] ?? 0;
$product_id = intval($product_id);
$shop_id = $_GET['shop_id'] ?? $_SESSION['user']['shop_id'];

// Get product details - Use product selling_price
$sql = "SELECT 
            p.*,
            COALESCE(SUM(pb.qty), 0) as current_stock
        FROM products p
        LEFT JOIN product_batches pb ON p.id = pb.product_id
        WHERE p.id = ? AND p.shop_id = ?
        GROUP BY p.id, p.sku, p.name, p.generic_name, p.unit, p.category, 
                 p.vat_percent, p.selling_price, p.buying_price, p.created_at, p.shop_id, p.is_active";

$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id, $shop_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo '<div class="alert alert-danger">Product not found</div>';
    exit();
}

// Get available batches for stock tracking (ONLY batches with positive stock)
$batches_sql = "SELECT 
                    pb.id, 
                    pb.batch_no, 
                    pb.sell_price as batch_price,
                    pb.expiry_date,
                    DATEDIFF(pb.expiry_date, CURDATE()) as days_left,
                    pb.qty as current_qty
                FROM product_batches pb
                WHERE pb.product_id = ? 
                AND pb.shop_id = ?
                AND pb.is_active = 1
                AND pb.qty > 0
                ORDER BY pb.expiry_date ASC";
                
$batches_stmt = $pdo->prepare($batches_sql);
$batches_stmt->execute([$product_id, $shop_id]);
$batches = $batches_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get default batch for auto-selection (FIFO - only from batches with stock)
$default_batch_sql = "SELECT 
                        pb.id,
                        pb.batch_no
                      FROM product_batches pb
                      WHERE pb.product_id = ? 
                      AND pb.shop_id = ?
                      AND pb.is_active = 1
                      AND pb.qty > 0
                      ORDER BY pb.expiry_date ASC 
                      LIMIT 1";
                      
$default_batch_stmt = $pdo->prepare($default_batch_sql);
$default_batch_stmt->execute([$product_id, $shop_id]);
$default_batch = $default_batch_stmt->fetch(PDO::FETCH_ASSOC);

// Use product's selling price (NOT batch price)
$selling_price = $product['selling_price'];
?>

<form id="productSaleForm">
    <input type="hidden" name="product_id" value="<?= $product_id ?>">
    <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
    
    <!-- Product Info -->
    <div class="alert alert-info mb-3">
        <div class="row">
            <div class="col-md-4">
                <strong>Product:</strong> <?= htmlspecialchars($product['name']) ?>
            </div>
            <div class="col-md-4">
                <strong>Available Stock:</strong> 
                <span class="badge <?= $product['current_stock'] <= 10 ? 'badge-warning' : 'badge-success' ?>">
                    <?= $product['current_stock'] ?> <?= $product['unit'] ?>
                </span>
            </div>
            <div class="col-md-4">
                <strong>Selling Price:</strong> 
                <span class="text-success fw-bold">
                    TZS <?= number_format($selling_price, 2) ?>
                </span>
            </div>
        </div>
        <?php if ($product['generic_name']): ?>
        <div class="mt-2">
            <strong>Generic:</strong> <?= htmlspecialchars($product['generic_name']) ?>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Sale Details -->
    <div class="row mb-3">
        <div class="col-md-6">
            <div class="form-group">
                <label>Quantity *</label>
                <input type="number" name="qty" class="form-control" min="1" 
                       max="<?= $product['current_stock'] ?>" value="1" required>
                <small class="text-muted">Max: <?= $product['current_stock'] ?> available</small>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label>Unit Price *</label>
                <input type="number" name="unit_price" class="form-control" step="0.01" min="0.01" 
                       value="<?= $selling_price ?>" required readonly>
                <small class="text-muted">Fixed product selling price</small>
            </div>
        </div>
    </div>
    
    <!-- Batch Selection -->
    <div class="mb-3">
        <label>Batch Selection (For Stock Tracking)</label>
        <select name="batch_id" class="form-control">
            <option value="">Auto-select (FIFO - First Expiry)</option>
            <?php foreach($batches as $batch): ?>
            <option value="<?= $batch['id'] ?>" 
                    data-qty="<?= $batch['current_qty'] ?>"
                    <?= $default_batch && $default_batch['id'] == $batch['id'] ? 'selected' : '' ?>>
                <?= $batch['batch_no'] ?> 
                (<?= $batch['current_qty'] ?> left, 
                Exp: <?= date('M d, Y', strtotime($batch['expiry_date'])) ?>)
            </option>
            <?php endforeach; ?>
        </select>
        <small class="text-muted">For stock tracking only - price remains fixed</small>
    </div>
    
    <!-- Batch Information -->
    <?php if(!empty($batches)): ?>
    <div class="alert alert-secondary mb-3">
        <h6><i class="fas fa-boxes"></i> Available Batches:</h6>
        <div class="row">
            <?php foreach($batches as $batch): ?>
            <div class="col-md-4 mb-2">
                <div class="card <?= $default_batch && $default_batch['id'] == $batch['id'] ? 'border-primary' : 'border-light' ?>">
                    <div class="card-body p-2">
                        <small>
                            <strong><?= $batch['batch_no'] ?></strong>
                            <?php if($default_batch && $default_batch['id'] == $batch['id']): ?>
                            <span class="badge badge-primary float-end">Default</span>
                            <?php endif; ?>
                            <br>
                            Stock: <?= $batch['current_qty'] ?><br>
                            Expiry: <?= $batch['days_left'] ?> days left
                        </small>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Calculated Total -->
    <div class="alert alert-success mb-3">
        <div class="row">
            <div class="col-md-6">
                <strong>Total:</strong> TZS <span id="productTotal"><?= number_format($selling_price, 2) ?></span>
            </div>
            <div class="col-md-6 text-end">
                <button type="button" class="btn btn-primary" onclick="addSelectedToCart()">
                    <i class="fas fa-cart-plus"></i> Add to Cart
                </button>
            </div>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    // Calculate total
    function calculateTotal() {
        const qty = parseInt($('input[name="qty"]').val()) || 0;
        const price = parseFloat($('input[name="unit_price"]').val()) || 0;
        const total = qty * price;
        $('#productTotal').text(total.toFixed(2));
        return { qty, price, total };
    }
    
    // Update batch quantity restrictions when batch is selected
    $('select[name="batch_id"]').change(function() {
        const selectedOption = $(this).find('option:selected');
        const batchQty = selectedOption.data('qty');
        
        if (batchQty) {
            const maxQty = Math.min(batchQty, <?= $product['current_stock'] ?>);
            $('input[name="qty"]').attr('max', maxQty);
            $('input[name="qty"]').next('small').text('Max: ' + maxQty + ' available (from selected batch)');
        } else {
            $('input[name="qty"]').attr('max', <?= $product['current_stock'] ?>);
            $('input[name="qty"]').next('small').text('Max: <?= $product['current_stock'] ?> available (total stock)');
        }
    });
    
    // Update total when quantity changes
    $('input[name="qty"]').on('input', calculateTotal);
    
    // Initialize
    calculateTotal();
});

function addSelectedToCart() {
    const form = document.getElementById('productSaleForm');
    const formData = new FormData(form);
    
    const productId = formData.get('product_id');
    const batchId = formData.get('batch_id');
    const qty = parseInt(formData.get('qty'));
    const price = parseFloat(formData.get('unit_price'));
    
    // Get product name
    const productName = '<?= addslashes($product['name']) ?>';
    
    // If no batch selected, use default
    let selectedBatchId = batchId;
    if (!selectedBatchId) {
        selectedBatchId = <?= $default_batch ? $default_batch['id'] : 'null' ?>;
    }
    
    // Get max quantity for selected batch
    let maxQty = <?= $product['current_stock'] ?>;
    if (batchId) {
        const selectedOption = $('select[name="batch_id"] option:selected');
        maxQty = selectedOption.data('qty') || maxQty;
    }
    
    // Call addToCart function from parent
    if (window.parent.addToCart) {
        window.parent.addToCart(productId, selectedBatchId, productName, price, qty, maxQty);
    } else {
        // Fallback if called directly
        addToCart(productId, selectedBatchId, productName, price, qty, maxQty);
    }
}
</script>