<?php $__env->startSection('page_title', 'Attendance & Daily Work'); ?>

<?php $__env->startSection('content'); ?>
<?php
    $hasStarted   = (bool) $session?->start_time;
    $hasStopped   = (bool) $session?->stop_time;
    $hasActiveLunch = $session?->lunchBreaks?->contains(fn ($l) => is_null($l->end_time)) ?? false;
    $isAbsent = $session && $session->is_absent && !$hasStarted;
    $cutoffDisplay = \Carbon\Carbon::parse($lastOfficeStartTimeStr)->format('h:i A');
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');

    .att-wrap { display: grid; gap: 20px; }

    /* ── Hero status bar ── */
    .att-hero {
        background: linear-gradient(135deg, #1e1b4b 0%, #312e81 45%, #4c1d95 100%);
        border-radius: 20px;
        padding: 28px 30px;
        color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 16px;
        position: relative;
        overflow: hidden;
    }
    .att-hero::before {
        content: '';
        position: absolute;
        width: 300px; height: 300px;
        background: rgba(255,255,255,.04);
        border-radius: 50%;
        top: -100px; right: -60px;
    }
    .att-hero::after {
        content: '';
        position: absolute;
        width: 150px; height: 150px;
        background: rgba(255,255,255,.06);
        border-radius: 50%;
        bottom: -50px; right: 120px;
    }
    .att-hero-left h2 { margin: 0 0 4px; font-size: 22px; font-weight: 800; }
    .att-hero-left p  { margin: 0; font-size: 13px; color: #c4b5fd; }
    .att-status-pill {
        display: inline-flex;
        align-items: center;
        gap: 7px;
        background: rgba(255,255,255,.12);
        backdrop-filter: blur(6px);
        border: 1px solid rgba(255,255,255,.2);
        padding: 9px 18px;
        border-radius: 999px;
        font-size: 13px;
        font-weight: 600;
    }
    .att-status-pill .dot {
        width: 9px; height: 9px;
        border-radius: 50%;
        animation: pulse 1.8s infinite;
    }
    .dot-active   { background: #4ade80; box-shadow: 0 0 0 0 rgba(74,222,128,.6); }
    .dot-idle     { background: #fbbf24; }
    .dot-absent   { background: #f87171; }
    .dot-done     { background: #a78bfa; animation: none; }
    @keyframes pulse {
        0%   { box-shadow: 0 0 0 0 rgba(74,222,128,.6); }
        70%  { box-shadow: 0 0 0 8px rgba(74,222,128,0); }
        100% { box-shadow: 0 0 0 0 rgba(74,222,128,0); }
    }

    /* ── KPI row ── */
    .att-kpi-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: 14px;
    }
    .att-kpi {
        background: #fff;
        border: 1px solid #e5eaf4;
        border-radius: 14px;
        padding: 18px 16px;
        text-align: center;
        transition: box-shadow .2s, transform .2s;
    }
    .att-kpi:hover { box-shadow: 0 8px 28px rgba(99,102,241,.12); transform: translateY(-2px); }
    .att-kpi .kpi-icon { font-size: 26px; margin-bottom: 8px; line-height: 1; }
    .att-kpi .kpi-val  { font-size: 20px; font-weight: 800; color: #1e1b4b; line-height: 1; }
    .att-kpi .kpi-lbl  { font-size: 11px; color: #6b7280; margin-top: 5px; font-weight: 500; text-transform: uppercase; letter-spacing: .5px; }

    /* ── Camera action cards ── */
    .att-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
    @media(max-width:680px) { .att-actions { grid-template-columns: 1fr; } }

    .att-cam-card {
        background: #fff;
        border: 1px solid #e5eaf4;
        border-radius: 18px;
        overflow: hidden;
        transition: box-shadow .2s;
    }
    .att-cam-card:hover { box-shadow: 0 10px 36px rgba(99,102,241,.1); }
    .att-cam-header {
        padding: 18px 20px 12px;
        display: flex;
        align-items: center;
        gap: 12px;
    }
    .cam-icon-wrap {
        width: 42px; height: 42px;
        border-radius: 12px;
        display: flex; align-items: center; justify-content: center;
        font-size: 20px;
        flex-shrink: 0;
    }
    .cam-start-icon { background: linear-gradient(135deg,#6366f1,#818cf8); }
    .cam-stop-icon  { background: linear-gradient(135deg,#ef4444,#f87171); }
    .cam-icon-wrap img, .cam-icon-wrap span { line-height: 1; }
    .att-cam-header h4 { margin: 0; font-size: 15px; font-weight: 700; color: #1f2937; }
    .att-cam-header p  { margin: 3px 0 0; font-size: 12px; color: #9ca3af; }
    .cam-preview-wrap { position: relative; background: #0f172a; margin: 0 0 0 0; }
    video.cam-preview { width: 100%; max-height: 200px; display: block; object-fit: cover; }
    .cam-overlay {
        position: absolute; inset: 0;
        display: flex; align-items: center; justify-content: center;
        flex-direction: column; gap: 6px;
        color: rgba(255,255,255,.4);
        font-size: 13px;
        pointer-events: none;
    }
    .cam-overlay-icon { font-size: 36px; }
    video.cam-preview.active + .cam-overlay { display: none; }
    .cam-footer { padding: 16px 20px; }
    .att-btn {
        width: 100%;
        padding: 13px 18px;
        border: none;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 700;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: opacity .2s, transform .15s, box-shadow .2s;
        position: relative;
        overflow: hidden;
    }
    .att-btn:not(:disabled):hover { opacity: .9; transform: translateY(-1px); box-shadow: 0 6px 20px rgba(0,0,0,.15); }
    .att-btn:not(:disabled):active { transform: translateY(0); }
    .att-btn:disabled { opacity: .5; cursor: not-allowed; }
    .att-btn-start { background: linear-gradient(135deg,#6366f1 0%,#8b5cf6 100%); color: #fff; }
    .att-btn-stop  { background: linear-gradient(135deg,#ef4444 0%,#dc2626 100%); color: #fff; }
    .att-btn-done  { background: #f0fdf4; color: #16a34a; border: 1px solid #bbf7d0; }
    .status-text   { margin-top: 8px; font-size: 12px; color: #6366f1; font-weight: 500; min-height: 18px; }

    /* ── Lunch card ── */
    .att-lunch-card {
        background: linear-gradient(135deg, #fffbeb, #fef3c7);
        border: 1px solid #fde68a;
        border-radius: 18px;
        padding: 22px 24px;
    }
    .att-lunch-header { display: flex; align-items: center; gap: 12px; margin-bottom: 18px; }
    .lunch-icon-wrap { width: 44px; height: 44px; border-radius: 12px; background: linear-gradient(135deg,#f59e0b,#fbbf24); display: flex; align-items: center; justify-content: center; font-size: 22px; }
    .att-lunch-header h4 { margin: 0; font-size: 15px; font-weight: 700; color: #92400e; }
    .att-lunch-header p  { margin: 3px 0 0; font-size: 12px; color: #b45309; }
    .lunch-btns { display: flex; gap: 10px; flex-wrap: wrap; }
    .att-btn-lunch-start { background: #f59e0b; color: #fff; flex: 1; min-width: 120px; }
    .att-btn-lunch-end   { background: #fff; color: #92400e; border: 2px solid #fde68a; flex: 1; min-width: 120px; }
    .att-btn-lunch-start:not(:disabled):hover { background: #d97706; }
    .att-btn-lunch-end:not(:disabled):hover   { background: #fffbeb; }

    /* ── Work log card ── */
    .att-log-card {
        background: #fff;
        border: 1px solid #e5eaf4;
        border-radius: 18px;
        padding: 22px 24px;
    }
    .att-log-header { display: flex; align-items: center; gap: 12px; margin-bottom: 18px; }
    .log-icon-wrap { width: 44px; height: 44px; border-radius: 12px; background: linear-gradient(135deg,#10b981,#34d399); display: flex; align-items: center; justify-content: center; font-size: 22px; }
    .att-log-header h4 { margin: 0; font-size: 15px; font-weight: 700; color: #1f2937; }
    .att-log-header p  { margin: 3px 0 0; font-size: 12px; color: #9ca3af; }
    .att-input { width: 100%; padding: 11px 14px; border: 1.5px solid #e5eaf4; border-radius: 10px; background: #f8faff; outline: none; font-size: 13px; margin-top: 6px; margin-bottom: 14px; transition: border-color .2s, box-shadow .2s; }
    .att-input:focus { border-color: #818cf8; box-shadow: 0 0 0 3px rgba(129,140,248,.15); background: #fff; }
    .att-label { font-size: 12px; font-weight: 600; color: #374151; text-transform: uppercase; letter-spacing: .5px; }
    .att-select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236b7280' d='M6 8L1 3h10z'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 14px center; padding-right: 36px; }
    .att-btn-submit { background: linear-gradient(135deg,#10b981,#059669); color: #fff; width: 100%; padding: 13px; border-radius: 12px; border: none; font-size: 14px; font-weight: 700; cursor: pointer; transition: opacity .2s, transform .15s; margin-top: 4px; }
    .att-btn-submit:hover { opacity: .92; transform: translateY(-1px); }

    /* ── Timeline ── */
    .att-timeline { background: #fff; border: 1px solid #e5eaf4; border-radius: 18px; padding: 22px 24px; }
    .att-timeline h4 { margin: 0 0 20px; font-size: 15px; font-weight: 700; color: #1f2937; display: flex; align-items: center; gap: 8px; }
    .timeline-list { display: flex; flex-direction: column; gap: 0; }
    .timeline-item { display: flex; gap: 16px; position: relative; padding-bottom: 20px; }
    .timeline-item:last-child { padding-bottom: 0; }
    .timeline-item:not(:last-child)::before { content:''; position:absolute; left: 19px; top: 40px; bottom: 0; width: 2px; background: #e5eaf4; }
    .timeline-dot { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
    .dot-start  { background: linear-gradient(135deg,#6366f1,#818cf8); }
    .dot-stop   { background: linear-gradient(135deg,#ef4444,#f87171); }
    .dot-lunch  { background: linear-gradient(135deg,#f59e0b,#fbbf24); }
    .dot-log    { background: linear-gradient(135deg,#10b981,#34d399); }
    .timeline-body { flex: 1; padding-top: 8px; }
    .timeline-body strong { font-size: 13px; font-weight: 700; color: #1f2937; }
    .timeline-body .t-desc { font-size: 12px; color: #6b7280; margin-top: 2px; }
    .timeline-time { font-size: 11px; font-weight: 600; color: #9ca3af; white-space: nowrap; padding-top: 9px; }

    /* ── Absent banner ── */
    .att-absent-banner {
        background: linear-gradient(135deg, #fef2f2, #fee2e2);
        border: 1.5px solid #fecaca;
        border-radius: 16px;
        padding: 20px 24px;
        display: flex;
        align-items: flex-start;
        gap: 16px;
    }
    .absent-icon { font-size: 32px; flex-shrink: 0; line-height: 1; }
    .absent-text strong { font-size: 15px; font-weight: 700; color: #991b1b; display: block; }
    .absent-text p { margin: 5px 0 0; font-size: 13px; color: #b91c1c; }

    /* Countdown ring */
    .countdown-ring { display: none; align-items: center; justify-content: center; margin-top: 8px; }
    .countdown-ring.visible { display: flex; }
    .countdown-num { font-size: 28px; font-weight: 800; color: #6366f1; }
    .countdown-lbl { font-size: 11px; color: #9ca3af; text-align: center; margin-top: 2px; }
</style>

<div class="att-wrap">

    
    <div class="att-hero">
        <div class="att-hero-left">
            <h2>👋 <?php echo e(auth()->user()->name); ?></h2>
            <p><?php echo e(now('Asia/Dhaka')->format('l, d F Y')); ?> &nbsp;·&nbsp; Deadline: <?php echo e($cutoffDisplay); ?> BST</p>
        </div>
        <div>
            <?php if($isAbsent): ?>
                <div class="att-status-pill"><span class="dot dot-absent"></span> Marked Absent</div>
            <?php elseif($hasStopped): ?>
                <div class="att-status-pill"><span class="dot dot-done"></span> Session Complete</div>
            <?php elseif($hasStarted): ?>
                <div class="att-status-pill"><span class="dot dot-active"></span> Office In Progress</div>
            <?php else: ?>
                <div class="att-status-pill"><span class="dot dot-idle"></span> Not Started</div>
            <?php endif; ?>
        </div>
    </div>

    
    <?php if($isAbsent): ?>
    <div class="att-absent-banner">
        <div class="absent-icon">🚫</div>
        <div class="absent-text">
            <strong>আজকের দিনের জন্য আপনি Absent চিহ্নিত হয়েছেন</strong>
            <p>আজকের অফিস স্টার্ট করার সময় (<?php echo e($cutoffDisplay); ?>) শেষ হয়ে গেছে। প্রয়োজনে Admin-এর সাথে যোগাযোগ করুন।</p>
        </div>
    </div>
    <?php endif; ?>

    
    <?php if($session && !$isAbsent): ?>
    <div class="att-kpi-row">
        <div class="att-kpi">
            <div class="kpi-icon">🟢</div>
            <div class="kpi-val"><?php echo e($session->start_time ? $session->start_time->format('h:i A') : '—'); ?></div>
            <div class="kpi-lbl">Started At</div>
        </div>
        <div class="att-kpi">
            <div class="kpi-icon">🔴</div>
            <div class="kpi-val"><?php echo e($session->stop_time ? $session->stop_time->format('h:i A') : '—'); ?></div>
            <div class="kpi-lbl">Stopped At</div>
        </div>
        <div class="att-kpi">
            <div class="kpi-icon">🍽️</div>
            <div class="kpi-val"><?php echo e($session->lunch_minutes ?? 0); ?><span style="font-size:13px; font-weight:500; color:#6b7280;">m</span></div>
            <div class="kpi-lbl">Lunch Time</div>
        </div>
        <div class="att-kpi">
            <div class="kpi-icon">⚡</div>
            <div class="kpi-val"><?php echo e($session->net_work_minutes ?? 0); ?><span style="font-size:13px; font-weight:500; color:#6b7280;">m</span></div>
            <div class="kpi-lbl">Net Work</div>
        </div>
    </div>
    <?php endif; ?>

    
    <div class="att-actions">
        
        <div class="att-cam-card">
            <div class="att-cam-header">
                <div class="cam-icon-wrap cam-start-icon">📷</div>
                <div>
                    <h4>Start Office</h4>
                    <p>60s auto-record then upload</p>
                </div>
            </div>
            <div class="cam-preview-wrap">
                <video id="startPreview" class="cam-preview" autoplay muted playsinline></video>
                <div class="cam-overlay">
                    <div class="cam-overlay-icon">🎥</div>
                    <span>Camera preview will appear here</span>
                </div>
            </div>
            <div class="cam-footer">
                <?php if($hasStarted): ?>
                    <button class="att-btn att-btn-done" disabled>✅ Already Checked In</button>
                <?php elseif($isAbsent): ?>
                    <button class="att-btn att-btn-start" disabled>⛔ Absent Today</button>
                <?php else: ?>
                    <button class="att-btn att-btn-start" id="startRecordBtn">▶ Start Recording &amp; Check In</button>
                <?php endif; ?>
                <div class="countdown-ring" id="startCountdown">
                    <div style="text-align:center;">
                        <div class="countdown-num" id="startCountNum">60</div>
                        <div class="countdown-lbl">seconds left</div>
                    </div>
                </div>
                <div class="status-text" id="startStatus"></div>
            </div>
        </div>

        
        <div class="att-cam-card">
            <div class="att-cam-header">
                <div class="cam-icon-wrap cam-stop-icon">🔴</div>
                <div>
                    <h4>Stop Office</h4>
                    <p>60s verification video required</p>
                </div>
            </div>
            <div class="cam-preview-wrap">
                <video id="stopPreview" class="cam-preview" autoplay muted playsinline></video>
                <div class="cam-overlay">
                    <div class="cam-overlay-icon">🎥</div>
                    <span>Camera preview will appear here</span>
                </div>
            </div>
            <div class="cam-footer">
                <?php if($hasStopped): ?>
                    <button class="att-btn att-btn-done" disabled>✅ Already Checked Out</button>
                <?php elseif(!$hasStarted || $isAbsent): ?>
                    <button class="att-btn att-btn-stop" disabled>⛔ Start Office First</button>
                <?php else: ?>
                    <button class="att-btn att-btn-stop" id="stopRecordBtn">⏹ Record &amp; Check Out</button>
                <?php endif; ?>
                <div class="countdown-ring" id="stopCountdown">
                    <div style="text-align:center;">
                        <div class="countdown-num" id="stopCountNum">60</div>
                        <div class="countdown-lbl">seconds left</div>
                    </div>
                </div>
                <div class="status-text" id="stopStatus" style="color:#ef4444;"></div>
            </div>
        </div>
    </div>

    
    <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 18px;" class="bottom-grid">
        
        <div class="att-lunch-card">
            <div class="att-lunch-header">
                <div class="lunch-icon-wrap">🍱</div>
                <div>
                    <h4>Lunch Break</h4>
                    <p>Track your lunch duration</p>
                </div>
            </div>
            <div class="lunch-btns">
                <form method="POST" action="<?php echo e(route('attendance.lunch.start')); ?>" style="flex:1;">
                    <?php echo csrf_field(); ?>
                    <button class="att-btn att-btn-lunch-start" type="submit" <?php echo e((!$hasStarted || $hasStopped || $hasActiveLunch) ? 'disabled' : ''); ?>>
                        🍽 Start Lunch
                    </button>
                </form>
                <form method="POST" action="<?php echo e(route('attendance.lunch.end')); ?>" style="flex:1;">
                    <?php echo csrf_field(); ?>
                    <button class="att-btn att-btn-lunch-end" type="submit" <?php echo e((!$hasStarted || $hasStopped || !$hasActiveLunch) ? 'disabled' : ''); ?>>
                        ✅ End Lunch
                    </button>
                </form>
            </div>
            <?php if($hasActiveLunch): ?>
            <div style="margin-top:14px; text-align:center; font-size:13px; color:#b45309; font-weight:600; animation: pulse-text 1.5s ease-in-out infinite;">
                🟡 Lunch in progress...
            </div>
            <?php endif; ?>
        </div>

        
        <div class="att-log-card">
            <div class="att-log-header">
                <div class="log-icon-wrap">📝</div>
                <div>
                    <h4>Daily Work Log</h4>
                    <p>Log what you worked on today</p>
                </div>
            </div>
            <form method="POST" action="<?php echo e(route('attendance.daily-log')); ?>">
                <?php echo csrf_field(); ?>
                <label class="att-label">Log Title</label>
                <input name="title" class="att-input" placeholder="e.g. Completed homepage design" required>

                <label class="att-label">Description</label>
                <textarea name="description" class="att-input" rows="2" placeholder="What did you work on?" required></textarea>

                <label class="att-label">Status</label>
                <select name="completion_status" class="att-input att-select" required>
                    <option value="in_progress">🔄 In Progress</option>
                    <option value="completed">✅ Completed</option>
                    <option value="blocked">🚫 Blocked</option>
                </select>

                <button class="att-btn-submit" type="submit">📤 Submit Work Log</button>
            </form>
        </div>
    </div>

    
    <div class="att-timeline">
        <h4>📋 Today's Activity Timeline</h4>
        <?php if(!empty($activityTimeline)): ?>
            <div class="timeline-list">
                <?php $__currentLoopData = $activityTimeline; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $activity): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php
                        $dotClass = match($activity['type']) {
                            'start'       => 'dot-start',
                            'stop'        => 'dot-stop',
                            'lunch_start', 'lunch_end' => 'dot-lunch',
                            default       => 'dot-log',
                        };
                        $icon = match($activity['type']) {
                            'start'        => '🟢',
                            'stop'         => '🔴',
                            'lunch_start'  => '🍽',
                            'lunch_end'    => '✅',
                            default        => '📝',
                        };
                    ?>
                    <div class="timeline-item">
                        <div class="timeline-dot <?php echo e($dotClass); ?>"><?php echo e($icon); ?></div>
                        <div class="timeline-body">
                            <strong><?php echo e($activity['label']); ?></strong>
                            <div class="t-desc"><?php echo e($activity['description']); ?></div>
                        </div>
                        <div class="timeline-time"><?php echo e($activity['time']->format('h:i A')); ?></div>
                    </div>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        <?php else: ?>
            <div style="text-align:center; padding:30px 0; color:#9ca3af;">
                <div style="font-size:40px; margin-bottom:10px;">🌅</div>
                <div style="font-size:14px; font-weight:600;">আজ এখনো কোনো activity নেই</div>
                <div style="font-size:12px; margin-top:4px;">Start office to begin tracking your day</div>
            </div>
        <?php endif; ?>
    </div>

</div>

<style>
@media(max-width:700px) {
    .bottom-grid { grid-template-columns: 1fr !important; }
}
@keyframes pulse-text {
    0%,100% { opacity: 1; }
    50%      { opacity: .5; }
}
</style>

<script>
    let isProcessing = false;

    function showCountdown(countdownId, countNumId, seconds) {
        const ring = document.getElementById(countdownId);
        const num  = document.getElementById(countNumId);
        if (!ring || !num) return;
        ring.classList.add('visible');
        num.textContent = seconds;
        const interval = setInterval(() => {
            seconds = Math.max(0, seconds - 1);
            num.textContent = seconds;
            if (seconds === 0) clearInterval(interval);
        }, 1000);
        return interval;
    }

    async function recordAndUpload({previewId, statusId, endpoint, secondsField, buttonId, countdownId, countNumId}) {
        if (isProcessing) return;

        const preview   = document.getElementById(previewId);
        const statusEl  = document.getElementById(statusId);
        const button    = document.getElementById(buttonId);

        isProcessing = true;
        button.disabled = true;

        let stream;
        let countdownInterval;
        try {
            statusEl.textContent = '📡 Requesting camera permission...';
            stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
            preview.srcObject = stream;
            preview.classList.add('active');

            if (typeof MediaRecorder === 'undefined') {
                statusEl.textContent = 'Your browser does not support MediaRecorder.';
                isProcessing = false;
                button.disabled = false;
                stream.getTracks().forEach(t => t.stop());
                return;
            }

            const recorder = new MediaRecorder(stream);
            const chunks   = [];
            const startedAt = Date.now();

            recorder.ondataavailable = (e) => {
                if (e.data && e.data.size > 0) chunks.push(e.data);
            };

            statusEl.textContent = '🎥 Recording in progress...';
            countdownInterval = showCountdown(countdownId, countNumId, 60);

            recorder.start();
            await new Promise((resolve) => setTimeout(resolve, 60000));
            recorder.stop();
            await new Promise((resolve) => { recorder.onstop = resolve; });

            clearInterval(countdownInterval);
            document.getElementById(countdownId)?.classList.remove('visible');
            statusEl.textContent = '📦 Preparing upload...';

            const duration  = Math.max(60, Math.round((Date.now() - startedAt) / 1000));
            const blob      = new Blob(chunks, {type: recorder.mimeType || 'video/webm'});
            const extension = blob.type.includes('mp4') ? 'mp4' : 'webm';
            const file      = new File([blob], `${endpoint.includes('start') ? 'start' : 'stop'}-${Date.now()}.${extension}`, {type: blob.type || 'video/webm'});

            statusEl.textContent = '⬆️ Uploading video...';
            const formData = new FormData();
            formData.append('video_file', file);
            formData.append(secondsField, duration.toString());

            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                },
                body: formData,
            });

            const payload = await response.json().catch(() => ({success: false, message: 'Unexpected response'}));

            if (!response.ok || !payload.success) {
                statusEl.textContent = payload.message ? `❌ ${payload.message}` : '❌ Upload failed. Try again.';
                isProcessing = false;
                button.disabled = false;
                stream.getTracks().forEach(t => t.stop());
                return;
            }

            statusEl.textContent = `✅ ${payload.message || 'Success! Reloading...'}`;
            stream.getTracks().forEach(t => t.stop());
            setTimeout(() => window.location.reload(), 800);

        } catch (error) {
            if (countdownInterval) clearInterval(countdownInterval);
            document.getElementById(countdownId)?.classList.remove('visible');
            statusEl.textContent = '⚠️ Camera permission denied or recording failed.';
            if (stream) stream.getTracks().forEach(t => t.stop());
            isProcessing = false;
            button.disabled = false;
        }
    }

    document.getElementById('startRecordBtn')?.addEventListener('click', function () {
        recordAndUpload({
            previewId:   'startPreview',
            statusId:    'startStatus',
            endpoint:    '<?php echo e(route('attendance.start')); ?>',
            secondsField:'start_video_seconds',
            buttonId:    'startRecordBtn',
            countdownId: 'startCountdown',
            countNumId:  'startCountNum',
        });
    });

    document.getElementById('stopRecordBtn')?.addEventListener('click', function () {
        recordAndUpload({
            previewId:   'stopPreview',
            statusId:    'stopStatus',
            endpoint:    '<?php echo e(route('attendance.stop')); ?>',
            secondsField:'stop_video_seconds',
            buttonId:    'stopRecordBtn',
            countdownId: 'stopCountdown',
            countNumId:  'stopCountNum',
        });
    });
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH E:\Antigravity Projects\staff-monitoring\resources\views/attendance/index.blade.php ENDPATH**/ ?>