<?php require APPROOT . '/app/Views/layouts/header.php'; ?>

<div class="max-w-4xl mx-auto mb-10 space-y-6">

    <!-- Header & Status -->
    <div class="flex flex-col md:flex-row justify-between items-center bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700/50 p-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white font-mono"><?php echo htmlspecialchars($data['jobcard']->jobcard_number); ?></h1>
            <p class="text-sm text-gray-500">Client: <strong class="text-primary"><?php echo htmlspecialchars($data['jobcard']->client_name); ?></strong></p>
        </div>
        <div class="mt-4 md:mt-0 flex items-center space-x-4">
            <!-- LIVE TIMER UI -->
            <div id="live-timer-container" class="<?php echo ($data['jobcard']->status === 'Started') ? 'flex' : 'hidden'; ?> items-center text-red-500 font-mono font-bold text-lg bg-red-50 dark:bg-red-900/10 border border-red-200 dark:border-red-800/30 px-4 py-1.5 rounded-lg shadow-inner">
                <span class="animate-pulse mr-2">●</span> <span id="timer-display">00:00:00</span>
            </div>
            
            <span class="px-3 py-1.5 text-xs font-bold uppercase tracking-wider rounded border bg-gray-100 text-gray-700 border-gray-200 dark:bg-gray-900 dark:text-gray-300 dark:border-gray-700">
                Status: <?php echo $data['jobcard']->status; ?>
            </span>
        </div>
    </div>

    <!-- Instructions Block -->
    <div class="bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-800/30 rounded-xl p-6 shadow-sm">
        <h3 class="text-sm font-bold text-blue-900 dark:text-blue-300 mb-2 uppercase tracking-wider">Work Instructions</h3>
        <p class="text-blue-800 dark:text-blue-200/80 leading-relaxed whitespace-pre-wrap"><?php echo htmlspecialchars($data['jobcard']->instructions); ?></p>
    </div>

    <?php if ($data['jobcard']->status === 'Assigned'): ?>
        <!-- START ACTION -->
        <form action="<?php echo URLROOT; ?>/staff/startTimer/<?php echo $data['jobcard']->id; ?>" method="POST" onsubmit="confirmAction(event, this, 'Start Job', 'Are you on-site and ready to begin? This will start the time tracker.');">
            <button type="submit" class="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-4 rounded-xl shadow-lg transition-all text-lg">
                Arrived On-Site (Start Timer)
            </button>
        </form>
    <?php endif; ?>

    <?php if (in_array($data['jobcard']->status, ['Completed', 'Signed Off'])): ?>
    <!-- Operational Timeline -->
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700/50 p-6">
        <h3 class="text-sm font-bold text-gray-900 dark:text-white uppercase tracking-wider mb-4 border-b border-gray-200 dark:border-gray-700/50 pb-2">Operational Timeline</h3>
        <div class="space-y-4">
            <div class="flex justify-between items-center">
                <span class="text-xs font-bold text-gray-500 uppercase tracking-wider">Started</span>
                <span class="text-gray-900 dark:text-white font-medium text-sm font-mono"><?php echo $data['jobcard']->started_at ? date('M j, Y - H:i', strtotime($data['jobcard']->started_at)) : '<span class="text-gray-400 italic">Not started</span>'; ?></span>
            </div>
            <div class="flex justify-between items-center">
                <span class="text-xs font-bold text-gray-500 uppercase tracking-wider">Completed</span>
                <span class="text-gray-900 dark:text-white font-medium text-sm font-mono"><?php echo $data['jobcard']->completed_at ? date('M j, Y - H:i', strtotime($data['jobcard']->completed_at)) : '<span class="text-gray-400 italic">Not completed</span>'; ?></span>
            </div>
            <?php 
            $duration = '<span class="text-gray-400 italic">Not completed</span>';
            if (!empty($data['jobcard']->started_at) && !empty($data['jobcard']->completed_at)) {
                $start = new DateTime($data['jobcard']->started_at);
                $end = new DateTime($data['jobcard']->completed_at);
                $diff = $start->diff($end);
                $hours = ($diff->days * 24) + $diff->h;
                $duration = $hours . 'h ' . $diff->i . 'm';
            }
            ?>
            <div class="flex justify-between items-center pt-2 border-t border-gray-100 dark:border-gray-700/50">
                <span class="text-xs font-bold text-gray-500 uppercase tracking-wider">Time On-Site</span>
                <span class="text-gray-900 dark:text-white font-medium text-sm font-mono"><?php echo $duration; ?></span>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($data['jobcard']->status === 'Started' || $data['jobcard']->status === 'Completed'): ?>
        <!-- MATERIALS BLOCK -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700/50 overflow-hidden">
            <div class="p-5 border-b border-gray-200 dark:border-gray-700/50 bg-gray-50 dark:bg-gray-900/40">
                <h3 class="text-sm font-bold text-gray-900 dark:text-white uppercase tracking-wider">Materials Used</h3>
            </div>
            
            <?php if ($data['jobcard']->status === 'Started'): ?>
                <div class="p-5 border-b border-gray-200 dark:border-gray-700/50">
                    <form action="<?php echo URLROOT; ?>/staff/addMaterial" method="POST" class="flex flex-col sm:flex-row gap-3">
                        <input type="hidden" name="jobcard_id" value="<?php echo $data['jobcard']->id; ?>">
                        <input type="text" name="material_name" placeholder="Item Name/Code" class="flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white outline-none" required>
                        <input type="text" name="quantity" placeholder="Qty" class="w-24 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white outline-none" required>
                        <button type="submit" class="bg-gray-800 dark:bg-gray-700 text-white px-4 py-2 rounded-lg font-bold hover:opacity-90 transition-colors whitespace-nowrap">Add</button>
                    </form>
                </div>
            <?php endif; ?>

            <ul class="divide-y divide-gray-100 dark:divide-gray-700/50">
                <?php foreach($data['materials'] as $mat): ?>
                    <li class="p-4 flex justify-between items-center hover:bg-gray-50 dark:hover:bg-gray-900/20">
                        <span class="text-sm font-medium text-gray-800 dark:text-gray-200"><?php echo htmlspecialchars($mat->material_name); ?> <span class="text-gray-400 ml-2">x<?php echo htmlspecialchars($mat->quantity); ?></span></span>
                        <?php if ($data['jobcard']->status === 'Started'): ?>
                            <form action="<?php echo URLROOT; ?>/staff/deleteMaterial/<?php echo $mat->id; ?>/<?php echo $data['jobcard']->id; ?>" method="POST" class="m-0">
                                <button type="submit" class="text-red-500 hover:text-red-700"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg></button>
                            </form>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
                <?php if(empty($data['materials'])): ?>
                    <li class="p-6 text-center text-sm text-gray-500 italic">No materials logged.</li>
                <?php endif; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($data['jobcard']->status === 'Started'): ?>
        <!-- WORK DONE FORM -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700/50 overflow-hidden">
            <div class="p-5 border-b border-gray-200 dark:border-gray-700/50 bg-gray-50 dark:bg-gray-900/40">
                <h3 class="text-sm font-bold text-gray-900 dark:text-white uppercase tracking-wider">Finalize Jobcard</h3>
            </div>
            <div class="p-6">
                <form action="<?php echo URLROOT; ?>/staff/completeJobcard/<?php echo $data['jobcard']->id; ?>" method="POST" onsubmit="confirmAction(event, this, 'Complete Job', 'Are you sure you are done? This will stop the timer and lock the materials.');">
                    <label class="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Detailed Work Done *</label>
                    <textarea name="work_done" rows="5" class="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white outline-none resize-y mb-4" required></textarea>
                    
                    <button type="submit" class="w-full bg-primary hover:opacity-90 text-white font-bold py-3 rounded-lg shadow-sm transition-all focus:ring-4 focus:ring-primary/50">
                        Stop Timer & Complete Job
                    </button>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($data['jobcard']->status === 'Completed'): ?>
        <!-- DIGITAL SIGNATURE ENGINE -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-yellow-300 dark:border-yellow-600/50 overflow-hidden ring-4 ring-yellow-50 dark:ring-yellow-900/10">
            <div class="p-5 border-b border-gray-200 dark:border-gray-700/50 bg-yellow-50 dark:bg-yellow-900/20">
                <h3 class="text-sm font-bold text-yellow-800 dark:text-yellow-400 uppercase tracking-wider">Required Signatures</h3>
            </div>
            <div class="p-6">
                <div class="bg-gray-50 dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 mb-6">
                    <p class="text-sm text-gray-800 dark:text-gray-200"><strong>Work Done:</strong> <?php echo nl2br(htmlspecialchars($data['jobcard']->work_done)); ?></p>
                </div>

                <form id="signatureForm" action="<?php echo URLROOT; ?>/staff/signoff/<?php echo $data['jobcard']->id; ?>" method="POST" class="space-y-8">
                    
                    <!-- Client Canvas -->
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <label class="text-xs font-bold text-gray-700 dark:text-gray-300 uppercase tracking-wider">Client Signature</label>
                            <button type="button" onclick="clearCanvas(clientCanvas)" class="text-xs text-red-500 hover:underline">Clear</button>
                        </div>
                        <input type="text" name="client_sign_name" value="<?php echo htmlspecialchars($data['jobcard']->client_name); ?>" placeholder="Print Client Name" class="w-full px-4 py-2.5 mb-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary outline-none transition-colors" required>

                        <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl bg-white touch-none">
                            <canvas id="clientCanvas" class="w-full h-48 rounded-xl cursor-crosshair"></canvas>
                        </div>
                        <input type="hidden" name="client_signature" id="clientSigInput">
                    </div>

                    <!-- Tech Canvas -->
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <label class="text-xs font-bold text-gray-700 dark:text-gray-300 uppercase tracking-wider">Technician Signature</label>
                            <button type="button" onclick="clearCanvas(techCanvas)" class="text-xs text-red-500 hover:underline">Clear</button>
                        </div>
                        <input type="text" name="tech_sign_name" value="<?php echo htmlspecialchars($data['jobcard']->tech_name); ?>" placeholder="Print Technician Name" class="w-full px-4 py-2.5 mb-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary outline-none transition-colors" required>

                        <div class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl bg-white touch-none">
                            <canvas id="techCanvas" class="w-full h-48 rounded-xl cursor-crosshair"></canvas>
                        </div>
                        <input type="hidden" name="tech_signature" id="techSigInput">
                    </div>

                    <button type="button" onclick="submitSignatures()" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-4 rounded-xl shadow-lg transition-all text-lg">
                        Sign Off & Generate PDF
                    </button>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($data['jobcard']->status === 'Signed Off'): ?>
        <div class="bg-green-50 dark:bg-green-900/10 border border-green-200 dark:border-green-800/30 rounded-xl p-6 text-center shadow-sm">
            <h3 class="text-lg font-bold text-green-800 dark:text-green-400 mb-2">Jobcard Finalized</h3>
            <p class="text-sm text-green-700 dark:text-green-500">This jobcard has been signed off. A PDF copy has been emailed to the client.</p>
        </div>
    <?php endif; ?>
