<?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['full_name'], $_POST['email'], $_POST['gender'], $_POST['status'], $_POST['phone'], $_POST['address'], $_POST['city'])) {
                header('Location: ../view/admin/dashboard.php?error=Missing+fields');
                exit();
            }

            $id = (int) $_POST['id'];
            $fullName = trim($_POST['full_name']);
            $email = trim($_POST['email']);
            $gender = $_POST['gender'];
            $status = $_POST['status'];
            $phone = trim($_POST['phone']);
            $address = trim($_POST['address']);
            $city = trim($_POST['city']);

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

            if ($this->user->updateUserRecord($id, $fullName, $email, $gender, $status, $phone, $address, $city)) {
                header('Location: ../view/admin/dashboard.php?success=User+updated+successfully');
            } else {
                header('Location: ../view/admin/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)
    {
        trigger_error("UserProcessor::updateUser is deprecated or needs full parameters for updateUserRecord", E_USER_WARNING);
        return false;
    }

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

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

    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'];
            
            if ($result['role'] === 'Admin') {
                $_SESSION['admin_email'] = $email;
                $adminDetails = $this->user->getAdminByEmail($email);
                $_SESSION['admin_full_name'] = $adminDetails['full_name'] ?? 'Admin';
                $_SESSION['user_email'] = $email;
                $_SESSION['user_full_name'] = $_SESSION['admin_full_name'];

            } else {
                $_SESSION['user_email'] = $email;
                $userDetails = $this->user->getUserDetailsByEmail($email);
                if ($userDetails && isset($userDetails['full_name'])) {
                    $_SESSION['user_full_name'] = $userDetails['full_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'] ?? '';
        $fullName = ucwords($_POST['full_name'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmpassword = $_POST['confirmpassword'] ?? '';
        $gender = $_POST['gender'] ?? '';
        $status = $_POST['status'] ?? 'Regular';
        $phone = $_POST['phone'] ?? '';
        $address = $_POST['address'] ?? '';
        $city = $_POST['city'] ?? '';

        if (empty($email) || empty($fullName) || empty($password) || empty($confirmpassword) || empty($gender) || empty($phone) || empty($address) || empty($city) || empty($status)) {
            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($fullName, $email, $password, $status, $gender, $phone, $address, $city);

        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'];

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

        if ($processor->processLogin($email, $password, $role)) {
            if ($role === 'Admin') {
                 $_SESSION['admin_id'] = $_SESSION['id'];
            } else {
                 $_SESSION['user_id'] = $_SESSION['id'];
            }

            $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();
}

$cartJsonForPdf = '[]';
if (isset($_SESSION['last_checkout_cart_json'])) {
    $cartJsonForPdf = $_SESSION['last_checkout_cart_json'];
    unset($_SESSION['last_checkout_cart_json']);
}

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

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 {
    $dbCurrentQueueNumber = $userModel->getCurrentQueue(); 
    if ($dbCurrentQueueNumber > 0) {
        $currentQueueNumberToShow = $dbCurrentQueueNumber;
        $nameFromDbQueue = $userModel->getNameByQueueNumber($dbCurrentQueueNumber);
        if ($nameFromDbQueue !== null && !empty(trim($nameFromDbQueue))) {
            $currentUserNameToShow = htmlspecialchars($nameFromDbQueue);
        } elseif ($nameFromDbQueue === null && $dbCurrentQueueNumber > 0) {
            $currentUserNameToShow = "Error: User for queue " . $dbCurrentQueueNumber . " not found or name unavailable"; 
        } else {
            $currentUserNameToShow = "No one in queue";
        }
    }
}

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

$userModel->closeConnection();
?>