@extends('layouts.dashboard.superadminapp')

@section('title', 'Manufacturing Dashboard')

@section('styles')
<style>
    /* Compact Page Header */
    .page-header {
        background: #fff;
        padding: 0.5rem 1rem;
        margin-bottom: 0.75rem;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .page-header h1 { font-size: 1rem; margin: 0; color: #333; font-weight: 600; }
    .date-time-section { display: flex; align-items: center; gap: 0.5rem; }
    .date-box {
        background: linear-gradient(135deg, #f8f9fc 0%, #e3e6f0 100%);
        padding: 0.25rem 0.75rem;
        border-radius: 6px;
        font-size: 0.75rem;
        color: #5a5c69;
        font-weight: 500;
    }
    .time-box {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        padding: 0.25rem 0.75rem;
        border-radius: 6px;
        font-size: 0.75rem;
        color: #fff;
        font-weight: 600;
        font-family: 'Courier New', monospace;
        min-width: 70px;
        text-align: center;
    }

    /* Clickable Dashboard Cards */
    .dashboard-card {
        display: block;
        text-decoration: none;
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .dashboard-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        text-decoration: none;
    }

    /* Compact KPI Cards */
    .kpi-card {
        border-radius: 8px;
        padding: 0.75rem 1rem !important;
        color: #fff;
        position: relative;
        overflow: hidden;
    }
    .kpi-card .kpi-icon {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 2rem;
        opacity: 0.25;
    }
    .kpi-card .kpi-value {
        font-size: 1.5rem;
        font-weight: 700;
        line-height: 1.2;
    }
    .kpi-card .kpi-label {
        font-size: 0.7rem;
        opacity: 0.9;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    .kpi-card .kpi-info {
        font-size: 0.65rem;
        margin-top: 2px;
        opacity: 0.8;
    }

    /* Gradient Backgrounds */
    .bg-gradient-primary { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-gradient-success { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-gradient-warning { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-gradient-danger { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
    .bg-gradient-secondary { background: linear-gradient(135deg, #858796 0%, #5a5c69 100%); }

    /* Compact Cards */
    .compact-card {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        margin-bottom: 0.75rem;
    }
    .compact-card .card-header {
        border-radius: 8px 8px 0 0;
        padding: 0.5rem 0.75rem;
    }
    .compact-card .card-header h6 {
        font-size: 0.8rem;
        margin: 0;
    }
    .compact-card .card-body {
        padding: 0.75rem;
    }

    /* Chart Cards */
    .chart-card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        margin-bottom: 0.75rem;
    }
    .chart-card .card-header {
        border-radius: 8px 8px 0 0;
        padding: 0.5rem 0.75rem;
    }
    .chart-card .card-header h6 {
        font-size: 0.8rem;
        margin: 0;
    }
    .chart-card .card-body {
        padding: 0.75rem;
    }

    /* Quick Links */
    .quick-link-card {
        background: #fff;
        border-radius: 8px;
        padding: 0.75rem;
        text-align: center;
        transition: all 0.2s;
        border: 2px solid transparent;
    }
    .quick-link-card:hover {
        border-color: #4e73df;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(78,115,223,0.2);
    }
    .quick-link-card i {
        font-size: 1.25rem;
        margin-bottom: 0.25rem;
    }
    .quick-link-card .link-title {
        font-weight: 600;
        color: #333;
        font-size: 0.7rem;
    }

    /* Performance Overview */
    .perf-metric {
        text-align: center;
        padding: 0.5rem;
    }
    .perf-metric .perf-value {
        font-size: 1.25rem;
        font-weight: 700;
    }
    .perf-metric .perf-label {
        font-size: 0.7rem;
        color: #858796;
    }

    /* Alert Items */
    .alert-item {
        padding: 0.5rem 0.75rem;
        border-radius: 6px;
        margin-bottom: 0.5rem;
        display: flex;
        align-items: center;
        background: #f8f9fc;
        border-left: 3px solid;
    }
    .alert-item.warning { border-left-color: #f6c23e; }
    .alert-item.error { border-left-color: #e74a3b; }
    .alert-item .alert-icon {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 0.5rem;
        font-size: 0.75rem;
    }
    .alert-item.warning .alert-icon { background: #fff3cd; color: #856404; }
    .alert-item.error .alert-icon { background: #f8d7da; color: #721c24; }
    .alert-item .alert-message { font-weight: 500; color: #333; font-size: 0.75rem; }
    .alert-item .alert-time { font-size: 0.65rem; color: #858796; }

    /* Compact Table */
    .compact-table { font-size: 0.75rem; }
    .compact-table th, .compact-table td { padding: 0.4rem 0.5rem; }

    /* Filter Buttons */
    .filter-btn {
        padding: 3px 10px;
        border-radius: 15px;
        font-size: 0.7rem;
        transition: all 0.2s;
    }
    .filter-btn.active {
        background: #fff;
        color: #4e73df;
    }

    /* Reduce Row Margins */
    .row.compact-row { margin-bottom: 0.5rem; }
    .compact-row > [class*="col-"] { margin-bottom: 0.5rem; }
</style>
@endsection

@section('content')

<!-- Compact Page Header -->
<div class="page-header d-flex align-items-center justify-content-between">
    <h1><i class="fas fa-industry mr-2 text-primary"></i>UEPL | Manufacturing Dashboard</h1>
    <div class="date-time-section">
        <div class="date-box">
            <i class="far fa-calendar-alt mr-1"></i>
            <span id="currentDate"></span>
        </div>
        <div class="time-box">
            <span id="currentTime"></span>
        </div>
    </div>
</div>

@php
    $defectRate = 100 - $qualityRate;
    $idleMachines = isset($machineStatus['Idle']) ? $machineStatus['Idle'] : 0;
    $runningMachines = isset($machineStatus['Running']) ? $machineStatus['Running'] : 0;
    $maintenanceMachines = isset($machineStatus['Maintenance']) ? $machineStatus['Maintenance'] : 0;
    $totalMachines = $idleMachines + $runningMachines + $maintenanceMachines;
@endphp

<!-- KPI Cards Row -->
<div class="row compact-row">
    <div class="col-xl-3 col-md-6">
        <a href="{{ route('superadmin.readytoproduction') }}" class="dashboard-card">
            <div class="kpi-card bg-gradient-primary shadow">
                <i class="fas fa-box-open kpi-icon"></i>
                <div class="kpi-value">{{ number_format($totalProduction) }}</div>
                <div class="kpi-label">Total Production</div>
                <div class="kpi-info"><i class="fas fa-calendar-alt mr-1"></i> All manufacturing plans</div>
            </div>
        </a>
    </div>
    <div class="col-xl-3 col-md-6">
        <a href="{{ route('superadmin.machine.machinedetails') }}" class="dashboard-card">
            <div class="kpi-card bg-gradient-success shadow">
                <i class="fas fa-cogs kpi-icon"></i>
                <div class="kpi-value">{{ $machineUtilization }}%</div>
                <div class="kpi-label">Machine Utilization</div>
                <div class="kpi-info"><i class="fas fa-industry mr-1"></i> {{ $runningMachines }}/{{ $totalMachines }} running</div>
            </div>
        </a>
    </div>
    <div class="col-xl-3 col-md-6">
        <a href="{{ url('superadmin/quality/qc-management') }}" class="dashboard-card">
            <div class="kpi-card bg-gradient-info shadow">
                <i class="fas fa-check-double kpi-icon"></i>
                <div class="kpi-value">{{ $qualityRate }}%</div>
                <div class="kpi-label">Quality Rate</div>
                <div class="kpi-info"><i class="fas fa-clipboard-check mr-1"></i> {{ $defectRate }}% defect rate</div>
            </div>
        </a>
    </div>
    <div class="col-xl-3 col-md-6">
        <a href="{{ route('superadmin.report.machinereport') }}" class="dashboard-card">
            <div class="kpi-card bg-gradient-warning shadow">
                <i class="fas fa-tachometer-alt kpi-icon"></i>
                <div class="kpi-value">{{ $oeeRate }}%</div>
                <div class="kpi-label">OEE Score</div>
                <div class="kpi-info"><i class="fas fa-chart-line mr-1"></i> Overall Equipment Effectiveness</div>
            </div>
        </a>
    </div>
</div>

<!-- Performance Overview -->
<div class="compact-card shadow">
    <div class="card-header py-2" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="font-weight-bold text-white">
            <i class="fas fa-chart-pie mr-2"></i> Manufacturing Performance Overview
        </h6>
    </div>
    <div class="card-body py-2">
        <div class="row align-items-center">
            <div class="col-md-3 perf-metric">
                <div class="perf-value {{ $machineUtilization >= 70 ? 'text-success' : ($machineUtilization >= 40 ? 'text-warning' : 'text-danger') }}">
                    {{ $machineUtilization }}%
                </div>
                <p class="perf-label mb-0">Utilization</p>
            </div>
            <div class="col-md-3 perf-metric">
                <div class="perf-value {{ $qualityRate >= 95 ? 'text-success' : ($qualityRate >= 85 ? 'text-warning' : 'text-danger') }}">
                    {{ $qualityRate }}%
                </div>
                <p class="perf-label mb-0">Quality</p>
            </div>
            <div class="col-md-3 perf-metric">
                <div class="perf-value {{ $oeeRate >= 75 ? 'text-success' : ($oeeRate >= 60 ? 'text-warning' : 'text-danger') }}">
                    {{ $oeeRate }}%
                </div>
                <p class="perf-label mb-0">OEE</p>
            </div>
            <div class="col-md-3 perf-metric">
                <div class="perf-value text-primary">
                    {{ number_format($totalProduction) }}
                </div>
                <p class="perf-label mb-0">Total Output</p>
            </div>
        </div>
    </div>
</div>

<!-- Charts Row -->
<div class="row compact-row">
    <!-- Production Trend Chart -->
    <div class="col-lg-6">
        <div class="chart-card shadow">
            <div class="card-header d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                <h6 class="font-weight-bold text-white mb-0">
                    <i class="fas fa-chart-line mr-2"></i> Production Trend (Last 7 Days)
                </h6>
                <div>
                    <button class="btn btn-sm btn-light filter-btn active" data-filter="week">Week</button>
                    <button class="btn btn-sm btn-outline-light filter-btn" data-filter="month">Month</button>
                </div>
            </div>
            <div class="card-body">
                <canvas id="productionChart" height="130"></canvas>
            </div>
        </div>
    </div>

    <!-- Defect Analysis Chart -->
    <div class="col-lg-6">
        <div class="chart-card shadow">
            <div class="card-header" style="background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);">
                <h6 class="font-weight-bold text-white mb-0">
                    <i class="fas fa-bug mr-2"></i> Defect Analysis (Last 7 Days)
                </h6>
            </div>
            <div class="card-body">
                <canvas id="defectChart" height="130"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions -->
<div class="compact-card shadow">
    <div class="card-header py-2" style="background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);">
        <h6 class="font-weight-bold text-white">
            <i class="fas fa-bolt mr-2"></i> Quick Actions
        </h6>
    </div>
    <div class="card-body py-2">
        <div class="row">
            <div class="col-md-2 col-sm-4 col-6 mb-2">
                <a href="{{ route('superadmin.projectplanning.projectplanning') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-tasks text-primary"></i>
                        <div class="link-title">Planning</div>
                    </div>
                </a>
            </div>
            <div class="col-md-2 col-sm-4 col-6 mb-2">
                <a href="{{ route('superadmin.readytoproduction') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-play-circle text-success"></i>
                        <div class="link-title">Production</div>
                    </div>
                </a>
            </div>
            <div class="col-md-2 col-sm-4 col-6 mb-2">
                <a href="{{ route('superadmin.machine.machinedetails') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-cogs text-warning"></i>
                        <div class="link-title">Machines</div>
                    </div>
                </a>
            </div>
            <div class="col-md-2 col-sm-4 col-6 mb-2">
                <a href="{{ url('superadmin/quality/qc-management') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-clipboard-check text-info"></i>
                        <div class="link-title">Quality</div>
                    </div>
                </a>
            </div>
            <div class="col-md-2 col-sm-4 col-6 mb-2">
                <a href="{{ route('superadmin.sku.skumaster') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-boxes text-danger"></i>
                        <div class="link-title">SKU Master</div>
                    </div>
                </a>
            </div>
            <div class="col-md-2 col-sm-4 col-6 mb-2">
                <a href="{{ route('superadmin.report.machinereport') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-chart-bar text-secondary"></i>
                        <div class="link-title">Reports</div>
                    </div>
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Status Cards Row -->
<div class="row compact-row">
    <!-- Machine Status Chart -->
    <div class="col-lg-4">
        <div class="chart-card shadow h-100">
            <div class="card-header" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="font-weight-bold text-white mb-0">
                    <i class="fas fa-cog mr-2"></i> Machine Status
                </h6>
            </div>
            <div class="card-body">
                <canvas id="machineStatusChart" height="180"></canvas>
            </div>
        </div>
    </div>

    <!-- Production by Line Chart -->
    <div class="col-lg-4">
        <div class="chart-card shadow h-100">
            <div class="card-header" style="background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);">
                <h6 class="font-weight-bold text-white mb-0">
                    <i class="fas fa-industry mr-2"></i> Production by Machine
                </h6>
            </div>
            <div class="card-body">
                <canvas id="productionLineChart" height="180"></canvas>
            </div>
        </div>
    </div>

    <!-- Recent Alerts -->
    <div class="col-lg-4">
        <div class="compact-card shadow h-100">
            <div class="card-header py-2" style="background: linear-gradient(135deg, #858796 0%, #5a5c69 100%);">
                <h6 class="font-weight-bold text-white">
                    <i class="fas fa-bell mr-2"></i> Recent Alerts
                </h6>
            </div>
            <div class="card-body" style="max-height: 230px; overflow-y: auto;">
                @forelse($recentAlerts as $alert)
                    <div class="alert-item {{ strtolower($alert['type']) }}">
                        <div class="alert-icon">
                            @if(strtolower($alert['type']) == 'warning')
                                <i class="fas fa-exclamation-triangle"></i>
                            @else
                                <i class="fas fa-times-circle"></i>
                            @endif
                        </div>
                        <div class="alert-content">
                            <div class="alert-message">{{ $alert['message'] }}</div>
                            <div class="alert-time">{{ $alert['time'] }}</div>
                        </div>
                    </div>
                @empty
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-check-circle fa-2x mb-2 d-block text-success"></i>
                        <p class="mb-0 small">No alerts at this time</p>
                    </div>
                @endforelse
            </div>
        </div>
    </div>
</div>

<!-- Machine Status Summary Table -->
<div class="compact-card shadow">
    <div class="card-header py-2" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="font-weight-bold text-white">
            <i class="fas fa-list-alt mr-2"></i> Machine Status Summary
        </h6>
    </div>
    <div class="card-body p-0">
        <table class="table compact-table mb-0">
            <thead class="thead-light">
                <tr>
                    <th>Status</th>
                    <th class="text-center">Count</th>
                    <th class="text-center">Percentage</th>
                    <th>Distribution</th>
                </tr>
            </thead>
            <tbody>
                @foreach($machineStatus as $status => $count)
                    @php
                        $percentage = $totalMachines > 0 ? round(($count / $totalMachines) * 100, 1) : 0;
                        $color = $status == 'Running' ? 'success' : ($status == 'Maintenance' ? 'warning' : 'secondary');
                    @endphp
                    <tr>
                        <td class="font-weight-bold">
                            <i class="fas fa-circle text-{{ $color }} mr-2" style="font-size: 0.5rem;"></i>{{ $status }}
                        </td>
                        <td class="text-center">
                            <span class="badge badge-{{ $color }}">{{ $count }}</span>
                        </td>
                        <td class="text-center">{{ $percentage }}%</td>
                        <td>
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-{{ $color }}" style="width: {{ $percentage }}%"></div>
                            </div>
                        </td>
                    </tr>
                @endforeach
            </tbody>
            <tfoot class="thead-light">
                <tr class="font-weight-bold">
                    <td>Total Machines</td>
                    <td class="text-center"><span class="badge badge-primary">{{ $totalMachines }}</span></td>
                    <td class="text-center">100%</td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>
<script>
    // Dynamic Date/Time Update
    function updateDateTime() {
        const now = new Date();
        const options = { weekday: 'short', day: '2-digit', month: 'short', year: 'numeric' };
        document.getElementById('currentDate').textContent = now.toLocaleDateString('en-US', options);
        document.getElementById('currentTime').textContent = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);

    // Pass PHP data to JS
    window.productionTrend = @json($productionTrend ?? []);
    window.defectTrend = @json($defectTrend ?? []);
    window.machineStatus = @json($machineStatus ?? []);
    window.productionByLine = @json($productionByLine ?? []);

    // Production Trend Chart
    const prodLabels = [];
    const prodData = [];

    for (let i = 6; i >= 0; i--) {
        const date = moment().subtract(i, 'days').format('YYYY-MM-DD');
        prodLabels.push(moment(date).format('DD MMM'));
        prodData.push(window.productionTrend[date] || 0);
    }

    const prodCtx = document.getElementById('productionChart').getContext('2d');
    new Chart(prodCtx, {
        type: 'line',
        data: {
            labels: prodLabels,
            datasets: [{
                label: 'Units Produced',
                data: prodData,
                fill: true,
                backgroundColor: 'rgba(78, 115, 223, 0.1)',
                borderColor: 'rgba(78, 115, 223, 1)',
                borderWidth: 2,
                tension: 0.4,
                pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.05)' } },
                x: { grid: { display: false } }
            }
        }
    });

    // Defect Analysis Chart
    const defectLabels = [];
    const defectData = [];

    for (let i = 6; i >= 0; i--) {
        const date = moment().subtract(i, 'days').format('YYYY-MM-DD');
        defectLabels.push(moment(date).format('DD MMM'));
        defectData.push(window.defectTrend[date] || 0);
    }

    const defectCtx = document.getElementById('defectChart').getContext('2d');
    new Chart(defectCtx, {
        type: 'bar',
        data: {
            labels: defectLabels,
            datasets: [{
                label: 'Defects',
                data: defectData,
                backgroundColor: 'rgba(231, 74, 59, 0.8)',
                borderColor: 'rgba(231, 74, 59, 1)',
                borderWidth: 1,
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.05)' } },
                x: { grid: { display: false } }
            }
        }
    });

    // Machine Status Doughnut Chart
    const statusCtx = document.getElementById('machineStatusChart').getContext('2d');
    new Chart(statusCtx, {
        type: 'doughnut',
        data: {
            labels: Object.keys(window.machineStatus),
            datasets: [{
                data: Object.values(window.machineStatus),
                backgroundColor: ['#1cc88a', '#f6c23e', '#858796'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: { padding: 10, usePointStyle: true, font: { size: 10 } }
                }
            },
            cutout: '60%'
        }
    });

    // Production by Line Bar Chart
    const lineCtx = document.getElementById('productionLineChart').getContext('2d');
    new Chart(lineCtx, {
        type: 'bar',
        data: {
            labels: Object.keys(window.productionByLine),
            datasets: [{
                label: 'Output',
                data: Object.values(window.productionByLine),
                backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', '#858796', '#5a5c69', '#6f42c1'],
                borderWidth: 0,
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.05)' } },
                x: { grid: { display: false } }
            }
        }
    });

    // Filter buttons functionality
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const parent = this.closest('.card-header');
            parent.querySelectorAll('.filter-btn').forEach(b => {
                b.classList.remove('active', 'btn-light');
                b.classList.add('btn-outline-light');
            });
            this.classList.add('active', 'btn-light');
            this.classList.remove('btn-outline-light');
        });
    });
</script>
@endsection