</div>

<!-- Interactive Engine Logic -->
<script>
    // 1. LIVE TIMER LOGIC
    <?php if ($data['jobcard']->status === 'Started' && !empty($data['jobcard']->started_at)): ?>
        const startTime = new Date("<?php echo $data['jobcard']->started_at; ?>").getTime();
        
        function updateTimer() {
            const now = new Date().getTime();
            const diff = now - startTime;

            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((diff % (1000 * 60)) / 1000);

            document.getElementById("timer-display").innerHTML = 
                String(hours).padStart(2, '0') + ":" + 
                String(minutes).padStart(2, '0') + ":" + 
                String(seconds).padStart(2, '0');
        }

        setInterval(updateTimer, 1000);
        updateTimer();
    <?php endif; ?>

    // 2. CANVAS SIGNATURE API LOGIC
    <?php if ($data['jobcard']->status === 'Completed'): ?>
        let isDrawing = false;
        let clientCanvas = document.getElementById('clientCanvas');
        let techCanvas = document.getElementById('techCanvas');

        function initCanvas(canvas) {
            const ctx = canvas.getContext('2d');
            // Fix resolution scaling
            const rect = canvas.parentElement.getBoundingClientRect();
            canvas.width = rect.width;
            canvas.height = rect.height;
            
            ctx.lineWidth = 3;
            ctx.lineCap = 'round';
            ctx.strokeStyle = '#0f172a'; // Slate 900 ink

            const startPos = (e) => {
                isDrawing = true;
                ctx.beginPath();
                const pos = getPos(canvas, e);
                ctx.moveTo(pos.x, pos.y);
                e.preventDefault();
            };

            const draw = (e) => {
                if (!isDrawing) return;
                const pos = getPos(canvas, e);
                ctx.lineTo(pos.x, pos.y);
                ctx.stroke();
                e.preventDefault();
            };

            const stopPos = () => {
                isDrawing = false;
                ctx.closePath();
            };

            canvas.addEventListener('mousedown', startPos);
            canvas.addEventListener('mousemove', draw);
            canvas.addEventListener('mouseup', stopPos);
            canvas.addEventListener('mouseout', stopPos);

            canvas.addEventListener('touchstart', startPos, {passive: false});
            canvas.addEventListener('touchmove', draw, {passive: false});
            canvas.addEventListener('touchend', stopPos);
        }

        function getPos(canvas, e) {
            const rect = canvas.getBoundingClientRect();
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            const clientY = e.touches ? e.touches[0].clientY : e.clientY;

            return {
                x: clientX - rect.left,
                y: clientY - rect.top
            };
        }

        function clearCanvas(canvas) {
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }

        // Initialize both
        initCanvas(clientCanvas);
        initCanvas(techCanvas);

        // Resize handler
        window.addEventListener('resize', () => {
            initCanvas(clientCanvas);
            initCanvas(techCanvas);
        });

        function isCanvasBlank(canvas) {
            const blank = document.createElement('canvas');
            blank.width = canvas.width;
            blank.height = canvas.height;
            return canvas.toDataURL() === blank.toDataURL();
        }

        function submitSignatures() {
            if (isCanvasBlank(clientCanvas) || isCanvasBlank(techCanvas)) {
                alert("Both the Client and Technician must sign before finalizing.");
                return;
            }

            const clientNameField = document.querySelector('input[name="client_sign_name"]').value.trim();
            const techNameField = document.querySelector('input[name="tech_sign_name"]').value.trim();

            if (clientNameField === '' || techNameField === '') {
                alert("Please ensure both printed names are filled out.");
                return;
            }
            
            // Extract Base64 PNG data
            document.getElementById('clientSigInput').value = clientCanvas.toDataURL('image/png');
            document.getElementById('techSigInput').value = techCanvas.toDataURL('image/png');
            
            document.getElementById('signatureForm').submit();
        }
    <?php endif; ?>
</script>

<?php require APPROOT . '/app/Views/layouts/footer.php'; ?>