@extends('layouts.dashboard.managerapp')

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

@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <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"><a href="#">UEPL</a> / Manufacturing Planning</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>

    <div class="row">
        <div class="col-lg-12">
            <div class="tab mb-2">
                <button class="tablinks active" data-tab="ReadyToPlan" onclick="openTab(event, 'ReadyToPlan')">Ready To
                    Plan</button>
                <button class="tablinks" data-tab="PlannedProjects" onclick="openTab(event, 'PlannedProjects')">Planned
                    Projects</button>
            </div>
            <div id="ReadyToPlan" class="tabcontent" style="display: -webkit-box;
    overflow-y: auto;">
                <div id="RCProjectBoxes" class="project-boxes d-flex flex-wrap"></div>
            </div>
            <div id="PlannedProjects" class="tabcontent" style="display:-webkit-box;  overflow-y: auto;">
                <div id="PlannedProjectBoxes" class="project-boxes d-flex flex-wrap justify-content-center text-secondary"
                    style="min-height:200px;align-items:center;">
                    <div style="font-size:1.1rem;">Planned Projects will appear here.</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast for notifications -->
    <div id="planToast" class="toast" style="position: fixed; top: 1rem; right: 1rem; min-width: 200px; z-index:9999;">
        <div class="toast-header">
            <strong class="mr-auto" id="planToastTitle">Notice</strong>
            <button type="button" class="ml-2 mb-1 close" onclick="$('#planToast').toast('hide');">&times;</button>
        </div>
        <div class="toast-body" id="planToastBody"></div>
    </div>
@endsection

