<?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') {
            // Validate required fields
            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'];

            // Additional validation
            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)
    {
        $sql = "SELECT * FROM user_records WHERE ID = ?";
        $stmt = $this->user->getConnection()->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    public function updateUser($id, $name, $email, $gender, $status)
    {
        $sql = "UPDATE user_records SET Name = ?, Email = ?, Gender = ?, Status = ? WHERE ID = ?";
        $stmt = $this->user->getConnection()->prepare($sql);
        $stmt->bind_param("ssssi", $name, $email, $gender, $status, $id);
        return $stmt->execute();
    }

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

// Start session and handle requests
session_start();

// Initialize processor only once
$processor = new UserProcessor();

// Handle POST requests
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 ($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();
?>