@extends('layouts.admin')

@section('title', 'Machine Shifts')
@section('page-title', 'Machine Shifts')

@push('admin-styles')
    .session-status-running { background:rgba(16,185,129,.1); color:#059669; }
    .session-status-paused  { background:rgba(217,119,6,.1); color:#d97706; }
    .session-status-stopped { background:rgba(239,68,68,.1); color:#dc2626; }
    .btn-view {
        background: linear-gradient(135deg, #007870, #00a396);
        color: #fff;
        border: none;
        border-radius: 8px;
        padding: 6px 14px;
        font-size: .78rem;
        font-weight: 600;
        transition: all .2s ease;
        text-decoration: none;
    }
    .btn-view:hover { box-shadow: 0 4px 12px rgba(0,120,112,.3); color: #fff; transform: translateY(-1px); }
    .btn-delete {
        background: rgba(239,68,68,.1);
        color: #dc2626;
        border: none;
        border-radius: 8px;
        padding: 6px 12px;
        font-size: .78rem;
        font-weight: 600;
        transition: all .2s ease;
        cursor: pointer;
    }
    .btn-delete:hover { background: #dc2626; color: #fff; transform: translateY(-1px); }
    .btn-export {
        background: rgba(26,115,232,.1);
        color: #1a73e8;
        border: none;
        border-radius: 8px;
        padding: 6px 12px;
        font-size: .78rem;
        font-weight: 600;
        transition: all .2s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }
    .btn-export:hover { background: #1a73e8; color: #fff; transform: translateY(-1px); }
    .btn-email {
        background: rgba(16,185,129,.1);
        color: #059669;
        border: none;
        border-radius: 8px;
        padding: 6px 12px;
        font-size: .78rem;
        font-weight: 600;
        transition: all .2s ease;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }
    .btn-email:hover { background: #059669; color: #fff; transform: translateY(-1px); }
    .btn-email:disabled { opacity: .6; cursor: not-allowed; transform: none; }
    /* Export panel */
    .export-panel {
        padding: 16px 20px; border-radius: 12px;
        background: rgba(0,120,112,.06); border: 1px solid rgba(0,120,112,.15);
        margin-bottom: 16px;
    }
    .export-panel-header { display:flex; align-items:center; gap:8px; margin-bottom:12px; }
    .export-panel-header .ep-title { font-size:.8rem; font-weight:700; color:#007870; }
    .period-tabs { display:flex; gap:4px; background:#fff; border:1px solid #e5e7eb; border-radius:8px; padding:3px; }
    .period-tab {
        border: none; background: transparent; border-radius: 6px;
        padding: 5px 14px; font-size:.78rem; font-weight:600; color:#6b7280;
        cursor: pointer; transition: all .15s ease; white-space: nowrap;
    }
    .period-tab.active { background: #007870; color: #fff; box-shadow: 0 2px 6px rgba(0,120,112,.3); }
    .period-tab:not(.active):hover { background: rgba(0,120,112,.08); color: #007870; }
    .export-fields { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
    .export-fields select, .export-fields input[type="date"] {
        border: 1px solid #d1d5db; border-radius: 8px; padding: 5px 10px;
        font-size: .82rem; background: #fff; color: #1a1a2e; cursor: pointer;
        height: 34px;
    }
    .btn-excel {
        background: linear-gradient(135deg, #007870, #00a396);
        color: #fff; border: none; border-radius: 8px;
        padding: 6px 16px; font-size: .82rem; font-weight: 600;
        display: inline-flex; align-items: center; gap: 6px; height: 34px;
        cursor: pointer; transition: all .2s ease; text-decoration: none;
    }
    .btn-excel:hover { box-shadow: 0 4px 12px rgba(0,120,112,.35); color: #fff; transform: translateY(-1px); }
    .export-hint { font-size:.72rem; color:#9ca3af; }
    /* Toast */
    #email-toast-container { position:fixed; bottom:24px; right:24px; z-index:9999; display:flex; flex-direction:column; gap:10px; }
    .email-toast {
        min-width:280px; max-width:360px; padding:14px 18px;
        border-radius:12px; box-shadow:0 8px 24px rgba(0,0,0,.14);
        font-size:.85rem; font-weight:600; display:flex; align-items:center; gap:10px;
        animation: slideIn .25s ease;
    }
    .email-toast.success { background:#ecfdf5; color:#065f46; border-left:4px solid #059669; }
    .email-toast.error   { background:#fef2f2; color:#991b1b; border-left:4px solid #dc2626; }
    @keyframes slideIn { from { opacity:0; transform:translateX(40px); } to { opacity:1; transform:translateX(0); } }
@endpush

@section('content')
<div class="premium-card overflow-hidden">
    <div class="p-4 pb-0 d-flex justify-content-between align-items-center">
        <div>
            <h6 class="fw-bold mb-1">All Machine Shifts</h6>
            <p class="text-muted small mb-0">Complete production session history</p>
        </div>
        <span class="badge rounded-pill px-3 py-2" style="background:#f0f2f5; color:#6b7280; font-weight:600;">
            {{ $sessions->total() }} records
        </span>
    </div>
    {{-- Excel Export Panel --}}
    <div class="px-4 pt-3">
        <form action="{{ route('admin.sessions.export') }}" method="GET" id="export-form">
            <input type="hidden" name="period" id="period-input" value="daily">
            <div class="export-panel">
                <div class="export-panel-header">
                    <i class="bi bi-file-earmark-spreadsheet" style="color:#007870; font-size:1rem;"></i>
                    <span class="ep-title">Export Shifts Report</span>
                    <span class="export-hint ms-2">3 sheets: Shifts · Pauses · Product Segments</span>
                </div>
                <div class="d-flex align-items-center gap-3 flex-wrap">
                    {{-- Period tabs --}}
                    <div class="period-tabs">
                        <button type="button" class="period-tab active" data-period="daily">Daily</button>
                        <button type="button" class="period-tab" data-period="weekly">Weekly</button>
                        <button type="button" class="period-tab" data-period="monthly">Monthly</button>
                    </div>

                    {{-- Daily fields --}}
                    <div class="export-fields" id="fields-daily">
                        <input type="date" name="date" id="export-date" value="{{ now()->format('Y-m-d') }}">
                    </div>

                    {{-- Weekly fields --}}
                    <div class="export-fields d-none" id="fields-weekly">
                        <select name="week" id="export-week">
                            @for($w = 1; $w <= 53; $w++)
                                <option value="{{ $w }}" {{ $w == now()->isoWeek() ? 'selected' : '' }}>
                                    Week {{ $w }}
                                </option>
                            @endfor
                        </select>
                        <select name="year" id="export-year-w">
                            @foreach(range(now()->year, 2024, -1) as $y)
                                <option value="{{ $y }}" {{ $y == now()->year ? 'selected' : '' }}>{{ $y }}</option>
                            @endforeach
                        </select>
                    </div>

                    {{-- Monthly fields --}}
                    <div class="export-fields d-none" id="fields-monthly">
                        <select name="month" id="export-month">
                            @foreach(range(1, 12) as $m)
                                <option value="{{ $m }}" {{ $m == now()->month ? 'selected' : '' }}>
                                    {{ \Carbon\Carbon::create()->month($m)->format('F') }}
                                </option>
                            @endforeach
                        </select>
                        <select name="year" id="export-year-m">
                            @foreach(range(now()->year, 2024, -1) as $y)
                                <option value="{{ $y }}" {{ $y == now()->year ? 'selected' : '' }}>{{ $y }}</option>
                            @endforeach
                        </select>
                    </div>

                    <button type="submit" class="btn-excel">
                        <i class="bi bi-download"></i>Download Excel
                    </button>
                </div>
            </div>
        </form>
    </div>

    <div class="table-responsive mt-0">
        <table class="table align-middle mb-0" style="font-size:.85rem;">
            <thead>
                <tr style="background:#f8f9fb;">
                    <th class="text-muted fw-semibold ps-4" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">#</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Product</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Operator</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Start Time</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Duration</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Case</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Status</th>
                    <th class="text-muted fw-semibold" style="font-size:.72rem; text-transform:uppercase; letter-spacing:.5px;">Action</th>
                </tr>
            </thead>
            <tbody>
                @forelse($sessions as $session)
                    <tr style="border-bottom:1px solid #f0f2f5;">
                        <td class="text-muted ps-4">{{ $session->id }}</td>
                        <td class="fw-semibold">
                            {{ $session->product_name }}
                            @if($session->segments_count > 1)
                                <span class="badge rounded-pill ms-1" style="background:rgba(26,115,232,.1); color:#1a73e8; font-size:.65rem; font-weight:600;">
                                    {{ $session->segments_count }} products
                                </span>
                            @endif
                        </td>
                        <td>{{ $session->operator->name ?? '—' }}</td>
                        <td>
                            @if($session->start_time)
                                <div>{{ $session->start_time->format('d M Y') }}</div>
                                <small class="text-muted">{{ $session->start_time->format('h:i:s A') }}</small>
                            @else
                                —
                            @endif
                        </td>
                        <td>
                            @if($session->total_duration > 0)
                                <code style="background:#f0f2f5; padding:4px 10px; border-radius:6px; color:#1a1a2e; font-size:.82rem;">
                                    {{ gmdate('H:i:s', $session->total_duration) }}
                                </code>
                            @else
                                <span class="text-muted">—</span>
                            @endif
                        </td>
                        <td>
                            @if($session->case_number_history && str_contains($session->case_number_history, '+'))
                                {{ $session->case_number_history }} = {{ $session->case_number }}
                            @else
                                {{ $session->case_number ?? '—' }}
                            @endif
                        </td>
                        <td>
                            @if($session->status === 'running')
                                <span class="badge rounded-pill px-3 py-1 session-status-running fw-semibold">
                                    <i class="bi bi-play-fill me-1"></i>Running
                                </span>
                            @elseif($session->status === 'paused')
                                <span class="badge rounded-pill px-3 py-1 session-status-paused fw-semibold">
                                    <i class="bi bi-pause-fill me-1"></i>Paused
                                </span>
                            @else
                                <span class="badge rounded-pill px-3 py-1 session-status-stopped fw-semibold">
                                    <i class="bi bi-stop-fill me-1"></i>Stopped
                                </span>
                            @endif
                        </td>
                        <td>
                            <div class="d-flex gap-2">
                                <a href="{{ route('admin.sessions.show', $session) }}" class="btn-view">
                                    <i class="bi bi-eye me-1"></i>View
                                </a>
                                @if($session->status === 'stopped')
                                <a href="{{ route('admin.sessions.export-pdf', $session) }}" class="btn-export" title="Export PDF Report">
                                    <i class="bi bi-file-earmark-pdf"></i>PDF
                                </a>
                                @if($session->operator && $session->operator->email)
                                <button type="button" class="btn-email btn-send-email"
                                    data-url="{{ route('admin.sessions.send-email', $session) }}"
                                    data-email="{{ $session->operator->email }}"
                                    title="Send report to {{ $session->operator->email }}">
                                    <i class="bi bi-envelope"></i>Email
                                </button>
                                @endif
                                @endif
                                <form action="{{ route('admin.sessions.destroy', $session) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this session?');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn-delete">
                                        <i class="bi bi-trash3"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="8" class="text-center text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2" style="opacity:.3;"></i>
                            No machine shifts recorded yet.
                        </td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </div>
    @if($sessions->hasPages())
        <div class="p-3 d-flex justify-content-center border-top">
            {{ $sessions->links() }}
        </div>
    @endif
</div>
@endsection

@push('admin-scripts')
<div id="email-toast-container"></div>
<script>
/* --- Period tab switching --- */
(function() {
    var tabs      = document.querySelectorAll('.period-tab');
    var allFields = ['daily', 'weekly', 'monthly'];

    tabs.forEach(function(tab) {
        tab.addEventListener('click', function() {
            var period = this.dataset.period;

            // Update hidden input
            document.getElementById('period-input').value = period;

            // Update active tab
            tabs.forEach(function(t) { t.classList.remove('active'); });
            this.classList.add('active');

            // Show correct fields, hide others
            allFields.forEach(function(p) {
                var el = document.getElementById('fields-' + p);
                if (p === period) {
                    el.classList.remove('d-none');
                } else {
                    el.classList.add('d-none');
                }
            });

            // Disable inputs in hidden panels so they don't get submitted
            allFields.forEach(function(p) {
                var el = document.getElementById('fields-' + p);
                el.querySelectorAll('input, select').forEach(function(inp) {
                    inp.disabled = (p !== period);
                });
            });
        });
    });

    // On load: disable weekly and monthly fields (daily is default)
    ['weekly', 'monthly'].forEach(function(p) {
        document.getElementById('fields-' + p).querySelectorAll('input, select').forEach(function(inp) {
            inp.disabled = true;
        });
    });
})();

/* --- Email send buttons --- */
document.querySelectorAll('.btn-send-email').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var url   = this.dataset.url;
        var email = this.dataset.email;
        var self  = this;

        self.disabled = true;
        self.innerHTML = '<span class="spinner-border spinner-border-sm" style="width:.8rem;height:.8rem;"></span> Sending…';

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            showEmailToast(data.success, data.message);
        })
        .catch(function() {
            showEmailToast(false, 'Unexpected error. Please try again.');
        })
        .finally(function() {
            self.disabled = false;
            self.innerHTML = '<i class="bi bi-envelope"></i>Email';
        });
    });
});

function showEmailToast(success, message) {
    var container = document.getElementById('email-toast-container');
    var toast = document.createElement('div');
    toast.className = 'email-toast ' + (success ? 'success' : 'error');
    toast.innerHTML = '<i class="bi ' + (success ? 'bi-check-circle-fill' : 'bi-x-circle-fill') + '"></i>'
                    + '<span>' + message + '</span>';
    container.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 5000);
}
</script>
@endpush
