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

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

// Set session timeout to 1 minute (60 seconds)
$session_timeout = 60;

// Check if session is set and if it has timed out
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $session_timeout)) {
    session_unset();
    session_destroy();
    session_start();
}

// Update last activity time
$_SESSION['last_activity'] = time();

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

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    header('Content-Type: application/json');

    if (isset($_SESSION['face_detected']) && $_SESSION['face_detected'] === true) {
        echo json_encode(array("redirect" => "login.php"));
        exit();
    }

    $employee_id = $_POST['employee_id'] ?? '';
    $firstname = $_POST['firstname'] ?? '';
    $lastname = $_POST['lastname'] ?? '';
    $input_face_descriptor = json_decode($_POST['captured_image'], true);

    $sql = "SELECT id, firstname, lastname, amount_per_hour, face_descriptor 
            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) {
        $employee = $result->fetch_assoc();
        $stored_face_descriptor = json_decode($employee['face_descriptor'], true);

        $distance = 0.0;
        for ($i = 0; $i < count($stored_face_descriptor); $i++) {
            $distance += pow($input_face_descriptor[$i] - $stored_face_descriptor[$i], 2);
        }
        $distance = sqrt($distance);

        if ($distance < 0.6) {
            $current_time = new DateTime('now', new DateTimeZone('GMT+1'));
            $current_time_formatted = $current_time->format('H:i:s');

            // Restrict login from 00:00 to 06:59
            if ($current_time_formatted >= "00:00:00" && $current_time_formatted <= "06:59:59") {
                echo json_encode(array("error" => true, "message" => "You are Not Allow"));
                exit();
            }

            $current_date = date('Y-m-d');
            $morning_start_time = "08:00:00";
            $morning_end_time = "18:00:00";
            $night_start_time = "19:00:00";
            $night_end_time = "07:00:00";

            // Determine the shift
            $shift = ($current_time_formatted >= $morning_start_time && $current_time_formatted < $morning_end_time) ? 'morning' : 'night';
            $shift_start_time = ($shift == 'morning') ? $morning_start_time : $night_start_time;
            $shift_end_time = ($shift == 'morning') ? $morning_end_time : $night_end_time;

            // Calculate any late deduction
            $deduction = 0;
            $minutes_late = round((strtotime($current_time_formatted) - strtotime($shift_start_time)) / 60);
            if ($minutes_late > 30 && $minutes_late <= 45) {
                $deduction = 1000;
            } elseif ($minutes_late > 45) {
                $deduction = 5000;
            }

            // Check if there is an existing login without a logout
            $existing_login_query = "SELECT * FROM attendance WHERE employee_id = ? AND time_out IS NULL";
            $stmt = $conn->prepare($existing_login_query);
            $stmt->bind_param("i", $employee['id']);
            $stmt->execute();
            $existing_login_result = $stmt->get_result();

            if ($existing_login_result->num_rows > 0) {
                $logout_time = new DateTime('now', new DateTimeZone('GMT+1'));
                $logout_time_formatted = $logout_time->format('Y-m-d H:i:s');

                $login_record = $existing_login_result->fetch_assoc();
                $login_time = new DateTime($login_record['time_in'], new DateTimeZone('GMT+1'));

                // Check if the logout time is on the next day
                if ($logout_time < $login_time) {
                    $logout_time->modify('+1 day');
                }

                // Calculate hours worked
                $hours_worked = round(($logout_time->getTimestamp() - $login_time->getTimestamp()) / 3600, 2);

                // Do not count hours worked beyond shift end
                $shift_end_date_time = new DateTime($shift_end_time, new DateTimeZone('GMT+1'));
                if ($shift_end_time < $shift_start_time) {
                    $shift_end_date_time->modify('+1 day');
                }

                if ($logout_time > $shift_end_date_time) {
                    $logout_time = $shift_end_date_time;
                    $hours_worked = round(($logout_time->getTimestamp() - $login_time->getTimestamp()) / 3600, 2);
                }

                // Automatically log out with 0 payable amount if more than 3 hours after shift end
                $three_hours_after_shift_end = clone $shift_end_date_time;
                $three_hours_after_shift_end->modify('+3 hours');

                if ($logout_time > $three_hours_after_shift_end) {
                    $logout_time = $three_hours_after_shift_end;
                    $hours_worked = 0;
                }

                $payable_amount = $hours_worked * $employee['amount_per_hour'] - $deduction;

                $update_query = "
                    UPDATE attendance SET time_out = ?, hours_worked = ?, deduction = ?, payable_amount = ?
                    WHERE id = ?";
                $stmt = $conn->prepare($update_query);
                $stmt->bind_param("sdddi", $logout_time->format('Y-m-d H:i:s'), $hours_worked, $deduction, $payable_amount, $login_record['id']);

                if ($stmt->execute()) {
                    $_SESSION['face_detected'] = true;
                    echo json_encode(array("message" => "Logout successful. Deduction: $deduction. Payable amount: $payable_amount", "redirect" => "login.php"));
                    exit();
                } else {
                    echo json_encode(array("error" => true, "message" => "Failed to update logout details.", "error_detail" => $stmt->error));
                }
            } else {
                $login_time = $current_time_formatted;

                $insert_login_query = "INSERT INTO attendance (employee_id, date, time_in, shift, shift_time, deduction) VALUES (?, ?, ?, ?, ?, ?)";
                $stmt = $conn->prepare($insert_login_query);
                $stmt->bind_param("issssd", $employee['id'], $current_date, $login_time, $shift, $shift_start_time, $deduction);

                if ($stmt->execute()) {
                    $_SESSION['face_detected'] = true;
                    echo json_encode(array("message" => "Login successful. Welcome, " . $employee['firstname'] . " " . $employee['lastname'], "redirect" => "login.php"));
                    exit();
                } else {
                    echo json_encode(array("error" => true, "message" => "Failed to record login details.", "error_detail" => $stmt->error));
                }
            }
        } else {
            echo json_encode(array("error" => true, "message" => "Invalid face. Please try again."));
        }
    } else {
        echo json_encode(array("error" => true, "message" => "Employee ID not found."));
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Face Detection Login</title>
    <script defer src="face-api.js-master/weights/a.js"></script>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            try {
                console.log('Loading models...');
                await faceapi.nets.ssdMobilenetv1.loadFromUri('/t/face-api.js-master/weights');
                await faceapi.nets.faceRecognitionNet.loadFromUri('/t/face-api.js-master/weights');
                await faceapi.nets.faceLandmark68Net.loadFromUri('/t/face-api.js-master/weights');
                console.log('Models loaded.');
                setupCamera();
            } catch (err) {
                console.error('Error loading models: ', err);
            }

            setInterval(captureImage, 500); // Adjusted interval for faster detection
        });

        async function setupCamera() {
            const video = document.getElementById('video');
            navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480 } }) // Lower resolution
                .then(stream => {
                    video.srcObject = stream;
                })
                .catch(err => console.error('Error accessing camera: ', err));
        }

        async function captureImage() {
            const video = document.getElementById('video');
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');

            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);

            const detection = await faceapi.detectSingleFace(video).withFaceLandmarks().withFaceDescriptor();
            if (detection) {
                document.getElementById('captured_image').value = JSON.stringify(detection.descriptor);
                submitForm();
            } else {
                const responseMessage = document.getElementById('responseMessage');
                responseMessage.style.color = 'red';
                responseMessage.textContent = 'Invalid face. Please try again.';
            }
        }

        function submitForm() {
            const form = document.getElementById('loginForm');
            const formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    const responseMessage = document.getElementById('responseMessage');
                    responseMessage.style.color = 'red';
                    responseMessage.textContent = data.message;
                } else if (data.redirect) {
                    window.location.href = data.redirect;
                }
            })
            .catch(err => console.error('Error submitting form: ', err));
        }

        // Function to read the greeting message
        function readGreetingMessage() {
            const speech = new SpeechSynthesisUtterance();
            const firstname = "<?php echo htmlspecialchars($_GET['firstname'] ?? ''); ?>";
            const lastname = "<?php echo htmlspecialchars($_GET['lastname'] ?? ''); ?>";
            const message = `Welcome, ${firstname} ${lastname}. Please kindly verify your face.`;
            speech.text = message;
            speech.pitch = 1;
            speech.rate = 1;
            window.speechSynthesis.speak(speech);
        }

        readGreetingMessage(); // Call the greeting message function on page load
    </script>
    
    
    
    
   <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;
}


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

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

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




    </style>
    
    
    
    
</head>
<body>

    <form id="loginForm" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
            <h3>Welcome, <?php echo htmlspecialchars($_GET['firstname'] ?? ''); ?> <?php echo htmlspecialchars($_GET['lastname'] ?? ''); ?> Please Kindly Verify Your Face </h3>

        <input type="hidden" name="employee_id" value="<?php echo htmlspecialchars($_GET['employee_id'] ?? ''); ?>">
        <input type="hidden" name="firstname" value="<?php echo htmlspecialchars($_GET['firstname'] ?? ''); ?>">
        <input type="hidden" name="lastname" value="<?php echo htmlspecialchars($_GET['lastname'] ?? ''); ?>">
        <input type="hidden" id="captured_image" name="captured_image">
        <video id="video" width="100%" height="350" autoplay></video>
        <div id="responseMessage"></div>
    </form>
</body>
</html>
