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

if (!isset($_SESSION['user']['id'])) {
    die('<div class="alert alert-danger">Not logged in</div>');
}

if (!isset($_GET['batch_id']) || !is_numeric($_GET['batch_id'])) {
    die('<div class="alert alert-danger">Invalid batch ID</div>');
}

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

try {
    // Get batch details with product info
    $sql = "SELECT 
            pb.*,
            p.name as product_name,
            p.sku,
            p.unit,
            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
            JOIN products p ON pb.product_id = p.id
            LEFT JOIN suppliers s ON pb.supplier_id = s.id
            WHERE pb.id = ? AND pb.shop_id = ?";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$batch_id, $shop_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$batch) {
        die('<div class="alert alert-danger">Batch not found</div>');
    }
    
    // Format dates
    $createdDate = date('Y-m-d', strtotime($batch['created_at']));
    $updatedDate = $batch['updated_at'] ? date('Y-m-d', strtotime($batch['updated_at'])) : 'N/A';
    $expiryDate = $batch['expiry_date'] ? date('Y-m-d', strtotime($batch['expiry_date'])) : 'N/A';
    
    // Check if expired
    $isExpired = $batch['expiry_date'] && strtotime($batch['expiry_date']) < time();
    $expiryClass = $isExpired ? 'text-danger' : 'text-success';
    $expiryBadge = $isExpired ? 'badge-danger' : 'badge-success';
    
    // Calculate days to expiry
    $daysToExpiry = '';
    if ($batch['expiry_date']) {
        $days = floor((strtotime($batch['expiry_date']) - time()) / (60 * 60 * 24));
        if ($days < 0) {
            $daysToExpiry = '<span class="text-danger">Expired ' . abs($days) . ' days ago</span>';
        } elseif ($days <= 30) {
            $daysToExpiry = '<span class="text-warning">' . $days . ' days remaining</span>';
        } else {
            $daysToExpiry = '<span class="text-success">' . $days . ' days remaining</span>';
        }
    }
    
    ?>
    <div class="row">
        <div class="col-md-6">
            <h6>Basic Information</h6>
            <table class="table table-sm table-bordered">
                <tr>
                    <th width="40%">Product:</th>
                    <td><?= htmlspecialchars($batch['product_name']) ?> (<?= htmlspecialchars($batch['sku']) ?>)</td>
                </tr>
                <tr>
                    <th>Batch Number:</th>
                    <td><span class="badge badge-primary"><?= htmlspecialchars($batch['batch_no']) ?></span></td>
                </tr>
                <tr>
                    <th>Supplier:</th>
                    <td><?= htmlspecialchars($batch['supplier_name'] ?? 'N/A') ?></td>
                </tr>
                <tr>
                    <th>Current Stock:</th>
                    <td><span class="badge badge-info"><?= $batch['current_stock'] ?></span></td>
                </tr>
            </table>
        </div>
        <div class="col-md-6">
            <h6>Pricing & Dates</h6>
            <table class="table table-sm table-bordered">
                <tr>
                    <th width="40%">Cost Price:</th>
                    <td class="text-danger">TSh <?= number_format($batch['cost_price'], 2) ?></td>
                </tr>
                <tr>
                    <th>Selling Price:</th>
                    <td class="text-success">TSh <?= number_format($batch['sell_price'], 2) ?></td>
                </tr>
                <tr>
                    <th>Expiry Date:</th>
                    <td>
                        <span class="<?= $expiryClass ?>">
                            <?= $expiryDate ?>
                            <?php if($isExpired): ?>
                            <span class="badge <?= $expiryBadge ?> ml-2">Expired</span>
                            <?php endif; ?>
                        </span>
                    </td>
                </tr>
                <tr>
                    <th>Created:</th>
                    <td><?= $createdDate ?></td>
                </tr>
                <tr>
                    <th>Last Updated:</th>
                    <td><?= $updatedDate ?></td>
                </tr>
            </table>
        </div>
    </div>
    
    <div class="row mt-3">
        <div class="col-12">
            <h6>Status</h6>
            <table class="table table-sm table-bordered">
                <tr>
                    <th width="20%">Active:</th>
                    <td>
                        <?php if($batch['is_active']): ?>
                        <span class="badge badge-success">Active</span>
                        <?php else: ?>
                        <span class="badge badge-secondary">Inactive</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th>Original Quantity:</th>
                    <td><?= $batch['qty'] ?></td>
                </tr>
                <tr>
                    <th>Days to Expiry:</th>
                    <td>
                        <?= $daysToExpiry ?: '<span class="text-muted">Not set</span>' ?>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    
    <div class="row mt-4">
        <div class="col-12 text-center">
            <button class="btn btn-info btn-sm" onclick="loadBatchHistory()">
                <i class="fas fa-history"></i> View Batch History
            </button>
            <button class="btn btn-secondary btn-sm ml-2" onclick="window.location.href='view_product.php?product_id=<?= $batch['product_id'] ?>'">
                <i class="fas fa-arrow-left"></i> Back to Product
            </button>
        </div>
    </div>
    <?php
    
} catch (Exception $e) {
    echo '<div class="alert alert-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>