<?php
require_once 'includes/db.php';

// Fetch Statistics
$company_id = $_SESSION['company_id'];
$total_buyers = fetch("SELECT COUNT(*) as count FROM buyers WHERE company_id = ?", [$company_id])['count'];
$products_list = fetchAll("SELECT p.*, b.name as buyer_name FROM products p LEFT JOIN buyers b ON p.buyer_id = b.id WHERE p.company_id = ?", [$company_id]);

foreach ($products_list as &$p) {
    $p['materials'] = fetchAll("SELECT es.*, i.name, i.unit, i.sku FROM inventory_item_product es JOIN inventory_items i ON es.inventory_item_id = i.id WHERE es.product_id = ?", [$p['id']]);
}

$total_products = count($products_list);
$total_employees = fetch("SELECT COUNT(*) as count FROM employees WHERE company_id = ?", [$company_id])['count'];

// Helper to fetch full line data
function getFullLineData($lines) {
    foreach ($lines as &$line) {
        // Products
        $line['products'] = fetchAll("SELECT p.id, p.name, lp.quantity FROM production_line_products lp JOIN products p ON lp.product_id = p.id WHERE lp.production_line_id = ?", [$line['id']]);
        
        // Stages
        $line_stages = fetchAll("
            SELECT ls.*, ws.name as stage_name, ws.color_code 
            FROM line_stages ls 
            JOIN workflow_stages ws ON ls.workflow_stage_id = ws.id 
            WHERE ls.production_line_id = ? 
            ORDER BY ls.sort_order ASC
        ", [$line['id']]);
        
        foreach ($line_stages as &$ls) {
            // Staff
            $ls['staff'] = fetchAll("SELECT e.name, e.profile_picture, r.name as role_name FROM line_stage_staff lss JOIN employees e ON lss.employee_id = e.id LEFT JOIN roles r ON e.role_id = r.id WHERE lss.line_stage_id = ?", [$ls['id']]);
            
            // Machinery
            $ls['machinery'] = fetchAll("SELECT m.name FROM line_stage_machinery lsm JOIN machinery m ON lsm.machinery_id = m.id WHERE lsm.line_stage_id = ?", [$ls['id']]);
            
            // Hours
            $time_data = fetch("
                SELECT SUM(tl.hours_spent) as total_hours 
                FROM tasks t 
                JOIN task_time_logs tl ON t.id = tl.task_id 
                WHERE t.line_stage_id = ?
            ", [$ls['id']]);
            $ls['total_hours'] = $time_data['total_hours'] ?? 0;

            // Employee Time Logs with Attachments
            $timelogs = fetchAll("
                SELECT tl.*, e.name as employee_name, ts.name as status_name 
                FROM task_time_logs tl 
                JOIN tasks t ON tl.task_id = t.id 
                JOIN employees e ON tl.user_id = e.user_id 
                JOIN task_statuses ts ON tl.task_status_id = ts.id 
                WHERE t.line_stage_id = ? 
                ORDER BY tl.created_at DESC
            ", [$ls['id']]);

            foreach ($timelogs as &$log) {
                $log['attachments'] = fetchAll("SELECT * FROM task_log_attachments WHERE log_id = ?", [$log['id']]);
            }
            $ls['timelogs'] = $timelogs;

            // Manager Updates with Attachments
            $updates = fetchAll("
                SELECT u.*, e.name as manager_name 
                FROM line_stage_updates u 
                JOIN employees e ON u.user_id = e.user_id 
                WHERE u.line_stage_id = ? 
                ORDER BY u.created_at DESC
            ", [$ls['id']]);

            foreach ($updates as &$upd) {
                $upd['attachments'] = fetchAll("SELECT * FROM line_stage_update_attachments WHERE update_id = ?", [$upd['id']]);
            }
            $ls['updates'] = $updates;
        }
        $line['full_stages'] = $line_stages;
    }
    return $lines;
}

$active_lines = getFullLineData(fetchAll("SELECT * FROM production_lines WHERE company_id = ? AND status = 'Active'", [$company_id]));
$completed_lines = getFullLineData(fetchAll("SELECT * FROM production_lines WHERE company_id = ? AND status = 'Completed'", [$company_id]));
$blocked_lines = getFullLineData(fetchAll("SELECT * FROM production_lines WHERE company_id = ? AND status = 'Blocked'", [$company_id]));

$low_stock_items = fetchAll("SELECT * FROM inventory_items WHERE company_id = ? AND stock <= min_level", [$company_id]);
$recent_logs = fetchAll("SELECT * FROM audit_logs WHERE company_id = ? ORDER BY created_at DESC LIMIT 5", [$company_id]);

// Fetch My Tasks (for logged in employee)
$user_id = $_SESSION['user_id'] ?? 0;
$employee = fetch("SELECT id FROM employees WHERE user_id = ?", [$user_id]);
$my_tasks = [];
if ($employee) {
    $my_tasks = fetchAll("SELECT * FROM tasks WHERE employee_id = ? AND status = 'Pending' ORDER BY due_date ASC", [$employee['id']]);
}

?>

<?php if (!empty($my_tasks)): ?>
<div style="margin-bottom: 2rem;">
    <h2 style="font-size: 1.25rem; font-weight: 700; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
        <i class="fas fa-tasks-alt" style="color: var(--primary);"></i> My Assigned Tasks
    </h2>
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1rem;">
        <?php foreach ($my_tasks as $task): ?>
        <div class="card" style="border-left: 4px solid var(--primary); padding: 1.25rem;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.75rem;">
                <h3 style="font-size: 1rem; font-weight: 700; color: var(--text-main);"><?php echo $task['title']; ?></h3>
                <span style="font-size: 0.7rem; background: rgba(99, 102, 241, 0.1); color: var(--primary); padding: 0.2rem 0.6rem; border-radius: 12px; font-weight: 700;"><?php echo $task['status']; ?></span>
            </div>
            <p style="font-size: 0.875rem; color: var(--text-muted); margin-bottom: 1rem; line-height: 1.5;">
                <?php echo $task['description']; ?>
            </p>
            <div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--border); pt: 0.75rem; margin-top: 0.75rem; padding-top: 0.75rem;">
                <span style="font-size: 0.75rem; color: var(--text-muted);"><i class="far fa-calendar-check" style="margin-right: 0.25rem;"></i> Due: <?php echo date('M d, Y', strtotime($task['due_date'])); ?></span>
                <button class="btn" style="padding: 0.3rem 0.8rem; font-size: 0.75rem; background: var(--bg-dark); color: var(--success);" onclick="completeTask(<?php echo $task['id']; ?>)">
                    <i class="fas fa-check"></i> Done
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<script>
async function completeTask(id) {
    if (!confirm('Mark this task as completed?')) return;
    const result = await apiCall('tasks', { action: 'update-status', id: id, status: 'Completed' });
    if (result.success) {
        notify(result.message);
        location.reload();
    } else {
        notify(result.message, 'error');
    }
}
</script>
<?php endif; ?>

<?php if (hasRole(['owner', 'admin', 'manager'])): ?>
<div class="stats-grid">
    <!-- Active Lines KPI -->
    <div class="card stat-card kpi-card" onclick="showKpiDetails('active-lines', this)" style="cursor: pointer; transition: transform 0.2s;">
        <div class="stat-header">
            <div class="stat-icon" style="background: rgba(14, 165, 233, 0.1); color: var(--accent);">
                <i class="fas fa-industry"></i>
            </div>
        </div>
        <div class="stat-value"><?php echo count($active_lines); ?></div>
        <div class="stat-label">Active Lines</div>
    </div>

    <!-- Completed Lines KPI -->
    <div class="card stat-card kpi-card" onclick="showKpiDetails('completed-lines', this)" style="cursor: pointer; transition: transform 0.2s;">
        <div class="stat-header">
            <div class="stat-icon" style="background: rgba(16, 185, 129, 0.1); color: var(--success);">
                <i class="fas fa-check-double"></i>
            </div>
        </div>
        <div class="stat-value"><?php echo count($completed_lines); ?></div>
        <div class="stat-label">Completed Lines</div>
    </div>

    <!-- Blocked Lines KPI -->
    <div class="card stat-card kpi-card" onclick="showKpiDetails('blocked-lines', this)" style="cursor: pointer; transition: transform 0.2s;">
        <div class="stat-header">
            <div class="stat-icon" style="background: rgba(239, 68, 68, 0.1); color: var(--danger);">
                <i class="fas fa-ban"></i>
            </div>
            <?php if (count($blocked_lines) > 0): ?>
                <span style="background: var(--danger); color: white; padding: 0.2rem 0.5rem; border-radius: 50px; font-size: 0.65rem; font-weight: 800;"><?php echo count($blocked_lines); ?> BLOCKED</span>
            <?php endif; ?>
        </div>
        <div class="stat-value"><?php echo count($blocked_lines); ?></div>
        <div class="stat-label">Blocked Lines</div>
    </div>

    <!-- Low Stock KPI -->
    <div class="card stat-card kpi-card" onclick="showKpiDetails('low-stock', this)" style="cursor: pointer; transition: transform 0.2s;">
        <div class="stat-header">
            <div class="stat-icon" style="background: rgba(239, 68, 68, 0.1); color: var(--danger);">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <?php if (count($low_stock_items) > 0): ?>
                <span style="background: var(--danger); color: white; padding: 0.2rem 0.5rem; border-radius: 50px; font-size: 0.65rem; font-weight: 800;"><?php echo count($low_stock_items); ?> ALERT</span>
            <?php endif; ?>
        </div>
        <div class="stat-value"><?php echo count($low_stock_items); ?></div>
        <div class="stat-label">Low Stock Alerts</div>
    </div>
</div>

<!-- Dynamic KPI Details Section -->
<div id="kpi-details-container" style="display: none; margin-bottom: 2rem; animation: slideDown 0.3s ease-out;">
    <div style="display: flex; justify-content: space-between; align-items: center; padding: 1.5rem 0; border-bottom: 1px solid var(--border); margin-bottom: 1.5rem;">
        <h2 id="kpi-detail-title" style="font-size: 1.5rem; font-weight: 800; color: var(--text-main); display: flex; align-items: center; gap: 0.75rem;">
            <!-- Title injected by JS -->
        </h2>
    </div>
    <div id="kpi-detail-content">
        <!-- Content injected by JS -->
    </div>
</div>

<style>
    .kpi-card { border: 1px solid var(--border) !important; }
    .kpi-card:hover { transform: translateY(-4px); border-color: var(--primary) !important; }
    .kpi-card.active { 
        border-color: var(--primary) !important; 
        background: linear-gradient(135deg, rgba(124, 58, 237, 0.08) 0%, rgba(124, 58, 237, 0.02) 100%) !important;
        box-shadow: 0 10px 25px -5px rgba(124, 58, 237, 0.15) !important;
    }
</style>

<script>
function showKpiDetails(type, element) {
    const container = document.getElementById('kpi-details-container');
    const title = document.getElementById('kpi-detail-title');
    const content = document.getElementById('kpi-detail-content');
    
    // Highlight active card
    document.querySelectorAll('.kpi-card').forEach(c => c.classList.remove('active'));
    if (element) {
        element.classList.add('active');
    } else {
        const firstCard = document.querySelector('.kpi-card');
        if (firstCard) firstCard.classList.add('active');
    }
    
    container.style.display = 'block';
    content.innerHTML = '<div style="text-align: center; padding: 4rem;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';

    let html = '';
    switch(type) {
        case 'active-lines':
            title.innerHTML = '<i class="fas fa-industry"></i> Active Production Lines';
            html = generateProductionCards(<?php echo json_encode($active_lines); ?>);
            break;
        case 'completed-lines':
            title.innerHTML = '<i class="fas fa-check-double"></i> Completed Production Lines';
            html = generateProductionCards(<?php echo json_encode($completed_lines); ?>);
            break;
        case 'blocked-lines':
            title.innerHTML = '<i class="fas fa-ban"></i> Blocked Production Lines';
            html = generateProductionCards(<?php echo json_encode($blocked_lines); ?>);
            break;
        case 'products-list':
            title.innerHTML = '<i class="fas fa-shirt"></i> Total Products';
            html = generateProductsCards(<?php echo json_encode($products_list); ?>);
            break;
        case 'low-stock':
            title.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Low Stock Alerts';
            html = generateInventoryCards(<?php echo json_encode($low_stock_items); ?>);
            break;
    }
    content.innerHTML = html;
}

window.addEventListener('DOMContentLoaded', () => {
    showKpiDetails('active-lines');
});

function generateProductionCards(data) {
    if (!data.length) return '<div class="card" style="text-align: center; padding: 4rem; color: var(--text-muted); font-style: italic;">No production lines found in this category.</div>';
    
    let cards = data.map(line => {
        const blockedStage = line.full_stages.find(ls => ls.status === 'Blocked');
        const isBlocked = !!blockedStage;
        const currentStage = line.full_stages.find(ls => ls.status !== 'Completed');
        const displayStage = currentStage || (line.full_stages.length ? line.full_stages[line.full_stages.length - 1] : null);
        const currentPercent = displayStage ? ((displayStage.completed_units / (displayStage.quantity || 1)) * 100).toFixed(1) : 0;
        
        const productsHtml = line.products.map(p => `
                <span onclick="event.stopPropagation(); viewProductDetails(${p.id})" style="cursor: pointer; font-size: 0.7rem; color: var(--text-main); background: var(--bg-dark); padding: 0.2rem 0.5rem; border-radius: 4px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.3rem;">
                    <i class="fas fa-shopping-bag" style="font-size: 0.6rem; opacity: 0.5;"></i>
                    ${p.name} <span style="color: var(--primary); font-weight: 700;">(${p.quantity})</span>
                </span>
        `).join('');

        const stagesHtml = line.full_stages.map(ls => {
            const isCurrent = currentStage && currentStage.id === ls.id;
            const isCompleted = ls.status === 'Completed';
            
            let bg = 'var(--bg-dark)';
            let border = 'var(--border)';
            let color = 'var(--text-muted)';
            let weight = '500';

            if (isCurrent) {
                bg = 'rgba(79, 70, 229, 0.05)';
                border = 'var(--primary)';
                color = 'var(--text-main)';
                weight = '700';
            } else if (isCompleted) {
                bg = 'rgba(16, 185, 129, 0.05)';
                border = 'var(--success)';
                color = 'var(--success)';
            } else if (ls.status === 'Blocked') {
                border = 'var(--danger)';
                color = 'var(--danger)';
            }

            return `
                <span style="font-size: 0.7rem; padding: 0.2rem 0.6rem; background: ${bg}; border-radius: 6px; display: flex; align-items: center; gap: 0.4rem; border: 1px solid ${border}; color: ${color}; font-weight: ${weight};">
                    <div style="width: 6px; height: 6px; border-radius: 50%; background: ${ls.status === 'Blocked' ? 'var(--danger)' : (ls.color_code || 'var(--primary)')};"></div>
                    ${ls.stage_name}
                    ${isCompleted ? '<i class="fas fa-check-circle" style="color: var(--success); font-size: 0.65rem;"></i>' : ''}
                </span>
            `;
        }).join('');

        const statusColor = line.status === 'Completed' ? 'var(--primary)' : (line.status === 'Blocked' ? 'var(--danger)' : (line.is_active ? 'var(--success)' : 'var(--danger)'));
        const statusIcon = line.status === 'Completed' ? 'fa-flag-checkered' : (line.status === 'Blocked' ? 'fa-exclamation-triangle' : (line.is_active ? 'fa-check-circle' : 'fa-times-circle'));

        return `
            <div class="data-card" onclick='viewLineReadOnly(${JSON.stringify(line)})' style="border-top: 4px solid ${isBlocked ? 'var(--danger)' : (line.is_active ? 'var(--success)' : 'var(--border)')}; min-height: 220px; display: flex; flex-direction: column; transition: all 0.3s; cursor: pointer; ${!line.is_active ? 'filter: grayscale(0.4) opacity(0.8);' : ''} ${isBlocked ? 'box-shadow: 0 0 20px rgba(239, 68, 68, 0.2); border: 1px solid rgba(239, 68, 68, 0.3);' : ''}">
                <div class="data-card-header" style="padding: 1rem; padding-bottom: 0.25rem; display: flex; justify-content: space-between; align-items: flex-start;">
                    <div>
                        <h3 style="font-size: 1.1rem; font-weight: 700; margin-bottom: 0.25rem; color: var(--text-main);">${line.name}</h3>
                        <div style="display: flex; gap: 0.5rem; align-items: center;">
                            <div style="font-size: 0.7rem; font-weight: 800; color: ${statusColor}; text-transform: uppercase; letter-spacing: 0.05em;">
                                <i class="fas ${statusIcon}"></i>
                                ${line.status}
                            </div>
                            ${isBlocked && line.status !== 'Blocked' ? `
                                <div class="pulse-red" style="font-size: 0.65rem; font-weight: 900; background: var(--danger); color: white; padding: 0.1rem 0.5rem; border-radius: 4px; letter-spacing: 1px;">BLOCKED</div>
                            ` : ''}
                        </div>
                    </div>
                    <button class="btn-icon" style="background: var(--bg-dark); color: var(--primary); border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border: none;">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>

                <div class="data-card-body" style="flex: 1; padding: 0.5rem 1rem;">
                    <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.4rem;">
                        <i class="far fa-calendar-alt"></i>
                        ${formatDateSimple(line.start_date)} - ${formatDateSimple(line.end_date)}
                    </div>

                    <div style="margin-bottom: 0.75rem;">
                        <div style="font-size: 0.6rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.4rem;">Products</div>
                        <div style="display: flex; flex-wrap: wrap; gap: 0.3rem;">${productsHtml}</div>
                    </div>

                    <div style="margin-bottom: 0.75rem;">
                        <div style="font-size: 0.6rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.5rem;">Workflow</div>
                        <div style="display: flex; gap: 0.3rem; flex-wrap: wrap;">${stagesHtml}</div>
                    </div>

                    ${isBlocked ? `
                        <div style="background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.2); border-radius: 12px; padding: 0.75rem; margin-bottom: 0.5rem;">
                            <div style="font-size: 0.65rem; font-weight: 700; color: var(--danger); text-transform: uppercase; margin-bottom: 0.25rem;">
                                <i class="fas fa-exclamation-triangle"></i> Blocker Reason (${blockedStage.stage_name})
                            </div>
                            <p style="font-size: 0.75rem; color: var(--text-main); margin: 0; line-height: 1.4; font-style: italic;">
                                "${blockedStage.current_status_note || 'No reason specified'}"
                            </p>
                        </div>
                    ` : ''}
                </div>

                <div class="data-card-footer" style="padding: 0.6rem 1rem; border-top: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; background: rgba(0,0,0,0.02);">
                    <div style="display: flex; flex-direction: column; line-height: 1.1;">
                        <div style="font-size: 1rem; font-weight: 800; color: ${isBlocked ? 'var(--danger)' : (line.is_active ? 'var(--success)' : 'var(--text-muted)')};">${currentPercent}%</div>
                        <div style="font-size: 0.5rem; color: var(--text-muted); text-transform: uppercase; font-weight: 700;">Stage Progress</div>
                    </div>
                    <div style="font-size: 0.6rem; font-weight: 800; color: var(--primary); background: var(--bg-dark); padding: 0.15rem 0.5rem; border-radius: 4px;">READ-ONLY</div>
                </div>
            </div>
        `;
    }).join('');
    
    return `<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1.5rem;">${cards}</div>`;
}

function generateProductsCards(data) {
    if (!data.length) return '<div class="card" style="text-align: center; padding: 4rem; color: var(--text-muted); font-style: italic;">No products found in the catalog.</div>';
    
    let cards = data.map(p => `
        <div class="card" onclick='viewProductDetails(${p.id})' style="min-height: 180px; display: flex; flex-direction: column; padding: 1rem; transition: all 0.3s; background: white; cursor: pointer;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.75rem;">
                <div style="display: flex; align-items: center; gap: 0.75rem;">
                    <div style="width: 40px; height: 40px; border-radius: 12px; background: #f3f0ff; color: #7c3aed; display: flex; align-items: center; justify-content: center; font-size: 1.1rem;">
                        <i class="fas fa-shirt"></i>
                    </div>
                    <div>
                        <h3 style="font-size: 1rem; font-weight: 800; color: #1e293b; margin-bottom: 0.1rem;">${p.name}</h3>
                        <div style="font-size: 0.7rem; font-weight: 700; color: #7c3aed; letter-spacing: 0.02em;">${p.sku}</div>
                    </div>
                </div>
                <div style="background: #ecfdf5; color: #059669; padding: 0.2rem 0.6rem; border-radius: 20px; font-size: 0.6rem; font-weight: 800; display: flex; align-items: center; gap: 0.3rem;">
                    <div style="width: 5px; height: 5px; border-radius: 50%; background: #10b981;"></div>
                    Active
                </div>
            </div>

            <div style="display: flex; flex-direction: column; gap: 0.5rem; margin-bottom: 0.5rem;">
                <div style="display: flex; align-items: center; gap: 0.5rem; color: #64748b; font-size: 0.75rem;">
                    <i class="fas fa-barcode" style="width: 14px; opacity: 0.6;"></i>
                    <span style="font-weight: 600;">SKU: <span style="color: #7c3aed;">${p.sku}</span></span>
                </div>
                <div style="display: flex; align-items: center; gap: 0.5rem; color: #64748b; font-size: 0.75rem;">
                    <i class="fas fa-building" style="width: 14px; opacity: 0.6;"></i>
                    <span style="font-weight: 600;">Buyer: <span style="color: #1e293b;">${p.buyer_name || 'Individual'}</span></span>
                </div>
                <div style="display: flex; align-items: flex-start; gap: 0.5rem; color: #64748b; font-size: 0.75rem;">
                    <i class="fas fa-info-circle" style="width: 14px; opacity: 0.6; margin-top: 0.15rem;"></i>
                    <span style="font-weight: 500; font-style: italic;">${p.description || 'No description provided'}</span>
                </div>
            </div>
        </div>
    `).join('');
    return `<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem;">${cards}</div>`;
}

function generateInventoryCards(data) {
    if (!data.length) return '<div class="card" style="text-align: center; padding: 4rem; color: var(--text-muted); font-style: italic;">All inventory levels are healthy.</div>';
    
    let cards = data.map(item => `
        <div class="card" style="min-height: 180px; display: flex; flex-direction: column; padding: 1rem; transition: all 0.3s; background: white; border-top: 4px solid #ef4444;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.75rem;">
                <div style="display: flex; align-items: center; gap: 0.75rem;">
                    <div style="width: 40px; height: 40px; border-radius: 12px; background: #fee2e2; color: #ef4444; display: flex; align-items: center; justify-content: center; font-size: 1.1rem;">
                        <i class="fas fa-box"></i>
                    </div>
                    <div>
                        <h3 style="font-size: 1rem; font-weight: 800; color: #1e293b; margin-bottom: 0.1rem;">${item.name}</h3>
                        <div style="font-size: 0.7rem; font-weight: 700; color: #ef4444; letter-spacing: 0.02em;">${item.sku}</div>
                    </div>
                </div>
                <div style="background: #fee2e2; color: #b91c1c; padding: 0.2rem 0.6rem; border-radius: 20px; font-size: 0.6rem; font-weight: 800; display: flex; align-items: center; gap: 0.3rem;">
                    <i class="fas fa-triangle-exclamation"></i> LOW
                </div>
            </div>

            <div style="background: #f8fafc; border-radius: 12px; padding: 0.75rem; margin-bottom: 0.75rem; border: 1px solid #e2e8f0; display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; align-items: center;">
                <div>
                    <div style="font-size: 0.6rem; color: #64748b; text-transform: uppercase; font-weight: 800; margin-bottom: 0.15rem;">Available Stock</div>
                    <div style="font-size: 1.1rem; font-weight: 900; color: #ef4444;">${parseFloat(item.stock).toFixed(4)} <small style="font-size: 0.65rem; font-weight: 600; color: #64748b;">${item.unit}</small></div>
                </div>
                <div style="text-align: right;">
                    <div style="font-size: 0.6rem; color: #64748b; text-transform: uppercase; font-weight: 800; margin-bottom: 0.15rem;">Reserved</div>
                    <div style="font-size: 1rem; font-weight: 800; color: #f59e0b;">${parseFloat(item.reserved_stock || 0).toFixed(4)} <small style="font-size: 0.65rem; font-weight: 600;">${item.unit}</small></div>
                </div>
                <div style="grid-column: span 2; border-top: 1px solid #e2e8f0; padding-top: 0.5rem; margin-top: 0.25rem;">
                    <div style="font-size: 0.6rem; color: #64748b; text-transform: uppercase; font-weight: 800; margin-bottom: 0.15rem;">Min. Required</div>
                    <div style="font-size: 0.9rem; font-weight: 800; color: #1e293b;">${parseFloat(item.min_level).toFixed(4)} <small style="font-size: 0.65rem; font-weight: 600;">${item.unit}</small></div>
                </div>
            </div>
        </div>
    `).join('');
    return `<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem;">${cards}</div>`;
}

function formatDateSimple(dateStr) {
    if (!dateStr) return 'N/A';
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function formatDate(dateStr) {
    if (!dateStr) return 'N/A';
    return new Date(dateStr).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
}

async function viewProductDetails(productId) {
    const body = document.getElementById('product-view-body');
    body.innerHTML = '<div style="text-align: center; padding: 3rem;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';
    openModal('productViewModal');

    try {
        const result = await apiCall('products', { action: 'get', id: productId });
        if (result.success) {
            const p = result.product;
            window.currentProductSamples = p.samples || [];
            window.currentSlideIndex = 0;
            const isImg = (path) => path && path.match(/\.(jpg|jpeg|png|gif|webp)$/i);

            body.innerHTML = `
                <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 2.5rem;">
                    <div>
                        <div style="font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 1rem; letter-spacing: 0.05em; display: flex; align-items: center; justify-content: space-between;">
                            <div style="display: flex; align-items: center; gap: 0.5rem;">
                                <i class="fas fa-images" style="color: var(--primary);"></i>
                                Product Samples
                            </div>
                            <div id="slide-counter" style="background: var(--bg-dark); padding: 0.2rem 0.6rem; border-radius: 20px; font-size: 0.6rem; color: var(--primary); border: 1px solid var(--border);">1 / ${window.currentProductSamples.length || 1}</div>
                        </div>
                        
                        <div style="position: relative; width: 100%; aspect-ratio: 1; background: var(--bg-dark); border-radius: 24px; border: 1px solid var(--border); box-shadow: var(--shadow-lg); overflow: hidden;">
                            <div id="slides-wrapper" style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                                ${window.currentProductSamples.length > 0 ? (isImg(window.currentProductSamples[0].file_path) 
                                    ? `<img src="${window.currentProductSamples[0].file_path}" style="width: 100%; height: 100%; object-fit: contain;">`
                                    : `<div style="text-align: center; color: var(--text-muted); padding: 2rem;"><i class="fas fa-file-alt fa-5x" style="margin-bottom: 1.5rem; opacity: 0.5;"></i><div style="font-size: 1rem; font-weight: 800; color: var(--text-main);">${window.currentProductSamples[0].file_name}</div></div>`)
                                    : (p.image 
                                        ? `<img src="${p.image}" style="width: 100%; height: 100%; object-fit: contain;">`
                                        : `<div style="text-align: center; color: var(--text-muted); opacity: 0.3;"><i class="fas fa-image fa-5x"></i><br><br>No Samples</div>`)
                                }
                            </div>

                            ${window.currentProductSamples.length > 1 ? `
                                <button onclick="changeSlide(-1)" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; border-radius: 50%; background: rgba(0,0,0,0.5); color: white; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(4px); transition: all 0.2s;" onmouseover="this.style.background='var(--primary)'" onmouseout="this.style.background='rgba(0,0,0,0.5)'">
                                    <i class="fas fa-chevron-left"></i>
                                </button>
                                <button onclick="changeSlide(1)" style="position: absolute; right: 1rem; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; border-radius: 50%; background: rgba(0,0,0,0.5); color: white; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(4px); transition: all 0.2s;" onmouseover="this.style.background='var(--primary)'" onmouseout="this.style.background='rgba(0,0,0,0.5)'">
                                    <i class="fas fa-chevron-right"></i>
                                </button>
                            ` : ''}
                        </div>

                        <div style="display: flex; gap: 0.75rem; margin-top: 1rem; overflow-x: auto; padding-bottom: 0.5rem;" class="custom-scrollbar">
                            ${window.currentProductSamples.map((s, idx) => `
                                <div onclick="goToSlide(${idx})" style="flex: 0 0 60px; aspect-ratio: 1; border-radius: 12px; border: 2px solid ${idx === 0 ? 'var(--primary)' : 'var(--border)'}; overflow: hidden; background: var(--bg-dark); cursor: pointer; transition: all 0.2s;" class="slide-thumb" data-index="${idx}">
                                    ${isImg(s.file_path) ? `<img src="${s.file_path}" style="width: 100%; height: 100%; object-fit: cover;">` : `<div style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 0.8rem;"><i class="fas fa-file"></i></div>`}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div>
                        <div style="margin-bottom: 2rem;">
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.4rem; letter-spacing: 0.05em;">Product Information</div>
                            <div style="font-size: 1.75rem; font-weight: 900; color: var(--text-main); line-height: 1.2;">${p.name}</div>
                            <div style="display: flex; gap: 1rem; margin-top: 0.75rem;">
                                <span style="background: rgba(79, 70, 229, 0.1); color: var(--primary); padding: 0.2rem 0.6rem; border-radius: 6px; font-size: 0.75rem; font-weight: 800;">SKU: ${p.sku}</span>
                                <span style="background: var(--bg-dark); color: var(--text-muted); padding: 0.2rem 0.6rem; border-radius: 6px; font-size: 0.75rem; font-weight: 700;">${p.buyer_name || 'Generic Product'}</span>
                            </div>
                        </div>
                        <div style="margin-bottom: 2rem;">
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.6rem; letter-spacing: 0.05em;">Description</div>
                            <div style="font-size: 0.95rem; color: var(--text-muted); line-height: 1.6; background: var(--bg-dark); padding: 1rem; border-radius: 12px; border: 1px solid var(--border);">${p.description || 'No detailed description available.'}</div>
                        </div>
                        <div>
                            <div style="font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.8rem; letter-spacing: 0.05em;">Bill of Materials (BOM)</div>
                            <div style="background: var(--bg-dark); border-radius: 16px; border: 1px solid var(--border); overflow: hidden;">
                                ${(p.materials || []).map(m => `
                                    <div style="padding: 1rem; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center;">
                                        <div style="display: flex; align-items: center; gap: 1rem;">
                                            <div style="width: 32px; height: 32px; background: var(--bg-card); border-radius: 8px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border);"><i class="fas fa-boxes" style="font-size: 0.8rem; color: var(--text-muted);"></i></div>
                                            <div>
                                                <div style="font-size: 0.9rem; font-weight: 700; color: var(--text-main);">${m.name}</div>
                                                <div style="font-size: 0.7rem; color: var(--text-muted); font-family: monospace;">${m.sku}</div>
                                            </div>
                                        </div>
                                        <div style="text-align: right;">
                                            <div style="font-size: 1rem; font-weight: 900; color: var(--primary);">${m.quantity} <span style="font-size: 0.7rem; color: var(--text-muted); font-weight: 500;">${m.unit}</span></div>
                                            <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase; font-weight: 700;">Required</div>
                                        </div>
                                    </div>
                                `).join('') || '<div style="padding: 2rem; text-align: center; color: var(--text-muted); font-style: italic; font-size: 0.9rem;">No material requirements defined.</div>'}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        } else {
            notify(result.message, 'error');
        }
    } catch (error) {
        notify('Failed to load product details', 'error');
    }
}

function changeSlide(direction) {
    const total = window.currentProductSamples.length;
    if (total <= 1) return;
    window.currentSlideIndex = (window.currentSlideIndex + direction + total) % total;
    updateSlideshowUI();
}

function goToSlide(index) {
    window.currentSlideIndex = index;
    updateSlideshowUI();
}

function updateSlideshowUI() {
    const s = window.currentProductSamples[window.currentSlideIndex];
    const wrapper = document.getElementById('slides-wrapper');
    const isImg = s.file_path.match(/\.(jpg|jpeg|png|gif|webp)$/i);
    
    wrapper.style.opacity = '0';
    setTimeout(() => {
        if (isImg) {
            wrapper.innerHTML = `<img src="${s.file_path}" style="width: 100%; height: 100%; object-fit: contain; animation: fadeIn 0.3s;">`;
        } else {
            wrapper.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 2rem; animation: fadeIn 0.3s;"><i class="fas fa-file-alt fa-5x" style="margin-bottom: 1.5rem; opacity: 0.5;"></i><div style="font-size: 1rem; font-weight: 800; color: var(--text-main);">${s.file_name}</div></div>`;
        }
        wrapper.style.opacity = '1';
        document.getElementById('slide-counter').innerText = `${window.currentSlideIndex + 1} / ${window.currentProductSamples.length}`;
        
        document.querySelectorAll('.slide-thumb').forEach((thumb, idx) => {
            if (idx === window.currentSlideIndex) {
                thumb.style.borderColor = 'var(--primary)';
                thumb.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
            } else {
                thumb.style.borderColor = 'var(--border)';
            }
        });
    }, 200);
}

function viewLineReadOnly(line) {
    document.getElementById('view-summary-name').innerText = line.name;
    document.getElementById('view-summary-start').innerText = formatDate(line.start_date);
    document.getElementById('view-summary-end').innerText = formatDate(line.end_date);
    
    const productsHtml = (line.products || []).map(p => `
        <div style="background: var(--bg-card); padding: 0.4rem 0.8rem; border-radius: 12px; border: 1px solid var(--border); display: flex; align-items: center; gap: 0.5rem; min-width: max-content;">
            <i class="fas fa-shopping-bag" style="color: var(--primary); font-size: 0.8rem;"></i>
            <span onclick="viewProductDetails(${p.id})" style="cursor: pointer; font-size: 0.85rem; font-weight: 700; color: var(--text-main); white-space: nowrap;">${p.name} - <span style="color: var(--primary);">${p.quantity} units</span></span>
        </div>
    `).join('');
    document.getElementById('view-summary-products').innerHTML = productsHtml || '<span style="color: var(--text-muted);">No products assigned</span>';
    document.getElementById('view-summary-products').style.display = 'flex';
    document.getElementById('view-summary-products').style.flexWrap = 'wrap';
    document.getElementById('view-summary-products').style.gap = '0.5rem';

    let tableHtml = `
        <style>
            .mobile-scroll-container { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; margin-bottom: 1rem; border-radius: 12px; }
            @media (max-width: 768px) {
                .details-grid { grid-template-columns: 1fr !important; gap: 1.5rem !important; }
            }
        </style>
        <div class="mobile-scroll-container">
            <table style="width: 100%; min-width: 800px; border-collapse: separate; border-spacing: 0 0.5rem; margin-top: -0.5rem;">
                <thead>
                    <tr style="text-align: left; font-size: 0.65rem; text-transform: uppercase; color: var(--text-muted); letter-spacing: 1px;">
                        <th style="padding: 0.5rem 1rem;">Stage</th>
                        <th style="padding: 0.5rem 1rem;">Resources</th>
                        <th style="padding: 0.5rem 1rem;">Schedule</th>
                        <th style="padding: 0.5rem 1rem;">Time Spent</th>
                        <th style="padding: 0.5rem 1rem; text-align: right;">Progress</th>
                    </tr>
                </thead>
                <tbody>
    `;

    (line.full_stages || []).forEach((ls, idx) => {
        const staffHtml = (ls.staff || []).map(s => `
            <div style="display: flex; align-items: center; gap: 0.4rem; font-size: 0.75rem; color: var(--text-main); font-weight: 500; margin-bottom: 0.15rem;">
                ${s.profile_picture ? `<img src="${s.profile_picture}" style="width: 16px; height: 16px; border-radius: 50%; object-fit: cover;">` : `<div style="width: 16px; height: 16px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.5rem;">${s.name.charAt(0)}</div>`}
                <span>${s.name}</span>
            </div>
        `).join('');

        const machineryHtml = (ls.machinery || []).map(m => `
            <div style="display: flex; align-items: center; gap: 0.4rem; font-size: 0.7rem; color: var(--accent); font-weight: 500; opacity: 0.8;">
                <i class="fas fa-cog" style="font-size: 0.6rem;"></i> <span>${m.name}</span>
            </div>
        `).join('');

        const percent = ((ls.completed_units / (ls.quantity || 1)) * 100).toFixed(1);
        const hours = parseFloat(ls.total_hours || 0).toFixed(1);

        const timelogsHtml = (ls.timelogs || []).map(tl => `
            <div style="padding: 0.75rem; background: var(--bg-dark); border-radius: 8px; border: 1px solid var(--border); margin-bottom: 0.5rem; border-left: 3px solid var(--accent);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                    <span style="font-weight: 700; font-size: 0.7rem; color: var(--text-main);">${tl.employee_name}</span>
                    <span style="font-size: 0.6rem; color: var(--text-muted); font-weight: 600;">${formatDateSimple(tl.log_date)}</span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); line-height: 1.4; margin-bottom: 0.4rem;">${tl.comments || 'No comments'}</div>
                <div style="display: flex; gap: 0.4rem; flex-wrap: wrap;">
                    ${(tl.attachments || []).map(a => `
                        <a href="${a.file_path}" target="_blank" style="font-size: 0.6rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem; background: rgba(124, 58, 237, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid var(--primary)30;">
                            <i class="fas fa-paperclip"></i> ${a.file_name}
                        </a>
                    `).join('')}
                </div>
            </div>
        `).join('');

        const updatesHtml = (ls.updates || []).map(upd => `
            <div style="padding: 0.75rem; background: var(--bg-dark); border-radius: 8px; border: 1px solid var(--border); margin-bottom: 0.5rem; border-left: 3px solid var(--primary);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.25rem;">
                    <span style="font-weight: 700; font-size: 0.7rem; color: var(--text-main);">Manager: ${upd.manager_name}</span>
                    <span style="font-size: 0.6rem; color: var(--text-muted); font-weight: 600;">${formatDateSimple(upd.created_at)}</span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); line-height: 1.4; margin-bottom: 0.4rem;">${upd.comments || 'No comments'}</div>
                <div style="display: flex; gap: 0.4rem; flex-wrap: wrap;">
                    ${(upd.attachments || []).map(a => `
                        <a href="${a.file_path}" target="_blank" style="font-size: 0.6rem; color: var(--primary); text-decoration: none; display: flex; align-items: center; gap: 0.2rem; background: rgba(124, 58, 237, 0.05); padding: 0.15rem 0.4rem; border-radius: 4px; border: 1px solid var(--primary)30;">
                            <i class="fas fa-paperclip"></i> ${a.file_name}
                        </a>
                    `).join('')}
                </div>
            </div>
        `).join('');

        const detailsId = `stage-details-${ls.id}`;
        tableHtml += `
            <tr style="background: rgba(255,255,255,0.02); cursor: pointer;" onclick="toggleStageDetails('${detailsId}')">
                <td style="padding: 0.75rem 1rem; border-radius: 8px 0 0 8px;">
                    <div style="display: flex; align-items: center; gap: 0.75rem;">
                        <div style="width: 24px; height: 24px; background: ${ls.color_code}20; color: ${ls.color_code}; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; font-weight: 800; border: 1px solid ${ls.color_code}40;">${idx + 1}</div>
                        <div>
                            <div style="font-weight: 700; font-size: 0.85rem; color: var(--text-main);">${ls.stage_name}</div>
                            <div style="font-size: 0.6rem; font-weight: 800; color: ${
                                ls.status === 'Blocked' ? 'var(--danger)' : 
                                (ls.status === 'Completed' || ls.completed_units >= ls.quantity ? 'var(--primary)' : 
                                (ls.status === 'WIP' || ls.status === 'Active' ? 'var(--success)' : 'var(--text-muted)'))
                            }; text-transform: uppercase; letter-spacing: 0.5px; margin-top: 0.1rem;">
                                <i class="fas ${
                                    ls.status === 'Blocked' ? 'fa-ban' : 
                                    (ls.status === 'Completed' || parseFloat(ls.completed_units) >= parseFloat(ls.quantity) ? 'fa-flag-checkered' : 
                                    (ls.status === 'WIP' || ls.status === 'Active' || !ls.status ? 'fa-spinner fa-spin' : 'fa-clock'))
                                }"></i> 
                                ${
                                    ls.status === 'Blocked' ? 'Blocked' : 
                                    (ls.status === 'Completed' || parseFloat(ls.completed_units) >= parseFloat(ls.quantity) ? 'Completed' : 
                                    (ls.status === 'WIP' || ls.status === 'Active' || !ls.status ? 'Active' : ls.status))
                                }
                            </div>
                        </div>
                    </div>
                </td>
                <td style="padding: 0.75rem 1rem;">
                    <div style="display: flex; flex-direction: column;">
                        ${staffHtml || machineryHtml ? staffHtml + machineryHtml : '<span style="font-size: 0.7rem; color: var(--text-muted);">Unassigned</span>'}
                    </div>
                </td>
                <td style="padding: 0.75rem 1rem; font-size: 0.75rem; font-weight: 600;">
                    ${formatDateSimple(ls.start_date)} - ${formatDateSimple(ls.end_date)}
                </td>
                <td style="padding: 0.75rem 1rem;">
                    <div style="display: flex; align-items: center; gap: 0.4rem; color: var(--primary); font-weight: 700; font-size: 0.85rem;">
                        <i class="far fa-clock"></i> <span>${hours} <small>h</small></span>
                    </div>
                </td>
                <td style="padding: 0.75rem 1rem; text-align: right; border-radius: 0 8px 8px 0;">
                    <div style="display: flex; align-items: center; justify-content: flex-end; gap: 1rem;">
                        <div style="text-align: right;">
                            <div style="font-weight: 700; font-size: 0.85rem; color: ${percent >= 100 ? 'var(--success)' : 'var(--text-main)'};">${ls.completed_units}/${ls.quantity}</div>
                            <div style="font-size: 0.65rem; font-weight: 800; color: ${percent >= 100 ? 'var(--success)' : 'var(--primary)'};">${percent}%</div>
                        </div>
                        <i class="fas fa-chevron-up" id="chevron-${detailsId}" style="color: var(--text-muted); transition: transform 0.3s;"></i>
                    </div>
                </td>
            </tr>
            <tr id="${detailsId}" style="display: table-row;">
                <td colspan="5" style="padding: 0 1rem 1rem 1rem;">
                    <div style="background: rgba(0,0,0,0.02); border-radius: 12px; padding: 1rem; border: 1px solid var(--border);">
                        ${ls.status === 'Blocked' ? `
                            <div style="background: rgba(239, 68, 68, 0.08); border: 1px solid rgba(239, 68, 68, 0.2); border-radius: 10px; padding: 1rem; margin-bottom: 1.25rem; display: flex; align-items: center; gap: 1rem;">
                                <div style="width: 36px; height: 36px; background: var(--danger); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 4px 6px -1px rgba(239, 68, 68, 0.2);">
                                    <i class="fas fa-exclamation-triangle"></i>
                                </div>
                                <div>
                                    <div style="font-size: 0.6rem; color: var(--danger); text-transform: uppercase; font-weight: 900; letter-spacing: 0.5px; margin-bottom: 0.2rem;">Stage Bottleneck Identified</div>
                                    <div style="font-size: 0.9rem; font-weight: 700; color: var(--text-main); font-style: italic; line-height: 1.4;">"${ls.current_status_note || 'No reason specified'}"</div>
                                </div>
                            </div>
                        ` : ''}
                        <div class="details-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem;">
                            <div>
                                <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.4rem;">
                                    <i class="fas fa-user-clock"></i> Employee Time Logs
                                </div>
                                ${timelogsHtml || '<div style="font-size: 0.7rem; color: var(--text-muted); font-style: italic; padding: 0.5rem; background: var(--bg-dark); border-radius: 8px;">No activity logged yet</div>'}
                            </div>
                            <div>
                                <div style="font-size: 0.6rem; color: var(--text-muted); text-transform: uppercase; font-weight: 800; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.4rem;">
                                    <i class="fas fa-user-shield"></i> Manager Progress Updates
                                </div>
                                ${updatesHtml || '<div style="font-size: 0.7rem; color: var(--text-muted); font-style: italic; padding: 0.5rem; background: var(--bg-dark); border-radius: 8px;">No updates logged yet</div>'}
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        `;
    });

    tableHtml += `</tbody></table></div>`;
    document.getElementById('view-summary-workflow-detailed').innerHTML = tableHtml;
    openModal('viewLineModal');
}

function toggleStageDetails(id) {
    const row = document.getElementById(id);
    const chevron = document.getElementById('chevron-' + id);
    if (row.style.display === 'none') {
        row.style.display = 'table-row';
        chevron.style.transform = 'rotate(0deg)';
    } else {
        row.style.display = 'none';
        chevron.style.transform = 'rotate(-180deg)';
    }
}

function openModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.classList.add('active');
        // Ensure it's visible even if some other style tries to hide it
        modal.style.display = 'flex';
    }
}

function closeModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.classList.remove('active');
        modal.style.display = 'none';
    }
}
</script>

