<?php
// ajax/get_batches.php
session_start();
require_once '../../assets/db_connect.php';

if (!isset($_SESSION['user']['id'])) {
    die('Not logged in');
}

if (!isset($_GET['product_id']) || !is_numeric($_GET['product_id'])) {
    die('Invalid product ID');
}

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

try {
    // Get product info first
    $product_sql = "SELECT name, sku FROM products WHERE id = ? AND shop_id = ?";
    $product_stmt = $pdo->prepare($product_sql);
    $product_stmt->execute([$product_id, $shop_id]);
    $product = $product_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        die('Product not found');
    }
    
    // Get batches for this product
    $sql = "SELECT 
            pb.*,
            s.name as supplier_name,
            (SELECT COALESCE(SUM(
                CASE 
                    WHEN movement_type IN ('PURCHASE', 'RETURN') THEN change_qty
                    WHEN movement_type IN ('SALE', 'ADJUSTMENT') THEN -change_qty
                    ELSE 0
                END
            ), 0) FROM inventory_movements WHERE batch_id = pb.id) as current_stock
            FROM product_batches pb
            LEFT JOIN suppliers s ON pb.supplier_id = s.id
            WHERE pb.product_id = ? AND pb.shop_id = ?
            ORDER BY pb.expiry_date ASC, pb.batch_no ASC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$product_id, $shop_id]);
    $batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    ?>
    <div class="container-fluid">
        <div class="row mb-4">
            <div class="col-md-12">
                <h5 class="text-primary">
                    <i class="fas fa-boxes"></i> <?= htmlspecialchars($product['name']) ?> - All Batches
                    <small class="text-muted">(SKU: <?= htmlspecialchars($product['sku']) ?>)</small>
                </h5>
                <p class="text-muted mb-0">Manage all batches for this product</p>
            </div>
        </div>
        
        <?php if (empty($batches)): ?>
        <div class="alert alert-info text-center py-4">
            <i class="fas fa-box-open fa-3x mb-3 text-info"></i>
            <h5>No batches found</h5>
            <p class="mb-3">This product has no active batches.</p>
            <button class="btn btn-success add-new-batch-from-list-btn"
                    data-product-id="<?= $product_id ?>"
                    data-product-name="<?= htmlspecialchars($product['name']) ?>"
                    data-product-sku="<?= htmlspecialchars($product['sku']) ?>">
                <i class="fas fa-plus"></i> Add First Batch
            </button>
        </div>
        <?php else: ?>
        <div class="row mb-3">
            <div class="col-md-3">
                <div class="card bg-light">
                    <div class="card-body p-3 text-center">
                        <h6 class="card-title mb-1">Total Batches</h6>
                        <h3 class="mb-0"><?= count($batches) ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body p-3 text-center">
                        <h6 class="card-title mb-1">Total Stock</h6>
                        <h3 class="mb-0"><?= array_sum(array_column($batches, 'current_stock')) ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <?php 
                $expiredBatches = array_filter($batches, function($batch) {
                    return $batch['expiry_date'] && strtotime($batch['expiry_date']) < time();
                });
                $expiredCount = count($expiredBatches);
                ?>
                <div class="card <?= $expiredCount > 0 ? 'bg-danger text-white' : 'bg-success text-white' ?>">
                    <div class="card-body p-3 text-center">
                        <h6 class="card-title mb-1">Expired Batches</h6>
                        <h3 class="mb-0"><?= $expiredCount ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning">
                    <div class="card-body p-3 text-center">
                        <h6 class="card-title mb-1">Actions</h6>
                       <!-- <button class="btn btn-sm btn-success add-new-batch-from-list-btn"
                                data-product-id="<?= $product_id ?>"
                                data-product-name="<?= htmlspecialchars($product['name']) ?>"
                                data-product-sku="<?= htmlspecialchars($product['sku']) ?>">
                            <i class="fas fa-plus"></i> Add Batch
                        </button> -->
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0">
                        <thead class="thead-light">
                            <tr>
                                <th>Batch No</th>
                                <th>Supplier</th>
                                <th class="text-center">Current Stock</th>
                                <th class="text-right">Cost Price</th>
                                <th class="text-right">Selling Price</th>
                                <th class="text-center">Expiry Date</th>
                                <th class="text-center">Status</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($batches as $batch): 
                                // Check if expired
                                $isExpired = $batch['expiry_date'] && strtotime($batch['expiry_date']) < time();
                                $expiryClass = $isExpired ? 'text-danger' : '';
                                $expiryBadge = $isExpired ? 'badge-danger' : 'badge-success';
                                
                                // Stock status
                                $stock = $batch['current_stock'];
                                $stockClass = $stock <= 0 ? 'badge-danger' : ($stock <= 20 ? 'badge-warning' : 'badge-success');
                                
                                // Active status
                                $activeClass = $batch['is_active'] ? 'badge-success' : 'badge-secondary';
                                $activeText = $batch['is_active'] ? 'Active' : 'Inactive';
                            ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($batch['batch_no']) ?></strong></td>
                                <td><?= htmlspecialchars($batch['supplier_name'] ?? 'N/A') ?></td>
                                <td class="text-center">
                                    <span class="badge <?= $stockClass ?>"><?= $stock ?></span>
                                </td>
                                <td class="text-right">TSh <?= number_format($batch['cost_price'], 2) ?></td>
                                <td class="text-right">TSh <?= number_format($batch['sell_price'], 2) ?></td>
                                <td class="text-center <?= $expiryClass ?>">
                                    <?= $batch['expiry_date'] ? date('Y-m-d', strtotime($batch['expiry_date'])) : 'N/A' ?>
                                    <?php if($isExpired): ?>
                                    <br><small class="badge badge-danger">Expired</small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center">
                                    <span class="badge <?= $activeClass ?>"><?= $activeText ?></span>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group btn-group-sm" role="group">
                                        <!--<button class="btn btn-info view-batch-details-btn" 
                                                data-batch-id="<?= $batch['id'] ?>"
                                                title="View Batch Details">
                                            <i class="fas fa-eye"></i>
                                        </button> -->
                                        <!--<button class="btn btn-warning view-batch-history-btn" 
                                                data-batch-id="<?= $batch['id'] ?>"
                                                title="View Batch History">
                                            <i class="fas fa-history"></i>
                                        </button> -->
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="mt-4 text-center">
            <!--<button class="btn btn-primary btn-sm add-new-batch-from-list-btn"
                    data-product-id="<?= $product_id ?>"
                    data-product-name="<?= htmlspecialchars($product['name']) ?>"
                    data-product-sku="<?= htmlspecialchars($product['sku']) ?>">
                <i class="fas fa-plus"></i> Add New Batch
            </button> -->
            <button class="btn btn-secondary btn-sm" onclick="$('#batchModal').modal('hide');">
                <i class="fas fa-times"></i> Close
            </button>
        </div>
    </div>
    
    <script>
    // This script will be executed when the content loads
    $(document).ready(function() {
        console.log("Batch list loaded for product ID: <?= $product_id ?>");
    });
    </script>
    <?php
    
} catch (Exception $e) {
    echo '<div class="alert alert-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>