<?php
require_once 'config/db.php';
require_once 'config/constants.php';

// Simple Router
$page = isset($_GET['page']) ? $_GET['page'] : 'home';
$action = isset($_GET['action']) ? $_GET['action'] : 'index';

// Auto-load controllers
spl_autoload_register(function ($class_name) {
    if (file_exists('controllers/' . $class_name . '.php')) {
        require_once 'controllers/' . $class_name . '.php';
    }
});

switch ($page) {
    case 'auth':
        $controller = new AuthController($conn);
        if ($action == 'login') $controller->login();
        elseif ($action == 'register') $controller->register();
        elseif ($action == 'logout') $controller->logout();
        elseif ($action == 'admin_login') $controller->adminLogin();
        else $controller->login();
        break;

    case 'admin':
        require_once 'controllers/AdminController.php';
        $controller = new AdminController($conn);
        if (!isAdmin()) {
            header("Location: " . BASE_URL . "?page=auth&action=admin_login");
            exit;
        }
        if ($action == 'dashboard') $controller->dashboard();
        elseif ($action == 'users') $controller->users();
        elseif ($action == 'activate') $controller->activateUser();
        elseif ($action == 'deactivate') $controller->deactivateUser();
        elseif ($action == 'delete') $controller->deleteUser();
        elseif ($action == 'add_user') $controller->addUser();
        elseif ($action == 'edit_user') $controller->editUser();
        else $controller->dashboard();
        break;

    case 'user':
        require_once 'controllers/UserController.php';
        $controller = new UserController($conn);
        if (!isLoggedIn()) {
            header("Location: " . BASE_URL . "?page=auth&action=login");
            exit;
        }
        if ($action == 'dashboard') $controller->dashboard();
        elseif ($action == 'contacts') $controller->contacts();
        elseif ($action == 'add_contact') $controller->addContact();
        elseif ($action == 'import_contacts') $controller->importContacts();
        elseif ($action == 'birthdays') $controller->birthdays();
        elseif ($action == 'send_wishes') $controller->sendWishes();
        elseif ($action == 'template') $controller->template();
        else $controller->dashboard();
        break;

    default:
        // Redirect to Login
        if (isLoggedIn()) {
            header("Location: " . BASE_URL . "?page=user&action=dashboard");
        } else {
            header("Location: " . BASE_URL . "?page=auth&action=login");
        }
        break;
}
?>
