<?= $this->extend('layouts/employee') ?>

<?= $this->section('content') ?>

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 25px; margin-bottom: 40px;">
    <!-- Active Projects Card -->
    <div class="card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; position: relative; overflow: hidden; border: none;">
        <div style="position: relative; z-index: 2;">
            <div style="font-size: 0.85rem; opacity: 0.8; text-transform: uppercase; letter-spacing: 1px; font-weight: 600;">Active Projects</div>
            <div style="font-size: 2.8rem; font-weight: 800; margin: 10px 0;"><?= $project_count ?></div>
            <div style="font-size: 0.85rem; opacity: 0.8;">Currently assigned projects</div>
        </div>
        <i class="bi bi-briefcase-fill" style="position: absolute; right: -10px; bottom: -10px; font-size: 6rem; opacity: 0.15; transform: rotate(-15deg);"></i>
    </div>
    
    <!-- Profile Card -->
    <div class="card" style="display: flex; flex-direction: row; align-items: center; gap: 20px; border-left: 5px solid var(--primary);">
        <div style="width: 70px; height: 70px; border-radius: 18px; background: rgba(229, 45, 39, 0.1); color: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 2rem;">
            <i class="bi bi-person-badge-fill"></i>
        </div>
        <div>
            <div style="font-size: 0.8rem; color: var(--text-muted); text-transform: uppercase; font-weight: 600; letter-spacing: 0.5px;">Designation</div>
            <div style="font-weight: 800; font-size: 1.25rem; color: #2d3436; margin-top: 2px;"><?= $user['designation'] ?? 'Team Member' ?></div>
            <div style="font-size: 0.85rem; color: #2ecc71; margin-top: 4px; font-weight: 600;"><i class="bi bi-patch-check-fill"></i> Verified Employee</div>
        </div>
    </div>
</div>
<!-- Attendance Section -->
<div class="card" style="margin-bottom: 40px; padding: 30px; border: 1px solid var(--border);">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3 style="margin: 0; font-weight: 700; display: flex; align-items: center; gap: 10px;">
            <i class="bi bi-clock-history" style="color: var(--primary);"></i> Daily Attendance
        </h3>
        <?php if ($today_attendance): ?>
            <span class="status-badge" style="background: rgba(46, 204, 113, 0.1); color: #2ecc71; padding: 5px 15px; border-radius: 20px; font-weight: 600;">
                <i class="bi bi-check2-circle"></i> Marked for Today
            </span>
        <?php endif; ?>
    </div>

    <?php if (!$today_attendance): ?>
        <div id="attendance-interface" style="display: flex; gap: 30px; flex-wrap: wrap;">
            <div style="flex: 1; min-width: 300px;">
                <div id="camera-container" style="width: 100%; aspect-ratio: 4/3; background: #000; border-radius: 12px; overflow: hidden; position: relative;">
                    <video id="webcam" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
                    <canvas id="snapshot" style="display: none;"></canvas>
                    <div id="camera-overlay" style="position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,0.5); color: #fff; cursor: pointer;" onclick="startCamera()">
                        <div style="text-align: center;">
                            <i class="bi bi-camera" style="font-size: 3rem; display: block; margin-bottom: 10px;"></i>
                            <span>Click to Start Camera</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div style="flex: 1; min-width: 250px; display: flex; flex-direction: column; justify-content: center; gap: 20px;">
                <div>
                    <label style="display: block; margin-bottom: 10px; font-weight: 600; color: var(--text-muted);">Attendance Status</label>
                    <select id="attendance-status" class="form-control" style="padding: 12px;">
                        <option value="Present">Present (Full Day)</option>
                        <option value="Half Day">Half Day</option>
                    </select>
                </div>
                
                <button id="capture-btn" class="btn btn-primary" style="padding: 15px; font-weight: 700; width: 100%;" disabled onclick="takeSnapshot()">
                    <i class="bi bi-camera-fill"></i> Capture & Mark Attendance
                </button>
                
                <p style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.5;">
                    <i class="bi bi-info-circle"></i> Please ensure your face is clearly visible in the camera before capturing.
                </p>
            </div>
        </div>
        
        <div id="attendance-success" style="display: none; text-align: center; padding: 40px;">
            <div style="width: 80px; height: 80px; background: rgba(46, 204, 113, 0.1); color: #2ecc71; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 3rem; margin: 0 auto 20px;">
                <i class="bi bi-check-lg"></i>
            </div>
            <h3 style="margin-bottom: 10px;">Attendance Marked!</h3>
            <p style="color: var(--text-muted);">Your attendance has been recorded and is pending admin approval.</p>
        </div>
    <?php else: ?>
        <div style="display: flex; align-items: center; gap: 20px; background: rgba(248, 249, 250, 1); padding: 20px; border-radius: 12px; border: 1px dashed var(--border);">
            <div style="width: 100px; height: 100px; border-radius: 10px; overflow: hidden; border: 3px solid #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.1);">
                <img src="<?= base_url($today_attendance['image_path']) ?>" style="width: 100%; height: 100%; object-fit: cover;">
            </div>
            <div>
                <div style="font-weight: 700; font-size: 1.1rem; margin-bottom: 5px;">Marked at <?= date('h:i A', strtotime($today_attendance['created_at'])) ?></div>
                <div style="color: var(--text-muted); font-size: 0.9rem;">Status: <strong><?= $today_attendance['status'] ?></strong> | Approval: <strong><?= $today_attendance['approval_status'] ?></strong></div>
            </div>
        </div>
    <?php endif; ?>
</div>