@push('scripts')
    <!-- jQuery, Popper, Bootstrap JS for modals/toasts (skip if globally loaded) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- FontAwesome for icons (skip if already loaded) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />

    <script>
        function openTab(evt, tabName) {
            $('.tabcontent').hide();
            $('#' + tabName).show();
            $('.tablinks').removeClass('active');
            $(evt.currentTarget).addClass('active');
        }

        function showToast(msg, title = 'Notice') {
            $('#planToastTitle').text(title);
            $('#planToastBody').text(msg);
            $('#planToast').toast({
                delay: 2000
            });
            $('#planToast').toast('show');
        }

        function fetchApprovedRC() {
            fetch('{{ url('manager/routecard/approved') }}')
                .then(res => res.json())
                .then(data => renderApprovedRC(data));
        }

        function renderApprovedRC(cards) {
            let rcBox = $('#RCProjectBoxes');
            rcBox.html('');
            let color = '#dbf6fd';
            if (!cards.length) {
                rcBox.html(
                    '<div class="text-secondary py-4" style="font-size:1.1rem;">No approved Route Cards found.</div>');
            }
            cards.forEach(card => {
                let html = `
        <div class="project-box-wrapper mb-3" style="min-width:320px;max-width:380px;">
            <div class="project-box shadow-sm" style="background:${color};border-radius:22px;">
                <div class="project-box-header d-flex justify-content-between" style="align-items:center;">
                    <span class="project-date" style="font-size:1rem;">RC Date: ${formatDate(card.route_date) || ''}</span>
                    <div>
                        <a class="btn btn-sm btn-link text-primary" title="View" onclick="goToPlanPage(${card.id})">
                            <i class="fas fa-eye"></i>
                        </a>
                    </div>
                </div>
                <div class="project-box-content-header pb-0">
                    <p class="box-content-header mb-0 font-weight-bold" style="font-size:1.15rem;color:#329ad7;">${card.route_no}</p>
                    <p class="box-content-subheader mb-2" style="color:#90caf9;font-size:.95rem;">${card.company_name}</p>
                </div>
                <div class="box-progress-wrapper">
                    <p class="box-progress-header" style="font-weight:600;">Ready to plan</p>
                    <div class="box-progress-bar mb-2"><span class="box-progress" style="width:100%;background:#4287f5;height:4px;display:block;border-radius:2px;"></span></div>
                </div>
                <div class="mt-2" style="font-size: .97rem;">
                    <span style="color:#0a7d4b;font-weight:500;">Approved By:</span> 
                    <span style="color:#222;">${card.approved_by || 'Admin'}</span> <br>
                    <span style="color:#0a7d4b;font-weight:500;">On:</span>
                    <span style="color:#222;">${formatDate(card.approved_at) || ''}</span>
                </div>
                <div class="project-box-footer d-flex justify-content-between align-items-center mt-3" style="border:none;">
                    <button class="add-participant btn btn-light btn-sm" style="color: #ff942e;border-radius:50%;"><i class="fas fa-plus"></i></button>
                    <button class="btn btn-warning btn-sm" style="color:#fff;font-weight:600;" onclick="startPlanning(${card.id})">Create Plan</button>
                </div>
            </div>
        </div>
        `;
                rcBox.append(html);
            });
        }

        function startPlanning(rcId) {
            fetch(`{{ url('manager/routecard/plan') }}/${rcId}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                })
                .then(res => res.json())
                .then(resp => {
                    if (resp.success) {
                        showToast("Project moved to Planned Projects!");
                        fetchApprovedRC();
                        fetchPlannedRC();
                        // Switch to Planned Projects tab
                        openTab({
                            currentTarget: $('.tablinks[data-tab="PlannedProjects"]')[0]
                        }, 'PlannedProjects');
                        // Short delay (to show toast, update UI), then redirect to plan page
                        setTimeout(function() {
                            window.location.href = `{{ url('manager/manufacturing/plan') }}/${rcId}`;
                        }, 500); // You can adjust the delay as needed
                    } else {
                        showToast("Failed to move project!", "Error");
                    }
                });
        }


        function fetchPlannedRC() {
            fetch('{{ url('manager/routecard/planned') }}')
                .then(res => res.json())
                .then(data => renderPlannedRC(data));
        }

        function renderPlannedRC(cards) {
            let plannedBox = $('#PlannedProjectBoxes');
            plannedBox.html('');
            let color = '#e1fad6';
            if (!cards.length) {
                plannedBox.html(
                    '<div class="text-secondary py-4" style="font-size:1.1rem;">No planned projects yet.</div>');
            }
            cards.forEach(card => {
                let html = `
        <div class="project-box-wrapper mb-3" style="min-width:320px;max-width:380px;">
            <div class="project-box shadow-sm" style="background:${color};border-radius:22px;">
                <div class="project-box-header d-flex justify-content-between" style="align-items:center;">
                    <span class="project-date" style="font-size:1rem;">RC Date: ${formatDate(card.route_date) || ''}</span>
                    <a class="btn btn-sm btn-link text-primary" title="View" onclick="goToPlanPage(${card.id})">
                        <i class="fas fa-eye"></i>
                    </a>
                </div>
                <div class="project-box-content-header pb-0">
                    <p class="box-content-header mb-0 font-weight-bold" style="font-size:1.15rem;color:#329ad7;">${card.route_no}</p>
                    <p class="box-content-subheader mb-2" style="color:#90caf9;font-size:.95rem;">${card.company_name}</p>
                </div>
                <div class="box-progress-wrapper">
                    <p class="box-progress-header" style="font-weight:600;">Planned</p>
                    <div class="box-progress-bar mb-2"><span class="box-progress" style="width:100%;background:#60b85e;height:4px;display:block;border-radius:2px;"></span></div>
                </div>
                <div class="mt-2" style="font-size: .97rem;">
                    <span style="color:#0a7d4b;font-weight:500;">Planned By:</span>
                    <span style="color:#222;">${card.approved_by || 'Admin'}</span> <br>
                    <span style="color:#0a7d4b;font-weight:500;">On:</span>
                    <span style="color:#222;">${formatDate(card.approved_at) || ''}</span>
                </div>
                <div class="project-box-footer d-flex justify-content-between align-items-center mt-3" style="border:none;">
                    <button class="btn btn-success btn-sm" style="font-weight:600;" onclick="markReadyToProduction(${card.id})">
                        Ready to Production
                    </button>
                </div>
            </div>
        </div>
        `;
                plannedBox.append(html);
            });
        }

        function markReadyToProduction(cardId) {
            if (!confirm('Mark this project as Ready to Production and view Production Board?')) return;
            fetch(`{{ url('manager/routecard/ready-production') }}/${cardId}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                })
                .then(res => res.json())
                .then(resp => {
                    if (resp.success) {
                        showToast('Project marked as Ready to Production! Redirecting...');
                        fetchPlannedRC();
                        // Redirect after a short delay (for toast)
                        setTimeout(function() {
                            window.location.href = `{{ url('manager/ready-to-production') }}`;
                        }, 800); // 800ms delay to let user see the toast
                    } else {
                        showToast('Failed to update project!', 'Error');
                    }
                });
        }


        function goToPlanPage(id) {
            // Redirect to the detailed plan page (RC's scheduling board)
            window.location.href = `{{ url('manager/manufacturing/plan') }}/${id}`;
        }

        function formatDate(dateStr) {
            if (!dateStr) return '';
            const d = new Date(dateStr);
            if (isNaN(d.getTime())) return '';
            return d.toLocaleDateString('en-GB');
        }

        $(document).ready(function() {
            fetchApprovedRC();
            fetchPlannedRC();
            openTab({
                currentTarget: $('.tablinks')[0]
            }, 'ReadyToPlan');
        });
    </script>
    <style>
        .tab {
            margin-bottom: 1rem;
        }

        .tab button {
            background: #eee;
            border: none;
            outline: none;
            padding: 10px 20px;
            border-radius: 6px 6px 0 0;
        }

        .tab button.active {
            background: #4287f5;
            color: #fff;
        }

        .project-boxes {
            gap: 1.5rem;
        }

        .box-progress-bar {
            background: #e9ecef;
            border-radius: 2px;
        }

        .project-box {
            border-radius: 22px;
            padding: 1.2rem 1.4rem;
            background: #dbf6fd;
            box-shadow: 0 1px 6px 0 rgba(80, 102, 144, 0.06);
            min-width: 320px;
            max-width: 380px;
            transition: box-shadow 0.2s;
        }

        .project-box:hover {
            box-shadow: 0 4px 14px 0 rgba(80, 102, 144, 0.13);
        }

        .box-progress-header {
            color: #4287f5;
            font-weight: 600;
            font-size: 1.07rem;
        }

        .box-content-header {
            color: #329ad7;
        }

        .project-box-footer .btn {
            font-size: 0.95rem;
        }
    </style>
@endpush
