@extends('layouts.dashboard.superadminapp')

@section('title', 'Machine Report')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    .stat-card {
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-active { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-process { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-hours { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-idle { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Machine Report" icon="chart-bar" iconColor="info" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Filter Card -->
<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-filter mr-2"></i> Filter Options
        </h6>
    </div>
    <div class="card-body">
        <form id="machineReportFilters" method="GET" action="{{ route('superadmin.report.machinereport') }}">
            <div class="row align-items-end">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Machine</label>
                    <select name="machine_id" id="machine_id" class="form-control">
                        <option value="">All Machines</option>
                        @foreach ($machines as $machine)
                            <option value="{{ $machine->id }}" {{ request('machine_id') == $machine->id ? 'selected' : '' }}>
                                {{ $machine->machine_id }} - {{ $machine->machine_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">Status</label>
                    <select name="status" class="form-control">
                        <option value="">All Status</option>
                        <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Active</option>
                        <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactive</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-primary btn-sm mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filter
                    </button>
                    <a href="{{ route('superadmin.report.machinereport') }}" class="btn btn-secondary btn-sm">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </a>
                </div>
                <div class="col-md-2 mb-3">
                    <button type="button" class="btn btn-success btn-sm" id="exportExcelBtn">
                        <i class="fas fa-file-excel mr-1"></i> Export Excel
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

@php
    $totalMachines = $machines->count();
    $activeMachines = $machines->filter(fn($m) => isset($m->routeProcesses) && $m->routeProcesses->count() > 0);
    $idleMachines = $machines->filter(fn($m) => !isset($m->routeProcesses) || $m->routeProcesses->count() == 0);
    $totalProcesses = $machines->sum(fn($m) => isset($m->routeProcesses) ? $m->routeProcesses->count() : 0);

    $totalHours = 0;
    $totalMinutes = 0;
    foreach($machines as $machine) {
        if (isset($machine->routeProcesses)) {
            foreach($machine->routeProcesses as $proc) {
                $totalHours += (int)($proc->cycle_hours ?? 0);
                $totalMinutes += (int)($proc->cycle_minutes ?? 0);
            }
        }
    }
    $totalHours += floor($totalMinutes / 60);
    $totalMinutes = $totalMinutes % 60;
@endphp

<!-- Summary Stats -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-total">
            <div class="stat-value">{{ $totalMachines }}</div>
            <div class="stat-label"><i class="fas fa-cogs mr-1"></i> Total Machines</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-active">
            <div class="stat-value">{{ $activeMachines->count() }}</div>
            <div class="stat-label"><i class="fas fa-check-circle mr-1"></i> Active Machines</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-process">
            <div class="stat-value">{{ $totalProcesses }}</div>
            <div class="stat-label"><i class="fas fa-tasks mr-1"></i> Total Processes</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-idle">
            <div class="stat-value">{{ $idleMachines->count() }}</div>
            <div class="stat-label"><i class="fas fa-pause-circle mr-1"></i> Idle Machines</div>
        </div>
    </div>
</div>

<!-- Machine Details Card -->
<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 mr-2"></i> Machine Details
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="machineTable" class="table table-bordered table-striped table-sm" width="100%">
                <thead class="thead-light">
                    <tr class="text-center">
                        <th>Machine ID</th>
                        <th>Machine Name</th>
                        <th>Serial No</th>
                        <th>Make</th>
                        <th>Model</th>
                        <th>Processes</th>
                        <th>Total Cycle Time</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($machines as $machine)
                        @php
                            $machineHours = 0;
                            $machineMinutes = 0;
                            $processCount = 0;
                            if (isset($machine->routeProcesses)) {
                                $processCount = $machine->routeProcesses->count();
                                foreach($machine->routeProcesses as $proc) {
                                    $machineHours += (int)($proc->cycle_hours ?? 0);
                                    $machineMinutes += (int)($proc->cycle_minutes ?? 0);
                                }
                            }
                            $machineHours += floor($machineMinutes / 60);
                            $machineMinutes = $machineMinutes % 60;
                            $isActive = $processCount > 0;
                        @endphp
                        <tr class="text-center">
                            <td>{{ $machine->machine_id }}</td>
                            <td class="text-left">{{ $machine->machine_name ?? '-' }}</td>
                            <td>{{ $machine->machine_sl_no ?? '-' }}</td>
                            <td>{{ $machine->make ?? '-' }}</td>
                            <td>{{ $machine->model_type ?? '-' }}</td>
                            <td>
                                @if($processCount > 0)
                                    <span class="badge badge-primary">{{ $processCount }}</span>
                                @else
                                    <span class="badge badge-secondary">0</span>
                                @endif
                            </td>
                            <td>
                                @if($machineHours > 0 || $machineMinutes > 0)
                                    <span class="badge badge-info">{{ $machineHours }}h {{ $machineMinutes }}m</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($isActive)
                                    <span class="badge badge-success">Active</span>
                                @else
                                    <span class="badge badge-warning">Idle</span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Active & Idle Machine Summary -->
<div class="row">
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-check-circle mr-2"></i> Top Active Machines
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Machine</th>
                            <th class="text-center">Processes</th>
                            <th class="text-center">Total Cycle Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $topActiveMachines = $activeMachines->sortByDesc(fn($m) => $m->routeProcesses->count())->take(5);
                        @endphp
                        @forelse($topActiveMachines as $machine)
                            @php
                                $machineHours = 0;
                                $machineMinutes = 0;
                                foreach($machine->routeProcesses as $proc) {
                                    $machineHours += (int)($proc->cycle_hours ?? 0);
                                    $machineMinutes += (int)($proc->cycle_minutes ?? 0);
                                }
                                $machineHours += floor($machineMinutes / 60);
                                $machineMinutes = $machineMinutes % 60;
                            @endphp
                            <tr>
                                <td>{{ $machine->machine_name ?? $machine->machine_id }}</td>
                                <td class="text-center">
                                    <span class="badge badge-primary">{{ $machine->routeProcesses->count() }}</span>
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-info">{{ $machineHours }}h {{ $machineMinutes }}m</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">No active machines</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-exclamation-triangle mr-2"></i> Idle Machines (No Process)
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Machine</th>
                            <th>Serial No</th>
                            <th>Make / Model</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($idleMachines->take(5) as $machine)
                            <tr>
                                <td>{{ $machine->machine_name ?? $machine->machine_id }}</td>
                                <td>{{ $machine->machine_sl_no ?? '-' }}</td>
                                <td>{{ $machine->make ?? '-' }} / {{ $machine->model_type ?? '-' }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">All machines are active</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('#machineTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 25,
        responsive: true,
        order: [[0, 'asc']],
        language: {
            emptyTable: "No machine records found"
        }
    });

    // Export Excel logic
    $('#exportExcelBtn').click(function() {
        let form = $('#machineReportFilters');
        let originalAction = form.attr('action');
        let exportUrl = originalAction + (originalAction.includes('?') ? '&' : '?') + 'export=excel';
        window.location.href = exportUrl;
    });
});
</script>
@endsection
