<?php

/**
 * File Name : user/user_a.php
 * Description : 
 * In this manages login action 
 *  
 */
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Get the correct path to the root directory
$root_path = realpath(__DIR__ . '/../../');

// Include the necessary files
require_once $root_path . '/includes/include_all.inc.php';

// Function to log messages
function logMessage($message) {
    error_log(date('[Y-m-d H:i:s] ') . $message . "\n", 3, $GLOBALS['root_path'] . '/logs/user_actions.log');
}

// Log the root path and include path
logMessage("Root path: " . $root_path);
logMessage("Include path: " . get_include_path());

// Log all included files
$included_files = get_included_files();
logMessage("Included files: " . print_r($included_files, true));

// Check if Users class exists
if (class_exists('Users')) {
    logMessage("Users class found");
} else {
    logMessage("Users class not found");
    
    // Check if the Users class file exists
    $users_class_path = $root_path . '/classes/users/Users.class.php';
    if (file_exists($users_class_path)) {
        logMessage("Users.class.php file exists at: " . $users_class_path);
        // Try to include it directly
        require_once $users_class_path;
        if (class_exists('Users')) {
            logMessage("Users class found after direct inclusion");
        } else {
            logMessage("Users class still not found after direct inclusion");
        }
    } else {
        logMessage("Users.class.php file not found at: " . $users_class_path);
    }
}

