<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check for session or cookie authentication
if (!isset($_SESSION['user_id']) && isset($_COOKIE['user_auth'])) {
    $userId = unserialize(base64_decode($_COOKIE['user_auth']));
    if ($userId) {
        $_SESSION['user_id'] = $userId;
    }
}

// Prevent multiple redirects by checking the current page
if (!isset($_SESSION['user_id']) && $_SERVER['REQUEST_URI'] !== '/login.php') {
    header('Location: /login.php');
    exit;
}

// Handle logout action
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    setcookie('user_auth', '', time() - 3600, "/"); 
    header('Location: /login.php');
    exit;
}

// Autoload for classes
spl_autoload_register(function ($class_name) {
    $paths = ['c/', 'm/'];
    foreach ($paths as $path) {
        $file = $path . $class_name . '.php';
        if (file_exists($file)) {
            require_once $file;
            return;
        }
    }
});

// Load models and controllers
$db = new DB();
$itemController = new ItemController(new Item($db));
$itemData = $itemController->showItems();

$cartController = new CartController(new Cart($db));
$cartData = $cartController->getCartItems($_SESSION['user_id']);

$orderController = new OrderController(new Order($db));
$orderData = $orderController->getOrdersByUserId($_SESSION['user_id']);
$hasUnconfirmedClearance = $orderController->hasUnconfirmedClearance($_SESSION['user_id']);

$clearanceController = new ClearanceController(new Clearance($db));
$clearanceData = $clearanceController->getClearanceData($_SESSION['user_id']);

$userController = new UserController(new User($db));

// Switch views
if (isset($_GET['view'])) {
    header('Content-Type: text/html');
    $tags = $itemController->showItems(); 

    switch ($_GET['view']) {
        case 'cart':
            loadView('cart', ['tags' => $tags['tags'], 'cartItems' => $cartData]);
            break;

        case 'order':
            loadView('order', ['tags' => $tags['tags'], 'orderItems' => $orderData, 'hasUnconfirmedClearance' => $hasUnconfirmedClearance]);
            break;

        case 'clearance':
             $userId = $_SESSION['user_id'];
             $selectedUserId = isset($_GET['user_id']) ? $_GET['user_id'] : null;

             // Determine which user's data to fetch
             if ($userId == 1 && $selectedUserId) {
                 // Admin viewing another user's clearance data
                 $clearanceData = $clearanceController->getClearanceData($selectedUserId);
                 $clearanceHistory = $clearanceController->getClearanceHistoryByUserId($selectedUserId);
             } else {
                 // Regular user or admin without selected user
                 $clearanceData = $clearanceController->getClearanceData($userId);
                 $clearanceHistory = $clearanceController->getClearanceHistoryByUserId($userId);
             }

             // Get all users if admin
             if ($userId == 1) {
                 $users = $clearanceController->getAllUsers();
             } else {
                 $users = [];
             }

             loadView('clearance', [
                 'tags' => $tags['tags'],
                 'clearanceData' => $clearanceData,
                 'clearanceHistory' => $clearanceHistory,
                 'users' => $users,
                 'selectedUserId' => $selectedUserId,
             ]);
             break;

        case 'dashboard':
            loadView('dashboard', ['tags' => $tags['tags']]);
            break;
}

    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    $actionMap = [
        'update_order'     => 'handleCartRequests',
        'delete_item'      => 'handleCartRequests',
        'confirm_order'    => 'handleCartRequests',
        'add_to_cart'      => 'handleCartRequests',
        'sell'             => 'handleOrderRequests',
        'return'           => 'handleOrderRequests',
        'finalize_deal'    => 'handleOrderRequests',
        'confirm_invoice'  => 'handleClearanceRequests',
        'reset_orders'     => 'handleOrderRequests',
    ];
    
    if (isset($data['action'])) {
        $action = $data['action'];
        
        if (isset($actionMap[$action])) {
            $handlerFunction = $actionMap[$action];
            if ($handlerFunction === 'handleCartRequests') {
                handleCartRequests($data, $cartController);
            } elseif ($handlerFunction === 'handleOrderRequests') {
                handleOrderRequests($data, $orderController);
            } elseif ($handlerFunction === 'handleClearanceRequests') {
                handleClearanceRequests($data, $clearanceController);
            }
        } else {
            // Handle unknown actions
            echo json_encode(['success' => false, 'message' => 'Action not recognized']);
        }
        exit;
    }
}

// Load item page
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $itemId = (int)$_GET['id'];
    $item = $itemController->showItem($itemId);
    if ($item) {
        $data = $itemController->showItems();
        $tags = $data['tags'];
        loadView('item', ['item' => $item, 'tags' => $tags]);
        exit; // Make sure to exit after loading the item view
    }
}

// Load main view
loadView('main', [
    'items' => $itemData['items'] ?? [],
    'tags'  => $itemData['tags'] ?? []
]);


function loadView($view, $v = null) {
    if (is_array($v)) {
        extract($v);
    }
    require 'v/' . $view . '.php';
}


function handleCartRequests($data, $cartController) {
    if (isset($data['action'])) {
        switch ($data['action']) {
            case 'update_order':
                $cartController->updateItemQuantity();
                break;
            case 'delete_item':
                $cartController->removeItem();
                break;
            case 'confirm_order':
                $cartController->confirmOrder();
                break;
            case 'add_to_cart':
                if (isset($data['itemId'], $data['quantity'], $data['totalPrice'])) {
                    $cartController->addToCart($_SESSION['user_id'], $data['itemId'], $data['quantity'], $data['totalPrice']);
                    echo json_encode(['success' => true]);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Invalid data']);
                }
                break;
            default:
                echo json_encode(['success' => false, 'message' => 'Cart action not recognized']);
                break;
        }
    } 
}

function handleOrderRequests($data, $orderController) {
    if (isset($data['action'])) {
        switch ($data['action']) {
            case 'sell':
                echo json_encode($orderController->sell($_SESSION['user_id'], $data['itemId'], $data['quantityToSell']));
                break;
            case 'return':
                echo json_encode($orderController->return($_SESSION['user_id'], $data['itemId'], $data['quantityToReturn']));
                break;
            case 'reset_orders':
                echo json_encode($orderController->resetOrders($_SESSION['user_id']));
                break;
            case 'finalize_deal':
                echo json_encode($orderController->finalizeDeal($data['itemIds']));
                break;
        }
    }
}

function handleClearanceRequests($data, $clearanceController) {
    if (isset($data['action'])) {
        switch ($data['action']) {
            case 'confirm_invoice':
                if (!($_SESSION['user_id'] == 1)) {
                    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
                    exit;
                }
                if (!isset($data['invoiceId']) || !is_numeric($data['invoiceId'])) {
                    echo json_encode(['success' => false, 'message' => 'Invoice ID is required and must be a number.']);
                    exit;
                }
                $result = $clearanceController->confirmInvoice($data['invoiceId']);
                echo json_encode($result);
                break;
            default:
                echo json_encode(['success' => false, 'message' => 'Clearance action not recognized']);
                break;
        }
    }
}
