

<?php $__env->startSection('content'); ?>
<div class="min-h-screen bg-gray-50 flex flex-col font-sans pb-28">
  <main class="flex-1 max-w-2xl mx-auto w-full p-4 py-6 relative">
    
    <div class="flex items-center gap-3 mb-6">
      <div class="bg-[#109E38] p-2.5 rounded-xl shadow-md">
        <i data-lucide="briefcase" class="w-6 h-6 text-white"></i>
      </div>
      <div>
        <h1 class="text-2xl font-black text-gray-900">Job Center</h1>
        <p class="text-sm font-bold text-gray-500">Manage bookings & payments</p>
      </div>
    </div>

    <div class="flex overflow-x-auto hide-scrollbar bg-white rounded-2xl p-1.5 shadow-sm border border-gray-100 mb-6 gap-1" id="tab-container">
      </div>

    <div id="jobs-container" class="space-y-5">
      </div>

  </main>

  <div id="otp-modal" class="hidden fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
    <div class="bg-white rounded-3xl p-6 w-full max-w-sm shadow-2xl">
      <h3 class="text-xl font-black mb-2">Start Work</h3>
      <p class="text-sm font-bold text-gray-500 mb-6">Ask customer for 4-digit OTP to start service.</p>
      <input type="text" id="otp-input" maxlength="4" placeholder="Enter OTP" class="w-full h-14 border-2 border-gray-200 rounded-xl px-4 text-center text-2xl font-black tracking-widest mb-4 focus:border-[#109E38] outline-none" />
      <div class="flex gap-3">
        <button onclick="closeOtpModal()" class="flex-1 h-12 bg-gray-100 font-black rounded-xl text-gray-600">Cancel</button>
        <button onclick="verifyOtp()" class="flex-1 h-12 bg-[#109E38] text-white font-black rounded-xl shadow-md">Verify</button>
      </div>
    </div>
  </div>

  <div id="bill-modal" class="hidden fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex flex-col items-center justify-end md:justify-center p-0 md:p-4">
    <div class="bg-white rounded-t-3xl md:rounded-3xl p-6 w-full max-w-md shadow-2xl h-[85vh] flex flex-col transition-transform transform translate-y-full" id="bill-modal-content">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-xl font-black text-gray-900">Add Parts</h3>
        <button onclick="closeBillModal()"><i data-lucide="x-circle" class="w-6 h-6 text-gray-400"></i></button>
      </div>
      <div class="flex-1 overflow-y-auto pr-2 space-y-6 hide-scrollbar" id="inventory-list">
        </div>
      <button onclick="closeBillModal()" class="w-full h-14 bg-gray-900 text-white font-black rounded-xl mt-4 shadow-lg">Done</button>
    </div>
  </div>

  <style>
    .hide-scrollbar::-webkit-scrollbar { display: none; }
    .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
  </style>

  <script>
    // DATA STORE
    const INVENTORY = [
      { id: 's1', category: 'Service & Inspection', name: 'Foam-Jet Wash (Split AC)', price: 499 },
      { id: 's3', category: 'Service & Inspection', name: 'Inspection / Visit Charge', price: 299 },
      { id: 'g1', category: 'Gas Refill & Repair', name: 'Gas Charging (R32/R410)', price: 2200 },
      { id: 'e1', category: 'Electrical Parts', name: 'Capacitor (45/50 MFD)', price: 450 },
    ];

    let activeTab = localStorage.getItem("instafix_tab") || "new";
    let activeJobForOtp = null;
    let activeJobForBill = null;

    // 🚀 ASALI DATABASE WALI JOBS (Laravel se aa rahi hain) 🚀
    let jobs = <?php echo json_encode($jobsData, 15, 512) ?>;

    // INITIALIZATION
    document.addEventListener("DOMContentLoaded", () => {
        renderTabs();
        renderJobs();
        renderInventory();
        lucide.createIcons();
    });

    // RENDER TABS
    function renderTabs() {
        const tabs = ["new", "ongoing", "pending", "completed"];
        const container = document.getElementById('tab-container');
        container.innerHTML = tabs.map(tab => {
            const isActive = activeTab === tab;
            let activeClass = "bg-gray-900 text-white";
            if (isActive) {
                if(tab === "new") activeClass = "bg-[#109E38] text-white";
                if(tab === "ongoing") activeClass = "bg-blue-600 text-white";
                if(tab === "pending") activeClass = "bg-orange-500 text-white";
            }
            return `<button onclick="changeTab('${tab}')" class="capitalize whitespace-nowrap px-4 py-2.5 text-sm font-black rounded-xl transition-all ${isActive ? activeClass : "text-gray-500 hover:bg-gray-50"}">${tab}</button>`;
        }).join('');
    }

    function changeTab(tab) {
        activeTab = tab;
        localStorage.setItem("instafix_tab", tab);
        renderTabs();
        renderJobs();
    }

    // RENDER JOBS
    function renderJobs() {
        const container = document.getElementById('jobs-container');
        const displayJobs = jobs.filter(j => j.status === activeTab);

        if (displayJobs.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12 bg-white rounded-3xl border border-dashed border-gray-200">
                    <i data-lucide="alert-circle" class="w-12 h-12 text-gray-300 mx-auto mb-3"></i>
                    <h3 class="text-gray-500 font-black">No jobs here</h3>
                </div>`;
            lucide.createIcons();
            return;
        }

        container.innerHTML = displayJobs.map(job => {
            const totalBill = job.billItems.reduce((sum, item) => sum + item.price, 0);
            const isOnline = job.paymentMode === 'online';
            
            // Tag logic
            const tagClass = isOnline ? 'bg-purple-100 text-purple-700' : 'bg-green-100 text-green-700';
            const tagIcon = isOnline ? 'credit-card' : 'indian-rupee';
            const tagText = isOnline ? 'Online Paid' : 'Cash Job';

            // Bill Section
            let billHtml = '';
            if (job.subStatus === 'started' || job.status === 'completed' || job.status === 'pending') {
                const addPartBtn = job.status !== 'completed' ? `<button onclick="openBillModal('${job.id}')" class="text-xs font-bold bg-white text-blue-600 px-2 py-1 rounded-lg border border-blue-200 shadow-sm">+ Add Parts</button>` : '';
                
                const itemsList = job.billItems.map(item => `<li class="text-xs font-bold text-gray-600 flex justify-between"><span>• ${item.name}</span> <span>₹${item.price}</span></li>`).join('');
                
                let paymentAlert = '';
                if(job.status === 'ongoing' && !isOnline) {
                    paymentAlert = `<div class="mt-3 bg-red-100 text-red-700 p-2 rounded-xl text-center text-xs font-black uppercase tracking-wider border border-red-200">⚠️ Collect ₹${totalBill} Cash</div>`;
                } else if(job.status === 'ongoing' && isOnline) {
                    paymentAlert = `<div class="mt-3 bg-green-100 text-green-700 p-2 rounded-xl text-center text-xs font-black uppercase tracking-wider border border-green-200">✅ Online Paid</div>`;
                }

                billHtml = `
                    <div class="mb-5 bg-blue-50 border border-blue-100 rounded-2xl p-4">
                       <div class="flex justify-between items-center mb-2">
                         <h4 class="text-sm font-black text-blue-900">Final Bill</h4>
                         ${addPartBtn}
                       </div>
                       <ul class="space-y-1 mb-2">${itemsList}</ul>
                       <div class="flex justify-between items-center border-t border-blue-200 pt-2 mt-2">
                         <span class="text-sm font-black text-gray-900">Total Amount:</span>
                         <span class="text-xl font-black text-[#109E38]">₹${totalBill}</span>
                       </div>
                       ${paymentAlert}
                    </div>`;
            }

            // Action Buttons
            let actionHtml = '';
            if (job.status === 'new') {
                actionHtml = `
                    <div class="flex gap-3">
                      <button onclick="alert('Job Rejected')" class="flex-1 h-12 rounded-xl bg-gray-100 text-gray-500 font-black">Pass</button>
                      <button onclick="acceptJob('${job.id}')" class="flex-[2] h-12 rounded-xl bg-[#109E38] text-white font-black shadow-md">Accept</button>
                    </div>`;
            } else if (job.status === 'ongoing') {
                if (job.subStatus === 'assigned') actionHtml = `<button onclick="updateJob('${job.id}', 'ongoing', 'on_the_way')" class="w-full h-12 rounded-xl bg-blue-500 text-white font-black shadow-md">Mark On The Way</button>`;
                if (job.subStatus === 'on_the_way') actionHtml = `<button onclick="openOtpModal('${job.id}')" class="w-full h-12 rounded-xl bg-yellow-500 text-white font-black shadow-md">Arrived - Enter OTP</button>`;
                if (job.subStatus === 'started') actionHtml = `
                    <div class="flex gap-2">
                        <button onclick="updateJob('${job.id}', 'pending', 'started')" class="flex-1 h-12 rounded-xl bg-orange-50 text-orange-600 text-xs font-black border border-orange-200">Pause (Part needed)</button>
                        <button onclick="completeJob('${job.id}')" class="flex-1 h-12 rounded-xl bg-[#109E38] text-white text-xs font-black shadow-md">Complete Job</button>
                    </div>`;
            } else if (job.status === 'pending') {
                actionHtml = `<button onclick="updateJob('${job.id}', 'ongoing', 'started')" class="w-full h-12 rounded-xl bg-[#109E38] text-white font-black shadow-md">Resume Work</button>`;
            }

            return `
                <div class="bg-white rounded-3xl p-5 shadow-lg border border-gray-100 relative overflow-hidden">
                  <div class="absolute top-0 right-0 text-[10px] font-black px-3 py-1 rounded-bl-xl uppercase tracking-wider flex items-center gap-1 ${tagClass}">
                    <i data-lucide="${tagIcon}" class="w-3 h-3"></i> ${tagText}
                  </div>
                  <div class="mb-4 mt-2">
                    <h3 class="text-lg font-black text-gray-900">${job.billItems[0]?.name || "AC Service"}</h3>
                    <p class="text-xs font-bold text-gray-400">ID: ${job.id}</p>
                  </div>
                  <div class="bg-gray-50 rounded-2xl p-4 space-y-3 mb-5 border border-gray-100">
                    <p class="text-sm font-bold text-gray-700 flex items-center gap-3"><i data-lucide="user" class="w-4 h-4 text-gray-400"></i> ${job.customer}</p>
                    <p class="text-sm font-bold text-gray-700 flex items-start gap-3"><i data-lucide="map-pin" class="w-4 h-4 text-gray-400 shrink-0 mt-0.5"></i> <span>${job.address}</span></p>
                  </div>
                  ${billHtml}
                  ${actionHtml}
                </div>`;
        }).join('');
        lucide.createIcons();
    }

    // 🚀 ACTIONS (DATABASE SE JODA HUA) 🚀
    function updateJob(id, status, subStatus) {
        // 1. Pehle screen par instantly job ko move karo (Fast UI)
        jobs = jobs.map(j => j.id === id ? { ...j, status, subStatus } : j);

        // 2. Background mein Database API ko call lagao (Asali save)
        fetch(`/api/update-job/${id}/${status}`)
            .then(response => response.json())
            .then(data => {
                console.log("Database updated successfully!", data);
            })
            .catch(error => console.error("Database update failed:", error));

        // 3. Tab change karo
        if(status === 'pending') changeTab('pending');
        else renderJobs();
    }

    function acceptJob(id) {
        alert("Job Accepted!");
        updateJob(id, "ongoing", "assigned");
        changeTab("ongoing");
    }

    function completeJob(id) {
        const job = jobs.find(j => j.id === id);
        const total = job.billItems.reduce((sum, i) => sum + i.price, 0);
        if(job.paymentMode === 'cash') alert(`Job Completed! Collect ₹${total} CASH.`);
        else alert(`Job Completed! Online Payment already received.`);
        
        updateJob(id, "completed", "completed");
        changeTab("completed");
    }

    // OTP MODAL
    function openOtpModal(id) {
        activeJobForOtp = id;
        document.getElementById('otp-modal').classList.remove('hidden');
    }
    function closeOtpModal() {
        document.getElementById('otp-modal').classList.add('hidden');
        document.getElementById('otp-input').value = "";
    }
    function verifyOtp() {
        const input = document.getElementById('otp-input').value;
        const job = jobs.find(j => j.id === activeJobForOtp);
        if(job.otp === input) {
            alert("OTP Verified! Work Started.");
            updateJob(activeJobForOtp, "ongoing", "started");
            closeOtpModal();
        } else {
            alert("Galat OTP! Customer se dubara puchiye.");
        }
    }

    // INVENTORY & BILL MODAL
    function renderInventory() {
        const categories = [...new Set(INVENTORY.map(i => i.category))];
        const container = document.getElementById('inventory-list');
        container.innerHTML = categories.map(cat => {
            const items = INVENTORY.filter(i => i.category === cat).map(part => `
                <div onclick="addPart('${part.id}')" class="flex justify-between items-center p-3 rounded-xl mb-2 border border-gray-100 hover:border-[#109E38] cursor-pointer bg-white">
                  <div><p class="text-sm font-bold text-gray-700">${part.name}</p><p class="text-xs font-black text-gray-500">₹${part.price}</p></div>
                  <button class="text-[#109E38] bg-green-50 p-1.5 rounded-lg border border-green-100"><i data-lucide="plus-circle" class="w-4 h-4"></i></button>
                </div>`).join('');
            return `
                <div class="mb-6">
                  <h5 class="text-[10px] font-black text-[#109E38] bg-green-50 uppercase px-3 py-1.5 rounded-md inline-block mb-3 border border-green-100">${cat}</h5>
                  ${items}
                </div>`;
        }).join('');
    }

    function openBillModal(id) {
        activeJobForBill = id;
        const modal = document.getElementById('bill-modal');
        const content = document.getElementById('bill-modal-content');
        modal.classList.remove('hidden');
        setTimeout(() => content.classList.remove('translate-y-full'), 10);
    }

    function closeBillModal() {
        const modal = document.getElementById('bill-modal');
        const content = document.getElementById('bill-modal-content');
        content.classList.add('translate-y-full');
        setTimeout(() => modal.classList.add('hidden'), 300);
    }

    function addPart(partId) {
        const part = INVENTORY.find(i => i.id === partId);
        jobs = jobs.map(j => {
            if (j.id === activeJobForBill) {
                if (j.billItems.find(i => i.id === part.id)) {
                    alert("Part already added!");
                    return j;
                }
                alert(`${part.name} added.`);
                return { ...j, billItems: [...j.billItems, part] };
            }
            return j;
        });
        renderJobs();
    }
  </script>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.tech', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\Users\Asus\OneDrive\Documents\instafix24-app\resources\views/technician/track.blade.php ENDPATH**/ ?>