logMessage("Request received. Method: " . $_SERVER['REQUEST_METHOD']);
logMessage("POST data: " . print_r($_POST, true));
logMessage("Raw input: " . file_get_contents('php://input'));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    logMessage("Action received: " . $action);
    
    switch ($action) {
        case 'login':
            logMessage("Login case entered");
            $obj_users = new Users($pdo);

            $fields = array(
                'email' => array('type' => 'email', 'required' => true, 'error' => 'Please enter a valid email address'),
                'pass' => array('type' => 'string', 'required' => true, 'error' => 'Please enter a password')
            );
            
            logMessage("Fields array: " . print_r($fields, true));
            
            $validator = new Validator($fields);
            logMessage("Validator object created");
            
            if (!$validator->validate($_POST)) {
                $errors = $validator->errors();
                logMessage("Validation failed. Errors: " . print_r($errors, true));
            } else {
                logMessage("Validation passed");
            }
             
            if (empty($errors)) {
                $email = strtolower(filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
                logMessage("Attempting login for email: " . $email);
                
                $login = $obj_users->doLogin(['email' => $email, 'pass' => $_POST['pass']]);
                
                if ($login) {
                    logMessage("Login successful for email: " . $email);
                    $_SESSION['user_logged_in'] = true;
					unset($_SESSION['user_pro_status']);
					$_SESSION['clear_cache'] = true;
					// header('Location: ' . BASEURL . 'r.php?redirect=' . urlencode(BASEURL)); // works but has a separate page. it causes the forced refresh of leftover vars when logging into another account.
                    header('Location: ' . BASEURL);
                    exit;
                } else {
                    logMessage("Login failed for email: " . $email);
                    $_SESSION['errors'] = ['Email or password do not match'];
                    $_SESSION['session'] = $_POST;
                    header('Location: ' . BASEURL . 'login.php');
                    exit;
                }
            } else {
                logMessage("Validation errors: " . print_r($errors, true));
                $_SESSION['session'] = $_POST;
                $_SESSION['errors'] = $errors;
                header('Location: ' . BASEURL . 'login.php');
                exit;
            }
            break;

		case 'register':
			// Create Group object with PDO connection
			$obj_group = new Group($pdo);
			
			// Validate inputs - added 'type' for group_id
			$fields = array(
				'group_id' => array(
					'type' => 'int',         
					'required' => true, 
					'error' => 'Please select a group'
				),
				'email' => array(
					'type' => 'email', 
					'required' => true, 
					'error' => 'Please enter a valid email address'
				),
				'pass' => array(
					'type' => 'string', 
					'required' => true, 
					'error' => 'Please enter a password'
				)
			);
			
			ob_start(); // Start output buffering
			
			$validator = new Validator($fields);
			$errors = array();
			
			if (!$validator->validate($_POST)) {
				$errors = $validator->errors();
			} else {
				// Sanitize inputs
				$group_id = filter_var($_POST['group_id'], FILTER_SANITIZE_NUMBER_INT);
				$email = strtolower(filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
				$pass = trim($_POST['pass']);
				
				// Get the group password and verify using the Group class method
				$group_password = $obj_group->fetchGroupPassword($group_id);
				
				if ($group_password === false) {
					$errors[] = 'Invalid group selected.';
				} else {
					// Hash the provided password the same way as the stored group password
					$salt = sha1(md5($pass));
					$hashed_password = md5($pass.$salt);

					if ($group_password !== $hashed_password) {
						$errors[] = 'Incorrect group password.';
					} else {
						// Create user object
						$obj_users = new Users($pdo);
						
						// Check if user already exists
						if ($obj_users->fetchUserExistOrNot($email)) {
							$errors[] = 'Email address already exists, please try a new one or log in.';
						} else {
							// Get group password clear text
							$stmt = $pdo->prepare("SELECT group_pass_clear FROM wp_groups WHERE id = ?");
							$stmt->execute([$group_id]);
							$group_pass_clear = $stmt->fetchColumn();

							// Attempt to insert new user
							$user_data = [
								'email' => $email,
								'pass' => $pass,
								'pass_clear' => $group_pass_clear,
								'group_id' => $group_id
							];
							
							$insert_user = $obj_users->insertUser($user_data);
							
							if ($insert_user) {
								// Force sync passwords for the new user
								$userId = $pdo->lastInsertId();
								$syncSql = "
									UPDATE wp_users u
									JOIN wp_groups g ON u.group_id = g.id
									SET u.user_pass = g.group_pass,
										u.user_pass_clear = g.group_pass_clear,
										u.user_group = g.group_name
									WHERE u.id = ?
								";
								$syncStmt = $pdo->prepare($syncSql);
								$syncStmt->execute([$userId]);
	
								// Attempt to log in the new user
								$login = $obj_users->doLogin([
									'email' => $email,
									'pass' => $pass
								]);
								
								if ($login) {
									$_SESSION['user_logged_in'] = true;
									
									// Set the fresh login flag to trigger the cache clearing in header.php
									$_SESSION['fresh_login'] = true;
									
									// Force cache clearing to make sure permissions are refreshed
									$_SESSION['clear_cache'] = true;

									ob_end_clean();
									header('Location: ' . BASEURL);
									exit;
								} else {
									$errors[] = 'User created but unable to log in automatically. Please try logging in.';
								}
							} else {
								$errors[] = 'Unable to create user account. Please try again.';
							}
						}
					}
				}
			}
			
			if (!empty($errors)) {
				$_SESSION['errors'] = $errors;
				$_SESSION['session'] = $_POST;
				ob_end_clean();
				header('Location: ' . BASEURL . 'register.php');
				exit;
			}
			break;

        case 'userdata':
			// Call group class
			$obj_users = new Users();
			$_POST['user_data'] = strip_tags(urldecode($_POST['user_data']));
			$obj_users->insertUserData([
				'user_data' => $_POST['user_data'],
				'user_id' => intval($_POST['user_id']),
				'case_grade' => $_POST['case_grade'],
				'case_score' => $_POST['case_score']
			]);
			break;

        case 'logout':
            session_start(); // Ensure the session is started before destroying it
            $_SESSION = array(); // Clear session data
            if (ini_get("session.use_cookies")) {
                $params = session_get_cookie_params();
                setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
            }
            session_destroy(); // Destroy the session
            header('Location: ' . BASEURL . 'login.php'); // Redirect to login page
            exit;
            break;

        default:
            logMessage("Unknown action: " . $action);
            header('Location: ' . BASEURL . 'login.php');
            exit;
    }
} else {
    logMessage("Invalid request method");
    header('Location: ' . BASEURL . 'login.php');
    exit;
}

// If we've reached this point, something went wrong
error_log("Reached end of user_a.php without redirecting");
header('Location: ' . BASEURL . 'login.php');
exit;
?>