<?php 
session_start();
include 'includes/header.php'; 
include 'includes/sidebar.php'; 
include 'includes/connect.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

$variety_id = isset($_GET['variety_id']) ? intval($_GET['variety_id']) : 0;

/* CATEGORY + VARIETY FETCH FOR BREADCRUMB */
$category_name = "";
$variety_name = "";

if($variety_id > 0){

    $q = mysqli_query($conn, "
        SELECT lc.label_name, c.category_name 
        FROM lifeline_configuration lc
        LEFT JOIN category c ON lc.category_id = c.id
        WHERE lc.id = '$variety_id' LIMIT 1
    ");

    if($q && mysqli_num_rows($q) > 0){
        $r = mysqli_fetch_assoc($q);
        $variety_name = $r['label_name'];
        $category_name = $r['category_name'];
    }
}

/* ================= QUERY (FIXED batch_id) ================= */
$query = "
SELECT 
    im.batch_id,
    im.variety_id,
    im.brand,
    SUM(im.tray_no) AS total_trays,
    COUNT(im.id) AS total_batches,
    AVG(DATEDIFF(CURDATE(), im.creation_date)) AS growing_days,

    SUM(
        CASE 
            WHEN (
                CASE 
                    WHEN LOWER(c.category_name) LIKE '%chilli%' 
                        THEN DATEDIFF(CURDATE(), im.creation_date) >= 35
                    ELSE DATEDIFF(CURDATE(), im.creation_date) >= 22
                END
            ) THEN 1 ELSE 0 
        END
    ) AS ready_batches

FROM inventory_management im
LEFT JOIN category c ON im.category_id = c.id

WHERE im.variety_id = '$variety_id'

GROUP BY 
    im.variety_id,
    im.batch_id

ORDER BY im.batch_id ASC
";

$result = mysqli_query($conn, $query);
?>

<style>

.main-content-wrap {
    background: #f4f6f9;
}

/* ===== BREADCRUMB ===== */
.breadcrumb {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    font-size: 15px;
    margin-bottom: 22px;
    padding: 14px 18px;
    background: linear-gradient(135deg, #ffffff, #f9fafb);
    border-radius: 12px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.06);
    font-family: "Segoe UI", Roboto, Arial, sans-serif;
}

.breadcrumb a {
    text-decoration: none;
    color: #ff7a18;
    font-weight: 600;
}

.breadcrumb a:hover {
    color: #e65c00;
    text-decoration: underline;
}

.breadcrumb span {
    color: #374151;
    font-weight: 500;
}

.breadcrumb .divider {
    color: #9ca3af;
    margin: 0 6px;
}

/* ===== GRID ===== */
.brand-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
    gap: 22px;
}

/* ===== CARD ===== */
.brand-card {
    background: linear-gradient(145deg, #ffffff, #f9fafb);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.06);
    transition: all 0.3s ease;
    position: relative;
    border: 1px solid rgba(0,0,0,0.04);
    overflow: hidden;
}

/* Hover effect only */
.brand-card:hover {
    transform: translateY(-8px) scale(1.03);
    box-shadow: 0 20px 45px rgba(0,0,0,0.15);
}

/* TOP BORDER */
.brand-card::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    height: 4px;
    width: 100%;
    border-radius: 16px 16px 0 0;
    background: linear-gradient(90deg, #ff7a18, #ffb347);
}

.brand-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 12px;
    color: #111827;
}

.brand-stat {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px dashed #e5e7eb;
    font-size: 13px;
}

.brand-stat:last-child {
    border-bottom: none;
}

.brand-stat span:first-child {
    color: #6b7280;
}

.badge {
    padding: 5px 12px;
    border-radius: 8px;
    font-size: 11px;
    font-weight: 600;
}

