@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<style>
    .stat-card {
        border-radius: 12px;
        padding: 24px;
        color: #fff;
        transition: transform 0.2s, box-shadow 0.2s;
        position: relative;
        overflow: hidden;
    }
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    }
    .stat-card .stat-icon {
        position: absolute;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 3.5rem;
        opacity: 0.3;
    }
    .stat-card .stat-value {
        font-size: 2.5rem;
        font-weight: 700;
        line-height: 1;
    }
    .stat-card .stat-label {
        font-size: 0.9rem;
        opacity: 0.9;
        margin-top: 5px;
        text-transform: uppercase;
        letter-spacing: 1px;
    }
    .stat-card .stat-info {
        font-size: 0.8rem;
        margin-top: 10px;
        opacity: 0.8;
    }
    .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%); }

    .chart-card {
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        margin-bottom: 24px;
    }
    .chart-card .card-header {
        border-radius: 12px 12px 0 0;
        padding: 16px 20px;
    }
    .chart-card .card-body {
        padding: 20px;
    }

    .quick-link-card {
        background: #fff;
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        transition: all 0.2s;
        border: 2px solid transparent;
    }
    .quick-link-card:hover {
        border-color: #4e73df;
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(78,115,223,0.2);
    }
    .quick-link-card i {
        font-size: 2rem;
        margin-bottom: 10px;
    }
    .quick-link-card .link-title {
        font-weight: 600;
        color: #333;
    }

    .progress-stat {
        margin-bottom: 15px;
    }
    .progress-stat .progress-label {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
        font-weight: 500;
    }
    .progress {
        height: 8px;
        border-radius: 4px;
    }

    .filter-btn {
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 0.85rem;
        transition: all 0.2s;
    }
    .filter-btn.active {
        background: #fff;
        color: #4e73df;
    }

    .alert-item {
        padding: 12px 15px;
        border-radius: 8px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        background: #f8f9fc;
        border-left: 4px solid;
    }
    .alert-item.warning {
        border-left-color: #f6c23e;
    }
    .alert-item.error {
        border-left-color: #e74a3b;
    }
    .alert-item .alert-icon {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        font-size: 0.9rem;
    }
    .alert-item.warning .alert-icon {
        background: #fff3cd;
        color: #856404;
    }
    .alert-item.error .alert-icon {
        background: #f8d7da;
        color: #721c24;
    }
    .alert-item .alert-content {
        flex: 1;
    }
    .alert-item .alert-message {
        font-weight: 500;
        color: #333;
        font-size: 0.85rem;
    }
    .alert-item .alert-time {
        font-size: 0.7rem;
        color: #858796;
    }

    .oee-gauge {
        position: relative;
        width: 120px;
        height: 120px;
        margin: 0 auto;
    }
    .oee-value {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 1.5rem;
        font-weight: 700;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h5 mb-0 text-gray-800">UEPL | Manufacturing Dashboard</h1>
    <div class="display-date">
        <span id="day">day</span>,
        <span id="daynum">00</span>
        <span id="month">month</span>
        <span id="year">0000</span>
    </div>
    <div class="display-time"></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

<!-- Summary Statistics -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="stat-card bg-gradient-primary shadow">
            <i class="fas fa-box-open stat-icon"></i>
            <div class="stat-value">{{ number_format($totalProduction) }}</div>
            <div class="stat-label">Total Production</div>
            <div class="stat-info">
                <i class="fas fa-calendar-alt mr-1"></i> All manufacturing plans
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="stat-card bg-gradient-success shadow">
            <i class="fas fa-cogs stat-icon"></i>
            <div class="stat-value">{{ $machineUtilization }}%</div>
            <div class="stat-label">Machine Utilization</div>
            <div class="stat-info">
                <i class="fas fa-industry mr-1"></i> {{ $runningMachines }} of {{ $totalMachines }} machines running
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="stat-card bg-gradient-info shadow">
            <i class="fas fa-check-double stat-icon"></i>
            <div class="stat-value">{{ $qualityRate }}%</div>
            <div class="stat-label">Quality Rate</div>
            <div class="stat-info">
                <i class="fas fa-clipboard-check mr-1"></i> {{ $defectRate }}% defect rate
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="stat-card bg-gradient-warning shadow">
            <i class="fas fa-tachometer-alt stat-icon"></i>
            <div class="stat-value">{{ $oeeRate }}%</div>
            <div class="stat-label">OEE Score</div>
            <div class="stat-info">
                <i class="fas fa-chart-line mr-1"></i> Overall Equipment Effectiveness
            </div>
        </div>
    </div>
</div>

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

<!-- Charts Row -->
<div class="row">
    <!-- Production Trend Chart -->
    <div class="col-lg-6 mb-4">
        <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="m-0 font-weight-bold text-white">
                    <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="150"></canvas>
            </div>
        </div>
    </div>

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

<!-- Quick Actions -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-link mr-2"></i> Quick Actions
        </h6>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-2 col-sm-4 col-6 mb-3">
                <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-3">
                <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-3">
                <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-3">
                <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-3">
                <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-3">
                <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">
    <!-- Machine Status Chart -->
    <div class="col-lg-4 mb-4">
        <div class="chart-card shadow h-100">
            <div class="card-header" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-cog mr-2"></i> Machine Status
                </h6>
            </div>
            <div class="card-body">
                <canvas id="machineStatusChart" height="200"></canvas>
            </div>
        </div>
    </div>

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

    <!-- Recent Alerts -->
    <div class="col-lg-4 mb-4">
        <div class="card shadow h-100">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #858796 0%, #5a5c69 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-bell mr-2"></i> Recent Alerts
                </h6>
            </div>
            <div class="card-body">
                @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-4">
                        <i class="fas fa-check-circle fa-3x mb-3 d-block text-success"></i>
                        <p class="mb-0">No alerts at this time</p>
                    </div>
                @endforelse
            </div>
        </div>
    </div>
</div>

<!-- Machine Status Summary Table -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 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 table-sm 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"></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: 8px;">
                                <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>
    // 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 = [];

    // Generate last 7 days
    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: 3,
                tension: 0.4,
                pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 5,
                pointHoverRadius: 7
            }]
        },
        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: 5
            }]
        },
        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: 15, usePointStyle: true }
                }
            },
            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: 5
            }]
        },
        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');
        });
    });

    // Dynamic Date/Time
    function updateDateTime() {
        const now = new Date();
        document.getElementById('day').textContent = now.toLocaleString('en-us', { weekday: 'long' });
        document.getElementById('daynum').textContent = now.getDate();
        document.getElementById('month').textContent = now.toLocaleString('en-us', { month: 'long' });
        document.getElementById('year').textContent = now.getFullYear();
        document.querySelector('.display-time').textContent = now.toLocaleTimeString();
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);
</script>
@endsection