<!-- Product Quick View Modal (Slideshow) -->
<div id="productViewModal" class="modal-overlay" style="align-items: center; justify-content: center; z-index: 10005; background: rgba(0,0,0,0.4); backdrop-filter: blur(12px);">
    <div class="modal-content" style="width: 750px; max-width: 95vw; background: var(--bg-card); border-radius: 24px;">
        <div class="modal-header" style="border-bottom: 1px solid var(--border); padding: 1.5rem 2rem;">
            <h2 style="font-weight: 800; font-size: 1.5rem; display: flex; align-items: center; gap: 0.75rem;">
                <i class="fas fa-shopping-bag" style="color: var(--primary);"></i>
                Product Details
            </h2>
            <button class="btn-icon" style="background: var(--bg-dark); color: var(--text-muted); border-radius: 50%; width: 36px; height: 36px;" onclick="closeModal('productViewModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" id="product-view-body" style="padding: 2rem; max-height: 70vh; overflow-y: auto;">
            <div style="text-align: center; padding: 3rem;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
        </div>
    </div>
</div>

<!-- View Line Details Modal (Same as production-lines.php but Read-Only) -->
<div id="viewLineModal" class="modal-overlay">
    <div class="modal-content" style="width: 900px; max-width: 95vw; background: var(--bg-card); border-radius: 24px;">
        <div class="modal-header" style="border-bottom: 1px solid var(--border); padding: 1.5rem 2rem;">
            <h2 id="viewModalTitle" style="font-weight: 800; font-size: 1.5rem;">Production Line Details</h2>
            <button class="btn-icon" style="background: var(--bg-dark); color: var(--text-muted); border-radius: 50%; width: 36px; height: 36px;" onclick="closeModal('viewLineModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" style="padding: 2rem; max-height: 80vh; overflow-y: auto;">
            <div id="view-summary-container" style="display: flex; flex-direction: column; gap: 1.5rem;">
                <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.25rem 1.5rem; display: flex; flex-wrap: wrap; align-items: center; gap: 1.5rem; border: 1px solid var(--border);">
                    <div style="display: flex; flex-wrap: wrap; gap: 1.5rem; align-items: center; flex: 1;">
                        <div style="min-width: 120px;">
                            <div style="font-size: 0.55rem; color: var(--text-muted); margin-bottom: 0.2rem; text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;">Production Line</div>
                            <div id="view-summary-name" style="font-weight: 800; color: var(--primary); font-size: 1.1rem; letter-spacing: -0.5px;"></div>
                        </div>
                        <div style="min-width: 200px;">
                            <div style="font-size: 0.55rem; color: var(--text-muted); margin-bottom: 0.2rem; text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;">Operational Timeline</div>
                            <div style="font-weight: 700; color: var(--text-main); font-size: 0.85rem; white-space: nowrap;">
                                <span id="view-summary-start"></span> <i class="fas fa-long-arrow-alt-right" style="margin: 0 0.4rem; color: var(--text-muted); font-size: 0.7rem;"></i> <span id="view-summary-end"></span>
                            </div>
                        </div>
                    </div>
                    <div style="flex: 2; min-width: 250px; border-left: 1px solid var(--border); padding-left: 1.5rem;" class="products-header-col-dashboard">
                        <style>
                            @media (max-width: 768px) {
                                .products-header-col-dashboard { border-left: none !important; padding-left: 0 !important; border-top: 1px solid var(--border); padding-top: 1rem !important; }
                            }
                        </style>
                        <div style="font-size: 0.55rem; color: var(--text-muted); margin-bottom: 0.4rem; text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;">Assigned Products & Targets</div>
                        <div id="view-summary-products" style="display: flex; flex-wrap: wrap; gap: 0.4rem;"></div>
                    </div>
                </div>

                <div style="background: var(--bg-dark); border-radius: 16px; padding: 1.5rem; border: 1px solid var(--border);">
                    <div style="font-size: 0.6rem; color: var(--text-muted); margin-bottom: 1.25rem; text-transform: uppercase; font-weight: 800;">Workflow & Resource Allocation</div>
                    <div id="view-summary-workflow-detailed"></div>
                </div>
            </div>
        </div>
        <div class="modal-footer" style="background: var(--bg-dark); border-top: 1px solid var(--border); padding: 1.5rem 2rem; border-bottom-left-radius: 24px; border-bottom-right-radius: 24px; justify-content: flex-end;">
            <button class="btn btn-primary" onclick="closeModal('viewLineModal')">Close</button>
        </div>
    </div>
</div>

<?php endif; ?>