.badge-green { background: #dcfce7; color: #166534; }
.badge-blue { background: #dbeafe; color: #1e40af; }
.badge-orange { background: #fef3c7; color: #92400e; }

/* BUTTON */
.btn-order {
    margin-top: 15px;
    width: 100%;
    padding: 10px;
    background: linear-gradient(90deg, #ff7a18, #ffb347);
    border: none;
    border-radius: 10px;
    color: #fff;
    font-weight: 600;
    cursor: pointer;
    transition: 0.3s;
    position: relative;
    z-index: 2;
}

.btn-order:hover {
    transform: scale(1.03);
    box-shadow: 0 5px 15px rgba(255,122,24,0.4);
}

.no-data {
    text-align: center;
    padding: 30px;
    font-size: 14px;
    color: #6b7280;
}

</style>

<div class="main-content-inner">
<div class="main-content-wrap">

<div class="breadcrumb">
    <span>🏠</span>
    <a href="index.php">Home</a>
    <span class="divider">›</span>
    <a href="products.php">Products</a>
    <span class="divider">›</span>
    <a href="products.php"><?php echo htmlspecialchars($category_name ?: 'Category'); ?></a>
    <span class="divider">›</span>
    <a href="varieties.php?category_id="><?php echo htmlspecialchars($variety_name ?: 'Variety'); ?></a>
    <span class="divider">›</span>
    <span>Brands</span>
</div>

<div class="flex items-center justify-between mb-30">
    <h3 style="font-size:20px;font-weight:600;">
        🏷️ Brands - <?php echo htmlspecialchars($variety_name ?: ''); ?>
    </h3>
</div>

<div class="brand-grid">

<?php if(mysqli_num_rows($result) > 0){ ?>

<?php while($row = mysqli_fetch_assoc($result)){ ?>

<div class="brand-card">

    <div class="brand-title">
        <?php echo htmlspecialchars($row['brand']); ?>
    </div>
    
    <div class="brand-stat">
    <span>Batch ID</span>
    <span class="badge badge-blue"><?php echo $row['batch_id']; ?></span>
</div>

    <div class="brand-stat">
        <span>Available Trays</span>
        <span class="badge badge-green"><?php echo $row['total_trays']; ?></span>
    </div>

    <div class="brand-stat">
        <span>Total Batches</span>
        <span class="badge badge-blue"><?php echo $row['total_batches']; ?></span>
    </div>

    <div class="brand-stat">
        <span>Ready Batches</span>
        <span class="badge badge-orange"><?php echo $row['ready_batches']; ?></span>
    </div>

    <div class="brand-stat">
        <span>Growing Days</span>
        <span class="badge badge-blue"><?php echo round($row['growing_days']); ?> Days</span>
    </div>

    <button 
        type="button"
        class="btn-order"
        data-brand="<?php echo htmlspecialchars($row['brand'], ENT_QUOTES); ?>"
        data-variety="<?php echo $variety_id; ?>"
        data-batch="<?php echo $row['batch_id']; ?>"
        onclick="addToCart(this)"
    >
        🛒 Add to Cart
    </button>

</div>

<?php } ?>

<?php } else { ?>

<div class="no-data">No brands found</div>

<?php } ?>

</div>

</div>
</div>

<script>
function addToCart(btn){

    let brand = btn.dataset.brand;
    let variety_id = btn.dataset.variety;
    let batch_id = btn.dataset.batch;

    btn.innerHTML = "Adding...";
    btn.disabled = true;

    fetch("add_to_cart.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            brand: brand,
            variety_id: variety_id,
            batch_id: batch_id
        })
    })
    .then(res => res.json())
    .then(data => {

        if(data.success){
            btn.innerHTML = "✔ Added";
        } else {
            alert(data.message);
            btn.innerHTML = "🛒 Add to Cart";
            btn.disabled = false;
        }

    })
    .catch(() => {
        alert("Error occurred");
        btn.innerHTML = "🛒 Add to Cart";
        btn.disabled = false;
    });
}
</script>

<?php include 'includes/footer.php'; ?>