<?php
class UserController extends Controller {

    public function index() {
        $userModel = $this->model('User');

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

        // Handle Add
        if (isset($_POST['add'])) {
            $email = $_POST['email'];
            if ($userModel->emailExists($email)) {
                $_SESSION['message'] = "Email already exists!";
                header("Location: " . BASE_URL . "/user");
                exit;
            }

            $userModel->register([
                'username' => $_POST['username'],
                'phone' => $_POST['phone'],
                'email' => $_POST['email'],
                'password' => $_POST['password'],
                'user_type' => $_POST['user_type']
            ]);

            $_SESSION['message'] = "User added successfully!";
            header("Location: " . BASE_URL . "/user");
            exit;
        }

        // Handle Edit
        if (isset($_POST['edit'])) {
            $id = $_POST['id'];

            $data = [
                'username' => $_POST['username'],
                'phone' => $_POST['phone'],
                'email' => $_POST['email'],
                'user_type' => $_POST['user_type']
            ];

            if (!empty($_POST['password'])) {
                $data['password'] = $_POST['password'];
            }

            $userModel->updateUser($id, $data);

            $_SESSION['message'] = "User updated successfully!";
            header("Location: " . BASE_URL . "/user");
            exit;
        }

        // Handle Delete
        if (isset($_GET['delete'])) {
            $id = $_GET['delete'];
            $userModel->deleteUser($id);
            $_SESSION['message'] = "User deleted successfully!";
            header("Location: " . BASE_URL . "/user");
            exit;
        }

        // Fetch all users
        $data['users'] = $userModel->getAllUsers();
        $data['title'] = "Users";

        $this->view('templates/header', $data);
        $this->view('user/index', $data);
        $this->view('templates/footer', $data);
    }
}
