<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/User.php';

$database = new Database();
$db = $database->getConnection();

$user = new User($db);

// Start session for authenticated requests
session_start();

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['action']) && $_GET['action'] === 'current-user') {
            // Get current authenticated user
            require_once __DIR__ . '/../middleware/auth.php';
            $auth = new AuthMiddleware($db);
            $current_user = $auth->authenticate();
            
            if ($current_user) {
                http_response_code(200);
                echo json_encode($current_user);
            } else {
                http_response_code(401);
                echo json_encode(array("message" => "Not authenticated"));
            }
        } elseif(isset($_GET['action']) && $_GET['action'] === 'status') {
            // Check if user is logged in
            if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
                // Validate session by checking if user still exists and is active
                $user->id = $_SESSION['user_id'];
                $user->readOne();
                
                if($user->username && $user->is_active) {
                    http_response_code(200);
                    echo json_encode(array(
                        "message" => "User is authenticated",
                        "user" => array(
                            "id" => $user->id,
                            "username" => $user->username,
                            "email" => $user->email,
                            "first_name" => $user->first_name,
                            "last_name" => $user->last_name,
                            "role" => $user->role
                        )
                    ));
                } else {
                    // User no longer exists or is inactive, destroy session
                    session_destroy();
                    http_response_code(401);
                    echo json_encode(array("message" => "Session invalid - user not found or inactive"));
                }
            } else {
                http_response_code(401);
                echo json_encode(array("message" => "No active session"));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Invalid action"));
        }
        break;
        
    case 'POST':
        $data = json_decode(file_get_contents("php://input"));
        
        if($data->action === 'login') {
            if(!empty($data->username) && !empty($data->password)) {
                $authenticated_user = $user->authenticate($data->username, $data->password);
                
                if($authenticated_user) {
                    $_SESSION['user_id'] = $authenticated_user['id'];
                    $_SESSION['username'] = $authenticated_user['username'];
                    $_SESSION['role'] = $authenticated_user['role'];
                    $_SESSION['first_name'] = $authenticated_user['first_name'];
                    $_SESSION['last_name'] = $authenticated_user['last_name'];
                    
                    http_response_code(200);
                    echo json_encode(array(
                        "message" => "Login successful",
                        "user" => array(
                            "id" => $authenticated_user['id'],
                            "username" => $authenticated_user['username'],
                            "email" => $authenticated_user['email'],
                            "first_name" => $authenticated_user['first_name'],
                            "last_name" => $authenticated_user['last_name'],
                            "role" => $authenticated_user['role']
                        )
                    ));
                } else {
                    http_response_code(401);
                    echo json_encode(array("message" => "Invalid credentials"));
                }
            } else {
                http_response_code(400);
                echo json_encode(array("message" => "Username and password are required"));
            }
        } elseif($data->action === 'register') {
            if(!empty($data->username) && !empty($data->email) && !empty($data->password) && !empty($data->first_name) && !empty($data->last_name)) {
                
                // Check if username or email already exists
                $existing_user = $user->findByEmail($data->email);
                if($existing_user) {
                    http_response_code(409);
                    echo json_encode(array("message" => "Email already exists"));
                    break;
                }
                
                $existing_user = $user->read();
                while($row = $existing_user->fetch(PDO::FETCH_ASSOC)) {
                    if($row['username'] === $data->username) {
                        http_response_code(409);
                        echo json_encode(array("message" => "Username already exists"));
                        break 2;
                    }
                }
                
                $user->username = $data->username;
                $user->email = $data->email;
                $user->password_hash = password_hash($data->password, PASSWORD_DEFAULT);
                $user->first_name = $data->first_name;
                $user->last_name = $data->last_name;
                $user->role = $data->role ?? 'user';
                
                if($user->create()) {
                    http_response_code(201);
                    echo json_encode(array("message" => "User registered successfully"));
                } else {
                    http_response_code(503);
                    echo json_encode(array("message" => "Unable to register user"));
                }
            } else {
                http_response_code(400);
                echo json_encode(array("message" => "Required fields are missing"));
            }
        } elseif($data->action === 'logout') {
            // Start session if not already started
            if (session_status() === PHP_SESSION_NONE) {
                session_start();
            }
            
            // Destroy session
            session_destroy();
            
            http_response_code(200);
            echo json_encode(array("message" => "Logged out successfully"));
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Invalid action"));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
