<?php
require_once __DIR__ . '/../model/users.php';

class UserProcessor
{
    private $user;
    private $action;

    public function __construct()
    {
        $this->user = new User();
        $this->action = isset($_GET['action']) ? $_GET['action'] : '';
        $this->processAction();
    }

    private function processAction()
    {
        switch ($this->action) {
            case 'new':
                $this->create_new_user();
                break;

            case 'update':
                $this->update_user();
                break;
        }
    }

    private function update_user()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!isset($_POST['id'], $_POST['Name'], $_POST['Email'], $_POST['Gender'], $_POST['Status'])) {
                header('Location: ../view/admin/dashboard.php?error=Missing+fields');
                exit();
            }

            $id = (int) $_POST['id'];
            $name = trim($_POST['Name']);
            $email = trim($_POST['Email']);
            $gender = $_POST['Gender'];
            $status = $_POST['Status'];

            if (empty($name) || empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                header('Location: ../model/edit.php?id=' . $id . '&error=Invalid+input');
                exit();
            }

            if ($this->updateUser($id, $name, $email, $gender, $status)) {
                header('Location: ../view/admin/dashboard.php?success=User+updated+successfully');
            } else {
                header('Location: ../model/edit.php?id=' . $id . '&error=Update+failed');
            }
            exit();
        }
    }

    public function getPaginatedUsers($page = 1, $perPage = 10, $searchTerm = '')
    {
        $page = (int) $page;
        $perPage = (int) $perPage;
        $offset = ($page - 1) * $perPage;

        $result = $this->user->getAllUsersWithLimit($perPage, $offset, $searchTerm);
        $total = $this->user->getTotalUserCount($searchTerm);

        return [
            'data' => $result,
            'total' => $total,
            'perPage' => $perPage,
            'currentPage' => $page
        ];
    }

    public function getUserById($id)
    {
        return $this->user->getUserById($id);
    }

    public function updateUser($id, $name, $email, $gender, $status)
    {
        return $this->user->updateUserRecord($id, $name, $email, $gender, $status);
    }

    public function getAllUsers()
    {
        return $this->user->getAllUsers();
    }

    public function getGenderStatistics()
    {
        return [
            'female' => $this->user->getUsersPerGender("female"),
            'male' => $this->user->getUsersPerGender("male"),
            'others' => $this->user->getUsersPerGender("Others")
        ];
    }

    public function getStatusStatistics()
    {
        return [
            'pwd' => $this->user->getUsersPerStatus("PWD"),
            'regular' => $this->user->getUsersPerStatus("Regular")
        ];
    }

    public function processLogin($email, $password, $role)
    {
        $result = $this->user->authenticateUser($email, $password, $role);

        if ($result['success']) {
            $_SESSION['id'] = $result['id'];
            $_SESSION['role'] = $result['role'];
            $_SESSION['user_email'] = $email; 

            // Also set admin_email if the role is Admin
            if ($result['role'] === 'Admin') {
                $_SESSION['admin_email'] = $email;
            }

            $userDetails = $this->user->getUserDetailsByEmail($email);
            if ($userDetails && isset($userDetails['Name'])) {
                $_SESSION['user_full_name'] = $userDetails['Name'];
            } else {
                $_SESSION['user_full_name'] = 'User';
            }
            return true;
        }
        return false;
    }

    public function close()
    {
        $this->user->closeConnection();
    }

    private function create_new_user()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: ../view/admin/dashboard.php');
            exit();
        }

        $email = $_POST['Email'] ?? '';
        $name = ucwords($_POST['Name'] ?? '');
        $password = $_POST['Password'] ?? '';
        $confirmpassword = $_POST['confirmpassword'] ?? '';
        $gender = $_POST['Gender'] ?? '';
        $status = 'Regular';

        if (empty($email) || empty($name) || empty($password) || empty($confirmpassword) || empty($gender)) {
            echo "<script>alert('All fields are required!'); window.history.back();</script>";
            exit();
        }

        if ($password !== $confirmpassword) {
            echo "<script>alert('Passwords do not match!'); window.history.back();</script>";
            exit();
        }

        $result = $this->user->new_user($name, $email, $password, $status, $gender);

        if ($result) {
            echo "<script>alert('User added successfully'); window.location.href='../view/admin/dashboard.php';</script>";
            exit();
        } else {
            echo "<script>alert('Failed to create user. Email may already exist.'); window.history.back();</script>";
            exit();
        }
    }
}

$processor = new UserProcessor();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['user_role'])) {
        $role = $_POST['user_role'] ?? 'User';

        if (!in_array($role, ['User', 'Admin'])) {
            die("Invalid role selected");
        }

        $email = $_POST['email'];
        $password = $_POST['password'];

        // Ensure session is started before calling processLogin
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }

        if ($processor->processLogin($email, $password, $role)) {
            $redirect = ($role === 'Admin') ? "../view/admin/home.php" : "../view/user/home.php";
            header("Location: $redirect");
            exit();
        } else {
            echo "<script>alert('Invalid credentials'); window.history.back();</script>";
        }
    }
}

$processor->close();

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// --- Make cart data from last checkout available for PDF generation ---
$cartJsonForPdf = '[]';
if (isset($_SESSION['last_checkout_cart_json'])) {
    $cartJsonForPdf = $_SESSION['last_checkout_cart_json'];
    unset($_SESSION['last_checkout_cart_json']);
}
// --- End cart data for PDF ---

$userModel = new User();
$currentQueueNumberToShow = 0; 
$currentUserNameToShow = "No one in queue"; 

// Check if a specific queue number was just assigned to this user's session
if (isset($_SESSION['assigned_queue_number'])) {
    $currentQueueNumberToShow = intval($_SESSION['assigned_queue_number']);
    $nameFromAssignedQueue = $userModel->getNameByQueueNumber($currentQueueNumberToShow);

    if ($nameFromAssignedQueue !== null && !empty(trim($nameFromAssignedQueue))) {
        $currentUserNameToShow = htmlspecialchars($nameFromAssignedQueue);
    } elseif ($nameFromAssignedQueue === null && $currentQueueNumberToShow > 0) {
        $currentUserNameToShow = "Error: Your queue data unavailable"; 
    } else {
        $currentUserNameToShow = "Name not available"; 
    }
    unset($_SESSION['assigned_queue_number']);

} else {
    // Fallback to current queue from DB if no specific assignment
    $dbCurrentQueueNumber = $userModel->getCurrentQueue(); 
    if ($dbCurrentQueueNumber > 0) {
        $currentQueueNumberToShow = $dbCurrentQueueNumber;
        $nameFromDbQueue = $userModel->getNameByQueueNumber($dbCurrentQueueNumber);
        if ($nameFromDbQueue !== null && !empty(trim($nameFromDbQueue))) {
            $currentUserNameToShow = htmlspecialchars($nameFromDbQueue);
        } elseif ($nameFromDbQueue === null) {
            $currentUserNameToShow = "Error: Queue data unavailable"; 
        } else {
            $currentUserNameToShow = "Name not available";
        }
    }
}

$currentQueueNumber = $currentQueueNumberToShow;
$currentUserName = $currentUserNameToShow;

$userModel->closeConnection();
?>