<?php

require_once APP_ROOT . '/models/Collection.php';
require_once APP_ROOT . '/models/Subcollection.php';

class CollectionController
{
    private Collection $collectionModel;

    public function __construct()
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }
        $this->collectionModel = new Collection();
    }

    public function create(): void
    {
        $type = $_GET['type'] ?? 'banknote';
        require APP_ROOT . '/views/collections/create.php';
    }

    public function store(): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $type = $_POST['type'] ?? 'banknote';

        $validator = new Validator();
        $validator->required('name', $name, Lang::get('collection_name'));

        if ($validator->fails()) {
            Session::flash('error', $validator->firstError());
            header('Location: ' . APP_URL . '/collections/create');
            exit;
        }

        $collectionId = $this->collectionModel->create([
            'user_id'     => Session::getUserId(),
            'name'        => $name,
            'description' => $description,
            'type'        => $type,
        ]);

        // Create subcollections if provided
        if (!empty($_POST['subcollections'])) {
            $subModel = new Subcollection();
            foreach ($_POST['subcollections'] as $index => $sub) {
                $subName = trim($sub['name'] ?? '');
                if (!empty($subName)) {
                    $subModel->create([
                        'collection_id' => $collectionId,
                        'name'          => $subName,
                        'description'   => trim($sub['description'] ?? ''),
                        'sort_order'    => $index,
                    ]);
                }
            }
        }

        Session::flash('success', Lang::get('collection_created'));
        header('Location: ' . APP_URL . '/collections/' . $collectionId);
        exit;
    }

    public function show(string $id): void
    {
        $collection = $this->collectionModel->findById((int)$id);
        if (!$collection) {
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        $isOwner = $collection['user_id'] === Session::getUserId();

        if (!$isOwner) {
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        $subModel = new Subcollection();
        $subcollections = $subModel->getAllByCollection((int)$id);

        foreach ($subcollections as &$sub) {
            $sub['item_count'] = $subModel->countItems($sub['id']);
        }
        unset($sub);

        require APP_ROOT . '/views/collections/show.php';
    }

    public function edit(string $id): void
    {
        $collection = $this->collectionModel->findById((int)$id);
        if (!$collection) {
            header('Location: ' . APP_URL . '/home');
            exit;
        }
        require APP_ROOT . '/views/collections/edit.php';
    }

    public function update(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/collections/' . $id . '/edit');
            exit;
        }

        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');

        $validator = new Validator();
        $validator->required('name', $name, Lang::get('collection_name'));

        if ($validator->fails()) {
            Session::flash('error', $validator->firstError());
            header('Location: ' . APP_URL . '/collections/' . $id . '/edit');
            exit;
        }

        $this->collectionModel->update((int)$id, [
            'name'        => $name,
            'description' => $description,
        ]);

        Session::flash('success', Lang::get('collection_updated'));
        header('Location: ' . APP_URL . '/collections/' . $id);
        exit;
    }

    public function delete(string $id): void
    {
        $this->collectionModel->delete((int)$id);
        Session::flash('success', Lang::get('collection_deleted'));
        header('Location: ' . APP_URL . '/home');
        exit;
    }

    public function moveUp(string $id): void
    {
        $col = $this->collectionModel->findById((int)$id);
        if (!$col) { header('Location: ' . APP_URL . '/home'); exit; }

        $all = $this->collectionModel->getAllByUser(Session::getUserId());
        foreach ($all as $i => $c) {
            if ($c['id'] == (int)$id && $i > 0) {
                $this->collectionModel->swap((int)$id, $all[$i - 1]['id'], Session::getUserId());
                break;
            }
        }
        header('Location: ' . APP_URL . '/home');
        exit;
    }

    public function moveDown(string $id): void
    {
        $col = $this->collectionModel->findById((int)$id);
        if (!$col) { header('Location: ' . APP_URL . '/home'); exit; }

        $all = $this->collectionModel->getAllByUser(Session::getUserId());
        $count = count($all);
        foreach ($all as $i => $c) {
            if ($c['id'] == (int)$id && $i < $count - 1) {
                $this->collectionModel->swap((int)$id, $all[$i + 1]['id'], Session::getUserId());
                break;
            }
        }
        header('Location: ' . APP_URL . '/home');
        exit;
    }

    public function downloadSample(string $id, string $type): void
    {
        $collection = $this->collectionModel->findById((int)$id);
        if (!$collection || $collection['user_id'] !== Session::getUserId()) {
            header('Location: ' . APP_URL . '/home');
            exit;
        }

        require_once APP_ROOT . '/helpers/ExcelHelper.php';
        $excelHelper = new ExcelHelper();
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="sample_' . $type . '.xlsx"');
        header('Cache-Control: max-age=0');
        
        $excelHelper->generateSampleFile($type);
        exit;
    }

    public function testRoute(): void
    {
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'message' => 'Test route is working', 'timestamp' => date('Y-m-d H:i:s')]);
        exit;
    }

    public function import(): void
    {
        header('Content-Type: application/json');
        
        try {
            if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
                echo json_encode(['success' => false, 'message' => 'Invalid request']);
                exit;
            }

            if (!isset($_FILES['importFile']) || $_FILES['importFile']['error'] !== UPLOAD_ERR_OK) {
                $uploadError = $_FILES['importFile']['error'] ?? 'unknown';
                echo json_encode(['success' => false, 'message' => 'File upload failed', 'error_code' => $uploadError]);
                exit;
            }

            $collectionId = (int)($_POST['collectionId'] ?? 0);
            $collectionType = $_POST['collectionType'] ?? 'banknote';
            $subcollectionId = !empty($_POST['subcollectionId']) ? (int)$_POST['subcollectionId'] : null;
            
            $collection = $this->collectionModel->findById($collectionId);
            if (!$collection || $collection['user_id'] !== Session::getUserId()) {
                echo json_encode(['success' => false, 'message' => 'Collection not found']);
                exit;
            }

            require_once APP_ROOT . '/helpers/ExcelHelper.php';
            $excelHelper = new ExcelHelper();
            
            $result = $excelHelper->importFromFile($_FILES['importFile']['tmp_name'], $collectionId, $collectionType, $subcollectionId);
            echo json_encode($result);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Import failed: ' . $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        } catch (Error $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Fatal error: ' . $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
        exit;
    }

    public function getSubcollectionsJson(int $id): void
    {
        header('Content-Type: application/json');
        
        try {
            $collectionId = $id;
            
            $collection = $this->collectionModel->findById($collectionId);
            if (!$collection || $collection['user_id'] !== Session::getUserId()) {
                echo json_encode(['success' => false, 'message' => 'Collection not found']);
                exit;
            }

            // Use Subcollection model like in the show method
            $subModel = new Subcollection();
            $subcollections = $subModel->getAllByCollection($collectionId);

            // Add item count to each subcollection
            foreach ($subcollections as &$sub) {
                $sub['item_count'] = $subModel->countItems($sub['id']);
            }
            unset($sub);
            
            echo json_encode([
                'success' => true,
                'subcollections' => $subcollections
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false, 
                'message' => 'Error fetching subcollections: ' . $e->getMessage()
            ]);
        }
        exit;
    }
}
