<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$servername = "localhost";
$username = "safegua6_adds";
$password = "@mashaAllah1";
$dbname = "safegua6_fursa";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $employee_id = $_POST['employee_id'];

    $sql = "SELECT employee_id, firstname, lastname FROM employees WHERE employee_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $employee_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $firstname = $row['firstname'];
        $lastname = $row['lastname'];
        header("Location: step2.php?employee_id=" . $employee_id . "&firstname=" . urlencode($firstname) . "&lastname=" . urlencode($lastname));
        exit();
    } else {
        echo "Invalid employee ID. Please try again.";
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee QR Code Scanner</title>
    <style>
    /* Reset default margins and paddings */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background-color: #b36b00;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    overflow: hidden;
}

form {
    max-width: 100%;
    text-align: center;
    padding: 20px;
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    position: relative;
}

#employeeDetails {
    display: none;
    margin-top: 20px;
}

#employeeName {
    font-size: 1.5rem;
    margin-bottom: 10px;
}

#employeePhoto {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

#startButton {
    display: block;
    width: 100%;
    text-decoration: none;
    margin-top: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

#startButton video {
    width: 100%;
    height: auto;
    display: block;
}

#errorMessage {
    display: none;
    color: red;
    margin-top: 20px;
}

@media (min-width: 768px) {
    form {
        max-width: 500px;
    }
}


 #decoding-style {
            display: none;
        }
        input[type="submit"][name="next"] {
            display: none;
        }

    </style>
</head>
<body>
    <form id="qrCodeForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
       <h3>Welcome, Scan Your QR  </h3>
        <a id="startButton">
            <video id="video" width="100%" height="350" poster="scan.png"></video>
        </a>
        <input type="hidden" id="employee_id" name="employee_id">
        <select id="decoding-style">
            <option value="once"></option>
        </select>
        <input type="submit" name="next" value="Next" id="nextButton">
    
        <div id="errorMessage">Error: Could not access the camera. Please check your camera permissions and try again.</div>
    </form>
    
    <script type="text/javascript">
        let qrCodeDetected = false;

        function showError(message) {
            const errorMessage = document.getElementById('errorMessage');
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
        }

        function decodeOnce(codeReader, selectedDeviceId) {
            codeReader.decodeFromInputVideoDevice(selectedDeviceId, 'video').then((result) => {
                if (result && !qrCodeDetected) {
                    console.log('Found QR code!', result);
                    qrCodeDetected = true;
                    document.getElementById('employee_id').value = result.text.trim();
                    document.getElementById('qrCodeForm').submit();
                }
            }).catch((err) => {
                console.error(err);
                if (err instanceof ZXing.NotFoundException) {
                    console.log('No QR code found.');
                } else {
                    showError('Error reading QR code: ' + err.message);
                }
            });
        }

        window.addEventListener('load', function () {
            let selectedDeviceId;
            const codeReader = new ZXing.BrowserQRCodeReader();
            console.log('ZXing code reader initialized');

            codeReader.getVideoInputDevices()
                .then((videoInputDevices) => {
                    const frontCameraDevices = videoInputDevices.filter(device => device.label.toLowerCase().includes('front') || device.facingMode === 'user');

                    if (frontCameraDevices.length > 0) {
                        selectedDeviceId = frontCameraDevices[0].deviceId;
                        console.log(`Using front camera with id ${selectedDeviceId}`);
                    } else {
                        showError('');
                    }

                    document.getElementById('startButton').addEventListener('click', () => {
                        const decodingStyle = document.getElementById('decoding-style').value;

                        if (decodingStyle === "once") {
                            decodeOnce(codeReader, selectedDeviceId);
                        }
                    });
                })
                .catch((err) => {
                    console.error('Error getting video input devices:', err);
                    showError('Error: Could not access the camera. Please check your camera permissions and try again.');
                });
        });
    </script>
 
    <script type="text/javascript" src="js/qrscan.js"></script>
</body>
</html>