<h2 style="margin-bottom: 25px; font-weight: 800; display: flex; align-items: center; gap: 10px;">
    <i class="bi bi-kanban" style="color: var(--primary);"></i> My Assigned Projects
</h2>

<script>
    let video = document.getElementById('webcam');
    let canvas = document.getElementById('snapshot');
    let captureBtn = document.getElementById('capture-btn');
    let overlay = document.getElementById('camera-overlay');

    async function startCamera() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' }, audio: false });
            video.srcObject = stream;
            overlay.style.display = 'none';
            captureBtn.disabled = false;
        } catch (err) {
            console.error("Error accessing camera: ", err);
            alert("Could not access camera. Please ensure you have granted permission.");
        }
    }

    async function takeSnapshot() {
        const context = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        const imageData = canvas.toDataURL('image/jpeg');
        const status = document.getElementById('attendance-status').value;
        
        captureBtn.disabled = true;
        captureBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Processing...';

        try {
            const response = await fetch('<?= base_url('employee/save_attendance') ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: `image=${encodeURIComponent(imageData)}&status=${encodeURIComponent(status)}`
            });
            
            const result = await response.json();
            
            if (result.status === 'success') {
                document.getElementById('attendance-interface').style.display = 'none';
                document.getElementById('attendance-success').style.display = 'block';
                setTimeout(() => location.reload(), 2000);
            } else {
                alert(result.message);
                captureBtn.disabled = false;
                captureBtn.innerHTML = '<i class="bi bi-camera-fill"></i> Capture & Mark Attendance';
            }
        } catch (err) {
            console.error("Error saving attendance: ", err);
            alert("Error saving attendance. Please try again.");
            captureBtn.disabled = false;
            captureBtn.innerHTML = '<i class="bi bi-camera-fill"></i> Capture & Mark Attendance';
        }
    }
</script>

<h2 style="margin: 40px 0 25px 0; font-weight: 800; display: flex; align-items: center; gap: 12px; color: #1e1e2d;">
    <span style="width: 8px; height: 30px; background: var(--primary); border-radius: 4px;"></span>
    My Assigned Projects
</h2>

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 30px;">
    <?php if (empty($projects)): ?>
        <div class="card" style="grid-column: 1 / -1; text-align: center; padding: 80px 40px; background: #fff; border: 2px dashed var(--border);">
            <div style="width: 100px; height: 100px; background: #f8f9fa; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 25px; color: var(--border);">
                <i class="bi bi-folder-x" style="font-size: 3.5rem;"></i>
            </div>
            <h3 style="color: #2d3436; font-weight: 800; margin-bottom: 10px;">No projects assigned yet.</h3>
            <p style="color: var(--text-muted); max-width: 400px; margin: 0 auto;">Contact your administrator to get assigned to a construction project and start managing records.</p>
        </div>
    <?php else: ?>
        <?php foreach ($projects as $proj): ?>
            <div class="card" style="padding: 0; overflow: hidden; position: relative;">
                <div style="position: relative;">
                    <img src="<?= $proj['image'] ?? base_url('assets/images/placeholder.jpg') ?>" style="width: 100%; height: 220px; object-fit: cover;">
                    <div style="position: absolute; top: 15px; left: 15px;">
                        <span style="background: var(--primary); color: #fff; padding: 6px 15px; border-radius: 50px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; box-shadow: 0 4px 10px rgba(229, 45, 39, 0.3);">
                            <?= $proj['status'] ?>
                        </span>
                    </div>
                </div>
                <div style="padding: 25px;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px; color: var(--text-muted); font-size: 0.85rem; font-weight: 600;">
                        <i class="bi bi-calendar3" style="color: var(--primary);"></i>
                        Started <?= date('M Y', strtotime($proj['start_date'])) ?>
                    </div>
                    <h3 style="margin: 0 0 15px 0; font-size: 1.3rem; font-weight: 800; color: #1e1e2d; line-height: 1.4;"><?= $proj['title'] ?></h3>
                    
                    <?php if (!empty($proj['assigned_employees'])): ?>
                        <div style="margin-bottom: 20px;">
                            <div style="font-size: 0.75rem; color: var(--text-muted); font-weight: 700; text-transform: uppercase; margin-bottom: 8px;">Project Team</div>
                            <div style="display: flex; flex-wrap: wrap; gap: 6px;">
                                <?php foreach ($proj['assigned_employees'] as $name): ?>
                                    <span style="background: #f8f9fa; color: #4a5568; padding: 4px 12px; border-radius: 6px; font-size: 0.8rem; font-weight: 600; border: 1px solid #edf2f7;"><?= $name ?></span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <p style="font-size: 0.95rem; color: var(--text-muted); line-height: 1.6; margin-bottom: 25px;">
                        <?= substr(strip_tags($proj['description']), 0, 110) ?>...
                    </p>
                    <div style="padding-top: 20px; border-top: 1px solid #f1f3f5; display: flex; justify-content: space-between; align-items: center;">
                        <a href="<?= base_url('employee/project_expenses/' . $proj['id']) ?>" class="btn-manage" style="text-decoration: none; color: var(--primary); font-weight: 800; font-size: 0.95rem; display: flex; align-items: center; gap: 8px; transition: gap 0.3s;" onmouseover="this.querySelector('i').style.transform='translateX(5px)'" onmouseout="this.querySelector('i').style.transform='translateX(0)'">
                            Manage My Expenses <i class="bi bi-arrow-right" style="transition: transform 0.3s;"></i>
                        </a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<?= $this->endSection() ?>
