@extends('layouts.dashboard.superadminapp')

@section('title', 'Machine 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-danger { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
    .bg-gradient-warning { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 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;
    }

    /* Progress Stats */
    .progress-stat { margin-bottom: 0.75rem; }
    .progress-stat .progress-label {
        display: flex;
        justify-content: space-between;
        margin-bottom: 3px;
        font-weight: 500;
        font-size: 0.75rem;
    }
    .progress { height: 6px; border-radius: 3px; }

    /* Operator Cards */
    .operator-card {
        background: #fff;
        border-radius: 8px;
        padding: 0.75rem;
        text-align: center;
        box-shadow: 0 2px 6px rgba(0,0,0,0.08);
        transition: all 0.2s;
    }
    .operator-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.12);
    }
    .operator-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid #4e73df;
        margin-bottom: 0.5rem;
    }
    .operator-name { font-weight: 600; color: #333; font-size: 0.75rem; margin-bottom: 2px; }
    .operator-role { font-size: 0.65rem; color: #666; margin-bottom: 0.25rem; }
    .operator-status {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 0.6rem;
        font-weight: 600;
    }
    .operator-status.available { background: #d4edda; color: #155724; }
    .operator-status.busy { background: #fff3cd; color: #856404; }

    /* Status Indicator */
    .status-indicator {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 6px;
        animation: pulse 2s infinite;
    }
    .status-indicator.running { background: #1cc88a; }
    .status-indicator.maintenance { background: #f6c23e; }
    .status-indicator.idle { background: #858796; }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }

    /* Machine Status Cards */
    .machine-status-card {
        border-radius: 8px;
        padding: 0.75rem;
        margin-bottom: 0.5rem;
    }
    .machine-status-card .machine-name {
        font-size: 0.7rem;
        font-weight: 600;
        text-transform: uppercase;
        margin-bottom: 0.25rem;
    }
    .machine-status-card .route-no {
        font-size: 1rem;
        font-weight: 700;
        color: #333;
    }
    .machine-status-card .process-info {
        font-size: 0.65rem;
        color: #666;
    }
    .machine-status-card .operator-info {
        font-size: 0.65rem;
        font-weight: 600;
        color: #36b9cc;
    }

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

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

    /* Compact Alerts */
    .compact-alert {
        padding: 0.5rem 0.75rem;
        border-radius: 6px;
        font-size: 0.75rem;
        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-cogs mr-2 text-primary"></i>UEPL | Machine 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
    $capacityRate = $totalMachines > 0 ? round(($runningNow / $totalMachines) * 100, 1) : 0;
    $maintenanceRate = $totalMachines > 0 ? round(($underMaintenance / $totalMachines) * 100, 1) : 0;
    $idleMachines = max($totalMachines - $runningNow - $underMaintenance, 0);
    $idleRate = $totalMachines > 0 ? round(($idleMachines / $totalMachines) * 100, 1) : 0;
@endphp

<!-- KPI Cards Row -->
<div class="row compact-row">
    <div class="col-xl-3 col-md-6">
        <a href="{{ route('superadmin.machine.machinedetails') }}" class="dashboard-card">
            <div class="kpi-card bg-gradient-primary shadow">
                <i class="fas fa-industry kpi-icon"></i>
                <div class="kpi-value">{{ $totalMachines }}</div>
                <div class="kpi-label">Total Machines</div>
                <div class="kpi-info"><i class="fas fa-cogs mr-1"></i> All registered machines</div>
            </div>
        </a>
    </div>
    <div class="col-xl-3 col-md-6">
        <a href="{{ route('superadmin.readytoproduction') }}" class="dashboard-card">
            <div class="kpi-card bg-gradient-success shadow">
                <i class="fas fa-play-circle kpi-icon"></i>
                <div class="kpi-value">{{ $runningNow }}</div>
                <div class="kpi-label">Running Now</div>
                <div class="kpi-info"><i class="fas fa-chart-line mr-1"></i> {{ $capacityRate }}% utilization</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-warning shadow">
                <i class="fas fa-tools kpi-icon"></i>
                <div class="kpi-value">{{ $underMaintenance }}</div>
                <div class="kpi-label">Under Maintenance</div>
                <div class="kpi-info"><i class="fas fa-wrench mr-1"></i> {{ $maintenanceRate }}% of total</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-danger shadow">
                <i class="fas fa-exclamation-triangle kpi-icon"></i>
                <div class="kpi-value">{{ $issuesToday }}</div>
                <div class="kpi-label">Issues Today</div>
                <div class="kpi-info"><i class="fas fa-bell mr-1"></i> Requires attention</div>
            </div>
        </a>
    </div>
</div>

<!-- Machine Status 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-tachometer-alt mr-2"></i> Machine Status Overview
        </h6>
    </div>
    <div class="card-body py-2">
        <div class="row align-items-center">
            <div class="col-md-8">
                <div class="progress-stat">
                    <div class="progress-label">
                        <span><span class="status-indicator running"></span> Running</span>
                        <span>{{ $runningNow }} ({{ $capacityRate }}%)</span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar bg-success" style="width: {{ $capacityRate }}%"></div>
                    </div>
                </div>
                <div class="progress-stat">
                    <div class="progress-label">
                        <span><span class="status-indicator maintenance"></span> Maintenance</span>
                        <span>{{ $underMaintenance }} ({{ $maintenanceRate }}%)</span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar bg-warning" style="width: {{ $maintenanceRate }}%"></div>
                    </div>
                </div>
                <div class="progress-stat mb-0">
                    <div class="progress-label">
                        <span><span class="status-indicator idle"></span> Idle</span>
                        <span>{{ $idleMachines }} ({{ $idleRate }}%)</span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar bg-secondary" style="width: {{ $idleRate }}%"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-4 text-center">
                <div class="h2 font-weight-bold mb-0 {{ $capacityRate >= 70 ? 'text-success' : ($capacityRate >= 40 ? 'text-warning' : 'text-danger') }}">
                    {{ $capacityRate }}%
                </div>
                <p class="text-muted mb-0 small">Capacity Utilization</p>
            </div>
        </div>
    </div>
</div>

<!-- Live Machine Status -->
<div class="mb-3">
    <h6 class="font-weight-bold text-gray-800 mb-2" style="font-size: 0.85rem;"><i class="fas fa-microchip mr-2"></i> Live Machine Status</h6>
    <div class="row compact-row">
        @foreach($allMachines as $machine)
            @php
                $machineKey = $activeProcesses->has($machine->machine_id) ? $machine->machine_id : ($activeProcesses->has($machine->machine_name) ? $machine->machine_name : null);
                $activeProcs = $machineKey ? $activeProcesses[$machineKey] : null;
            @endphp
            <div class="col-xl-3 col-md-6">
                <div class="card border-left-{{ $activeProcs ? 'success' : 'secondary' }} shadow-sm h-100 machine-status-card">
                    <div class="machine-name text-{{ $activeProcs ? 'success' : 'secondary' }}">
                        {{ $machine->machine_name }}
                    </div>
                    @if($activeProcs && $activeProcs->count() > 0)
                        @foreach($activeProcs as $proc)
                            <div class="route-no">{{ $proc->routeCard->route_no ?? 'N/A' }}</div>
                            <div class="process-info">{{ $proc->process }}</div>
                            <div class="operator-info"><i class="fas fa-user-circle mr-1"></i> {{ $proc->operator ?? 'NA' }}</div>
                        @endforeach
                    @else
                        <div class="route-no text-gray-400">IDLE</div>
                        <div class="process-info">No active process</div>
                    @endif
                </div>
            </div>
        @endforeach
    </div>
</div>

<!-- Charts Row -->
<div class="row compact-row">
    <!-- Production Output Chart -->
    <div class="col-lg-8">
        <div class="chart-card shadow">
            <div class="card-header" 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 Output (Last 7 Days)
                </h6>
            </div>
            <div class="card-body">
                <canvas id="productionChart" height="100"></canvas>
            </div>
        </div>
    </div>

    <!-- Machine Status Distribution Chart -->
    <div class="col-lg-4">
        <div class="chart-card shadow">
            <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-chart-pie mr-2"></i> Status Distribution
                </h6>
            </div>
            <div class="card-body">
                <canvas id="statusChart" height="160"></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.machine.machinedetails') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-cogs text-primary"></i>
                        <div class="link-title">Machines</div>
                    </div>
                </a>
            </div>
            <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-success"></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-warning"></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.report.machinereport') }}" class="text-decoration-none">
                    <div class="quick-link-card shadow-sm">
                        <i class="fas fa-chart-bar text-info"></i>
                        <div class="link-title">Reports</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-danger"></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-secondary"></i>
                        <div class="link-title">SKU Master</div>
                    </div>
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Current Shift Operators -->
<div class="compact-card shadow">
    <div class="card-header py-2" style="background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);">
        <h6 class="font-weight-bold text-white">
            <i class="fas fa-users-cog mr-2"></i> Current Shift Operators
        </h6>
    </div>
    <div class="card-body py-2">
        <div class="row">
            @forelse($currentOperators as $operator)
                <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 mb-2">
                    <div class="operator-card">
                        <img src="{{ $operator['profile_picture'] }}" alt="{{ $operator['name'] }}" class="operator-avatar">
                        <div class="operator-name">{{ $operator['name'] }}</div>
                        <div class="operator-role">{{ $operator['role'] }}</div>
                        <span class="operator-status {{ strtolower($operator['status']) }}">
                            {{ $operator['status'] }}
                        </span>
                    </div>
                </div>
            @empty
                <div class="col-12">
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-user-slash fa-2x mb-2 d-block"></i>
                        <p class="mb-0 small">No operators currently on shift</p>
                    </div>
                </div>
            @endforelse
        </div>
    </div>
</div>

<!-- Machine Status Summary & Issues -->
<div class="row compact-row">
    <div class="col-md-6">
        <div class="compact-card shadow">
            <div class="card-header py-2" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="font-weight-bold text-white">
                    <i class="fas fa-check-circle mr-2"></i> Running Machines 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">%</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><span class="status-indicator running"></span> Running</td>
                            <td class="text-center"><span class="badge badge-success">{{ $runningNow }}</span></td>
                            <td class="text-center">{{ $capacityRate }}%</td>
                        </tr>
                        <tr>
                            <td><span class="status-indicator maintenance"></span> Maintenance</td>
                            <td class="text-center"><span class="badge badge-warning">{{ $underMaintenance }}</span></td>
                            <td class="text-center">{{ $maintenanceRate }}%</td>
                        </tr>
                        <tr>
                            <td><span class="status-indicator idle"></span> Idle</td>
                            <td class="text-center"><span class="badge badge-secondary">{{ $idleMachines }}</span></td>
                            <td class="text-center">{{ $idleRate }}%</td>
                        </tr>
                    </tbody>
                    <tfoot class="thead-light">
                        <tr class="font-weight-bold">
                            <td>Total</td>
                            <td class="text-center"><span class="badge badge-primary">{{ $totalMachines }}</span></td>
                            <td class="text-center">100%</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="compact-card shadow h-100">
            <div class="card-header py-2" style="background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);">
                <h6 class="font-weight-bold text-white">
                    <i class="fas fa-exclamation-circle mr-2"></i> Issues & Alerts
                </h6>
            </div>
            <div class="card-body py-2">
                @if($issuesToday > 0)
                    <div class="compact-alert alert-danger">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <strong>{{ $issuesToday }} issue(s)</strong> reported today requiring attention.
                    </div>
                @else
                    <div class="compact-alert alert-success">
                        <i class="fas fa-check-circle mr-2"></i>
                        <strong>No issues</strong> reported today.
                    </div>
                @endif

                @if($underMaintenance > 0)
                    <div class="compact-alert alert-warning">
                        <i class="fas fa-tools mr-2"></i>
                        <strong>{{ $underMaintenance }} machine(s)</strong> under maintenance.
                    </div>
                @endif

                @if($idleMachines > ($totalMachines * 0.3))
                    <div class="compact-alert alert-info mb-0">
                        <i class="fas fa-info-circle mr-2"></i>
                        <strong>{{ $idleMachines }} machine(s)</strong> idle. Consider optimization.
                    </div>
                @endif
            </div>
        </div>
    </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.productionLast7 = @json($productionLast7);
    window.machineStatus = @json($machineStatus);

    // Production Output 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.productionLast7[date] || 0);
    }

    const prodCtx = document.getElementById('productionChart').getContext('2d');
    new Chart(prodCtx, {
        type: 'line',
        data: {
            labels: prodLabels,
            datasets: [{
                label: 'Production Output',
                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 } }
            }
        }
    });

    // Machine Status Doughnut Chart
    const statusLabels = Object.keys(window.machineStatus);
    const statusData = Object.values(window.machineStatus);

    const statusCtx = document.getElementById('statusChart').getContext('2d');
    new Chart(statusCtx, {
        type: 'doughnut',
        data: {
            labels: statusLabels,
            datasets: [{
                data: statusData,
                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%'
        }
    });
</script>
@endsection
