<?php

class MenuVersionController
{
    private $pdo;

    public function __construct()
    {
        require_once __DIR__ . '/../../bootstrap/db.php';
        global $pdo;
        $this->pdo = $pdo;
        
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $this->checkAuth();
    }
    
    private function checkAuth()
    {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /samanta_crm/login');
            exit;
        }
    }
    
    private function render($view, $data = [])
    {
        extract($data);
        ob_start();
        require_once __DIR__ . '/../Views/' . $view . '.php';
        $content = ob_get_clean();
        
        require_once __DIR__ . '/../Views/layout.php';
    }

    /**
     * Display list of menu versions for a location
     */
    public function index()
    {
        $locationId = $_GET['location_id'] ?? null;
        
        // Get all locations for dropdown
        $stmt = $this->pdo->query("SELECT * FROM locations WHERE is_active = 1 ORDER BY name");
        $locations = $stmt->fetchAll();
        
        // Get versions if location selected
        $versions = [];
        $selectedLocation = null;
        if ($locationId) {
            $stmt = $this->pdo->prepare("
                SELECT v.*, l.name as location_name 
                FROM menu_versions v
                JOIN locations l ON v.location_id = l.id
                WHERE v.location_id = ?
                ORDER BY v.created_at DESC
            ");
            $stmt->execute([$locationId]);
            $versions = $stmt->fetchAll();
            
            $stmt = $this->pdo->prepare("SELECT * FROM locations WHERE id = ?");
            $stmt->execute([$locationId]);
            $selectedLocation = $stmt->fetch();
        }
        
        $this->render('menu/versions', [
            'locations' => $locations,
            'versions' => $versions,
            'selectedLocation' => $selectedLocation,
            'locationId' => $locationId
        ]);
    }

    /**
     * Create new version snapshot
     */
    public function create()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/menu/versions');
            exit;
        }

        $locationId = $_POST['location_id'] ?? null;
        $versionName = $_POST['version_name'] ?? null;
        $description = $_POST['description'] ?? '';

        if (!$locationId || !$versionName) {
            $_SESSION['error'] = 'Location and version name are required';
            header('Location: /samanta_crm/menu/versions?location_id=' . $locationId);
            exit;
        }

        // Export current menu state to JSON
        $menuData = $this->exportMenuData($locationId);
        
        $stmt = $this->pdo->prepare("
            INSERT INTO menu_versions (location_id, version_name, description, json_data, created_by)
            VALUES (?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $locationId,
            $versionName,
            $description,
            json_encode($menuData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
            $_SESSION['user']['username'] ?? 'system'
        ]);

        $_SESSION['success'] = 'Version snapshot created successfully';
        header('Location: /samanta_crm/menu/versions?location_id=' . $locationId);
        exit;
    }

    /**
     * Download version as JSON file
     */
    public function download()
    {
        $versionId = $_GET['id'] ?? null;
        
        if (!$versionId) {
            http_response_code(404);
            exit;
        }

        $stmt = $this->pdo->prepare("
            SELECT v.*, l.name as location_name 
            FROM menu_versions v
            JOIN locations l ON v.location_id = l.id
            WHERE v.id = ?
        ");
        $stmt->execute([$versionId]);
        $version = $stmt->fetch();

        if (!$version) {
            http_response_code(404);
            exit;
        }

        $filename = 'menu_' . $this->slugify($version['location_name']) . '_' . $this->slugify($version['version_name']) . '.json';

        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-cache, must-revalidate');
        
        echo $version['json_data'];
        exit;
    }

    /**
     * Download version as standalone HTML viewer
     */
    public function downloadViewer()
    {
        $versionId = $_GET['id'] ?? null;
        
        if (!$versionId) {
            http_response_code(404);
            exit;
        }

        $stmt = $this->pdo->prepare("
            SELECT v.*, l.name as location_name 
            FROM menu_versions v
            JOIN locations l ON v.location_id = l.id
            WHERE v.id = ?
        ");
        $stmt->execute([$versionId]);
        $version = $stmt->fetch();

        if (!$version) {
            http_response_code(404);
            exit;
        }

        $menuData = json_decode($version['json_data'], true);
        $htmlContent = $this->generateStandaloneHTML($menuData);
        
        $filename = 'menu_' . $this->slugify($version['location_name']) . '_' . $this->slugify($version['version_name']) . '.html';

        header('Content-Type: text/html; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: no-cache, must-revalidate');
        
        echo $htmlContent;
        exit;
    }

    /**
     * Delete version
     */
    public function delete()
    {
        $versionId = $_POST['id'] ?? null;
        
        if (!$versionId) {
            http_response_code(404);
            exit;
        }

        $stmt = $this->pdo->prepare("DELETE FROM menu_versions WHERE id = ?");
        $stmt->execute([$versionId]);

        $_SESSION['success'] = 'Version deleted successfully';
        header('Location: /samanta_crm/menu/versions?location_id=' . ($_POST['location_id'] ?? ''));
        exit;
    }

    /**
     * Export menu data for a location
     */
    private function exportMenuData($locationId)
    {
        // Get location info
        $stmt = $this->pdo->prepare("SELECT * FROM locations WHERE id = ?");
        $stmt->execute([$locationId]);
        $location = $stmt->fetch();

        // Get all menu items for this location with categories
        $stmt = $this->pdo->prepare("
            SELECT 
                mi.*,
                mc.name as category_name,
                mc.name_en as category_name_en,
                mc.sort_order as category_sort_order
            FROM menu_items mi
            JOIN menu_item_locations mil ON mi.id = mil.menu_item_id
            JOIN menu_categories mc ON mi.menu_category_id = mc.id
            WHERE mil.location_id = ? AND mi.is_active = 1
            ORDER BY mc.sort_order, mi.display_order
        ");
        $stmt->execute([$locationId]);
        $items = $stmt->fetchAll();

        // Group by category
        $groupedItems = [];
        foreach ($items as $item) {
            $categoryName = $item['category_name'];
            if (!isset($groupedItems[$categoryName])) {
                $groupedItems[$categoryName] = [
                    'sort_order' => $item['category_sort_order'],
                    'name_en' => $item['category_name_en'],
                    'items' => []
                ];
            }
            $groupedItems[$categoryName]['items'][] = [
                'id' => $item['id'],
                'code' => $item['code'],
                'name_pl' => $item['name_pl'],
                'name_en' => $item['name_en'],
                'description_pl' => $item['description_pl'],
                'description_en' => $item['description_en'],
                'price_1' => $item['price_1'],
                'price_1_prefix_pl' => $item['price_1_prefix_pl'],
                'price_1_prefix_en' => $item['price_1_prefix_en'],
                'price_2' => $item['price_2'],
                'price_2_prefix_pl' => $item['price_2_prefix_pl'],
                'price_2_prefix_en' => $item['price_2_prefix_en'],
                'price_3' => $item['price_3'],
                'price_3_prefix_pl' => $item['price_3_prefix_pl'],
                'price_3_prefix_en' => $item['price_3_prefix_en'],
                'image_url' => $item['image_url'],
                'display_order' => $item['display_order']
            ];
        }

        return [
            'version' => '1.0',
            'exported_at' => date('Y-m-d H:i:s'),
            'location' => [
                'id' => $location['id'],
                'name' => $location['name']
            ],
            'categories' => $groupedItems
        ];
    }

    /**
     * Generate standalone HTML file with embedded JSON
     */
    private function generateStandaloneHTML($menuData)
    {
        $jsonData = json_encode($menuData, JSON_UNESCAPED_UNICODE);
        
        ob_start();
        include __DIR__ . '/../Views/menu/standalone_template.php';
        return ob_get_clean();
    }

    /**
     * Convert string to URL-friendly slug
     */
    private function slugify($text)
    {
        $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
        $text = preg_replace('/[^a-zA-Z0-9]+/', '_', $text);
        $text = trim($text, '_');
        $text = strtolower($text);
        return $text;
    }
}
