<?php

require_once APP_ROOT . '/models/Wishlist.php';
require_once APP_ROOT . '/models/Item.php';
require_once APP_ROOT . '/models/Coin.php';

class WishlistController
{
    public function index(): void
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }

        $wishlist = new Wishlist();
        $userId = Session::getUserId();
        
        $wishlistItems = $wishlist->getUserWishlist($userId);
        $stats = $wishlist->getWishlistStats($userId);
        
        require APP_ROOT . '/views/wishlist/index.php';
    }

    public function apiAdd(): void
    {
        if (!Session::isLoggedIn()) {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }

        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Invalid request']);
            exit;
        }

        $itemType = $_POST['item_type'] ?? '';
        $itemId = (int)($_POST['item_id'] ?? 0);
        $notes = $_POST['notes'] ?? '';
        $targetPrice = $_POST['target_price'] ?? '';
        $priority = $_POST['priority'] ?? 'medium';

        if (!in_array($itemType, ['item', 'coin']) || $itemId <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid item data']);
            exit;
        }

        // Validate item exists
        if ($itemType === 'item') {
            $itemModel = new Item();
            $item = $itemModel->findById($itemId);
        } else {
            $coinModel = new Coin();
            $item = $coinModel->findById($itemId);
        }

        if (!$item) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Item not found']);
            exit;
        }

        $wishlist = new Wishlist();
        $userId = Session::getUserId();

        $data = [
            'notes' => $notes ?: null,
            'priority' => in_array($priority, ['low', 'medium', 'high']) ? $priority : 'medium',
        ];

        if ($targetPrice && is_numeric($targetPrice)) {
            $data['target_price'] = (float)$targetPrice;
        }

        try {
            $wishlistId = $wishlist->addToWishlist($userId, $itemType, $itemId, $data);
            $wishlistCount = $wishlist->getWishlistCount($userId);
            
            echo json_encode([
                'success' => true,
                'message' => 'Item added to wishlist',
                'wishlist_id' => $wishlistId,
                'wishlist_count' => $wishlistCount,
                'is_in_wishlist' => true
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to add to wishlist']);
        }
        exit;
    }

    public function apiRemove(): void
    {
        if (!Session::isLoggedIn()) {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }

        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Invalid request']);
            exit;
        }

        $itemType = $_POST['item_type'] ?? '';
        $itemId = (int)($_POST['item_id'] ?? 0);

        if (!in_array($itemType, ['item', 'coin']) || $itemId <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid item data']);
            exit;
        }

        $wishlist = new Wishlist();
        $userId = Session::getUserId();

        try {
            $success = $wishlist->removeFromWishlist($userId, $itemType, $itemId);
            $wishlistCount = $wishlist->getWishlistCount($userId);
            
            echo json_encode([
                'success' => $success,
                'message' => $success ? 'Item removed from wishlist' : 'Failed to remove from wishlist',
                'wishlist_count' => $wishlistCount,
                'is_in_wishlist' => false
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to remove from wishlist']);
        }
        exit;
    }

    public function apiCheck(): void
    {
        if (!Session::isLoggedIn()) {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }

        $itemType = $_GET['item_type'] ?? '';
        $itemId = (int)($_GET['item_id'] ?? 0);

        if (!in_array($itemType, ['item', 'coin']) || $itemId <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid item data']);
            exit;
        }

        $wishlist = new Wishlist();
        $userId = Session::getUserId();

        $isInWishlist = $wishlist->isInWishlist($userId, $itemType, $itemId);
        $wishlistItem = null;

        if ($isInWishlist) {
            $wishlistItem = $wishlist->getWishlistItem($userId, $itemType, $itemId);
        }

        echo json_encode([
            'success' => true,
            'is_in_wishlist' => $isInWishlist,
            'wishlist_item' => $wishlistItem
        ]);
        exit;
    }

    public function apiUpdate(): void
    {
        if (!Session::isLoggedIn()) {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }

        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Invalid request']);
            exit;
        }

        $itemType = $_POST['item_type'] ?? '';
        $itemId = (int)($_POST['item_id'] ?? 0);
        $notes = $_POST['notes'] ?? null;
        $targetPrice = $_POST['target_price'] ?? null;
        $priority = $_POST['priority'] ?? null;

        if (!in_array($itemType, ['item', 'coin']) || $itemId <= 0) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid item data']);
            exit;
        }

        $wishlist = new Wishlist();
        $userId = Session::getUserId();

        // Check if item is in wishlist
        if (!$wishlist->isInWishlist($userId, $itemType, $itemId)) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Item not in wishlist']);
            exit;
        }

        $data = [];
        if ($notes !== null) {
            $data['notes'] = $notes ?: null;
        }
        if ($targetPrice !== null && is_numeric($targetPrice)) {
            $data['target_price'] = (float)$targetPrice;
        }
        if ($priority !== null && in_array($priority, ['low', 'medium', 'high'])) {
            $data['priority'] = $priority;
        }

        if (empty($data)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'No valid data to update']);
            exit;
        }

        try {
            $success = $wishlist->updateWishlistItem($userId, $itemType, $itemId, $data);
            
            echo json_encode([
                'success' => $success,
                'message' => $success ? 'Wishlist item updated' : 'Failed to update wishlist item'
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update wishlist item']);
        }
        exit;
    }

    public function apiStats(): void
    {
        if (!Session::isLoggedIn()) {
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            exit;
        }

        $wishlist = new Wishlist();
        $userId = Session::getUserId();
        
        $stats = $wishlist->getWishlistStats($userId);
        
        echo json_encode([
            'success' => true,
            'stats' => $stats
        ]);
        exit;
    }
}
