<?php
session_start();
include 'config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'employee') {
    header("Location: login.php");
    exit();
}

$employee_id = (int)$_SESSION['user_id'];
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $lat = $_POST['lat'] ?? null;
    $lng = $_POST['lng'] ?? null;
    $photo_path = '';

    if ($action !== 'login' && $action !== 'logout') {
        $message = "Invalid action.";
        $message_type = 'danger';
    } else {
        // Photo required only for login
        if ($action === 'login') {
            if (empty($_POST['photo_data'])) {
                $message = "Selfie photo is required for login.";
                $message_type = 'warning';
            } else {
                $upload_dir = 'uploads/attendance/';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

                // Decode base64 photo
                $photo_data = $_POST['photo_data'];
                $photo_data = str_replace('data:image/jpeg;base64,', '', $photo_data);
                $photo_data = str_replace(' ', '+', $photo_data);
                $data = base64_decode($photo_data);

                $photo_name = $employee_id . '_login_' . date('Ymd_His') . '.jpg';
                $photo_path = $upload_dir . $photo_name;

                if (file_put_contents($photo_path, $data) === false) {
                    $message = "Failed to save photo.";
                    $message_type = 'danger';
                }
            }
        }

        if (empty($message)) {
            $today = date('Y-m-d');

            $stmt = $conn->prepare("SELECT * FROM mobileattendance WHERE user_id = ? AND attendance_date = ?");
            $stmt->bind_param("is", $employee_id, $today);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 0) {
                if ($action === 'login') {
                    $insert = $conn->prepare("
                        INSERT INTO mobileattendance 
                        (user_id, attendance_date, login_time, latitude, longitude, photo_path, created_at, updated_at)
                        VALUES (?, ?, NOW(), ?, ?, ?, NOW(), NOW())
                    ");
                    $insert->bind_param("isdds", $employee_id, $today, $lat, $lng, $photo_path);
                    if ($insert->execute()) {
                        $message = "Login marked successfully!";
                        $message_type = 'success';
                    } else {
                        $message = "Database error on login.";
                        $message_type = 'danger';
                    }
                    $insert->close();
                } else {
                    $message = "Please mark Login first.";
                    $message_type = 'warning';
                }
            } else {
                $row = $result->fetch_assoc();
                if ($action === 'logout' && is_null($row['logout_time'])) {
                    $update = $conn->prepare("
                        UPDATE mobileattendance 
                        SET logout_time = NOW(), logout_latitude = ?, logout_longitude = ?, updated_at = NOW()
                        WHERE user_id = ? AND attendance_date = ?
                    ");
                    $update->bind_param("ddis", $lat, $lng, $employee_id, $today);
                    if ($update->execute()) {
                        $message = "Logout marked successfully!";
                        $message_type = 'success';
                    } else {
                        $message = "Failed to mark logout.";
                        $message_type = 'danger';
                    }
                    $update->close();
                } else {
                    $message = $row['logout_time'] ? "Already logged out today." : "Already logged in today.";
                    $message_type = 'info';
                }
            }
            $stmt->close();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Mark Attendance</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
    <style>
        body { background: linear-gradient(135deg, #667eea, #764ba2); min-height: 100vh; color: white; }
        .card { background: rgba(255,255,255,0.95); border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); color: #333; }
        .btn-lg { padding: 15px; font-size: 1.2rem; border-radius: 15px; }
        #video { width: 100%; max-height: 400px; object-fit: cover; border-radius: 15px; background: #000; }
        #canvas { display: none; }
        #photoPreview { max-width: 100%; max-height: 300px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .permission-note { background: rgba(0,0,0,0.6); padding: 15px; border-radius: 12px; font-size: 0.9rem; }
        .loading { display: none; }
    </style>
</head>
<body class="d-flex align-items-center">
<div class="container">
    <div class="text-center mb-4">
        <h2 class="fw-bold"><i class="fas fa-mobile-alt me-3"></i>Mobile Attendance</h2>
        <p><?= date('l, d F Y') ?></p>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-<?= $message_type ?> text-center fw-bold">
            <?= htmlspecialchars($message) ?>
        </div>
    <?php endif; ?>

    <div class="card mx-auto p-4" style="max-width: 500px;">
        <div id="cameraSection">
            <div class="text-center mb-4">
                <h4 id="titleText">Take Selfie for Login</h4>
                <p class="permission-note">
                    <i class="fas fa-info-circle me-2"></i>
                    Allow camera & location access when prompted<br>
                    <small>Permissions are requested only once</small>
                </p>
            </div>

            <video id="video" autoplay playsinline muted></video>
            <canvas id="canvas"></canvas>

            <div class="text-center mt-3">
                <img id="photoPreview" alt="Your selfie preview" style="display:none;">
            </div>

            <div class="d-grid gap-3 mt-4">
                <button type="button" class="btn btn-primary btn-lg" id="captureBtn" onclick="capturePhoto()">
                    <i class="fas fa-camera me-2"></i>Capture Selfie
                </button>

                <button type="button" class="btn btn-success btn-lg" id="loginBtn" style="display:none;" onclick="submitAttendance('login')">
                    <i class="fas fa-sign-in-alt me-2"></i>Mark Login (with Selfie)
                </button>

                <button type="button" class="btn btn-warning btn-lg" id="retakeBtn" style="display:none;" onclick="retakePhoto()">
                    <i class="fas fa-redo me-2"></i>Retake Selfie
                </button>

                <button type="button" class="btn btn-danger btn-lg" onclick="submitAttendance('logout')">
                    <i class="fas fa-sign-out-alt me-2"></i>Mark Logout
                </button>
            </div>
        </div>

        <div class="loading text-center py-5" id="loading">
            <div class="spinner-border text-primary" style="width:3rem;height:3rem;"></div>
            <p class="mt-3">Processing your attendance...</p>
        </div>
    </div>

    <div class="text-center mt-4">
        <a href="dashboard_employee.php" class="btn btn-outline-light btn-lg">
            <i class="fas fa-home me-2"></i>Dashboard
        </a>
    </div>
</div>

<script>
// Elements
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const photoPreview = document.getElementById('photoPreview');
const titleText = document.getElementById('titleText');
const cameraSection = document.getElementById('cameraSection');
const loading = document.getElementById('loading');
const captureBtn = document.getElementById('captureBtn');
const loginBtn = document.getElementById('loginBtn');
const retakeBtn = document.getElementById('retakeBtn');

let stream = null;
let capturedPhotoData = '';

// Start camera
async function startCamera() {
    try {
        stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: "user" },
            audio: false
        });
        video.srcObject = stream;
        video.play();
        titleText.textContent = "Take Selfie for Login";
    } catch (err) {
        alert("Camera access denied or not available. Please allow camera permission and reload the page.");
        console.error("Camera error:", err);
    }
}

// Capture photo
function capturePhoto() {
    if (video.videoWidth === 0 || video.videoHeight === 0) {
        alert("Camera is not ready yet. Please wait a few seconds.");
        return;
    }

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const context = canvas.getContext('2d');
    context.drawImage(video, 0, 0);

    const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
    capturedPhotoData = dataUrl;

    photoPreview.src = dataUrl;
    photoPreview.style.display = 'block';

    titleText.textContent = "Selfie captured! Ready to mark login.";
    
    // Update buttons
    captureBtn.style.display = 'none';
    loginBtn.style.display = 'block';
    retakeBtn.style.display = 'block';
}

// Retake photo
function retakePhoto() {
    capturedPhotoData = '';
    photoPreview.style.display = 'none';
    photoPreview.src = '';
    titleText.textContent = "Take Selfie for Login";

    captureBtn.style.display = 'block';
    loginBtn.style.display = 'none';
    retakeBtn.style.display = 'none';
}

// Get location
async function getLocation() {
    return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
            reject("Geolocation is not supported by your browser.");
            return;
        }
        navigator.geolocation.getCurrentPosition(
            pos => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
            err => reject("Location access denied or failed. Please enable location permission."),
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 }
        );
    });
}

// Submit attendance
async function submitAttendance(action) {
    loading.style.display = 'block';
    cameraSection.style.display = 'none';

    try {
        const location = await getLocation();

        if (action === 'login' && !capturedPhotoData) {
            throw new Error("Please capture your selfie first.");
        }

        const form = document.createElement('form');
        form.method = 'POST';
        form.style.display = 'none';

        const addInput = (name, value) => {
            const input = document.createElement('input');
            input.name = name;
            input.value = value || '';
            form.appendChild(input);
        };

        addInput('action', action);
        addInput('lat', location.lat);
        addInput('lng', location.lng);
        if (action === 'login') {
            addInput('photo_data', capturedPhotoData);
        }

        document.body.appendChild(form);
        form.submit();

    } catch (err) {
        alert(err.message || err || "Failed to process attendance.");
        loading.style.display = 'none';
        cameraSection.style.display = 'block';
    }
}

// Start camera when page loads
window.onload = () => {
    startCamera();
};
</script>
</body>
</html>