<?php

require_once '../app/Models/Language.php';
require_once '../app/Models/Translation.php';

class LanguageController
{
    private $languageModel;
    private $translationModel;
    
    public function __construct()
    {
        $this->languageModel = new Language();
        $this->translationModel = new Translation();
        $this->checkAuth();
        $this->checkAdminAccess();
    }
    
    private function checkAuth()
    {
        if (!isset($_SESSION['user_id'])) {
            redirect('login');
            exit;
        }
    }
    
    private function checkAdminAccess()
    {
        if ($_SESSION['user_role'] !== 'admin') {
            $_SESSION['error'] = 'Access denied. Admin privileges required.';
            redirect('dashboard');
            exit;
        }
    }
    
    public function index()
    {
        $languages = $this->languageModel->getAll();
        $this->view('languages/index', ['languages' => $languages]);
    }
    
    public function create()
    {
        $this->view('languages/create');
    }
    
    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('languages/create');
            exit;
        }
        
        $data = [
            'code' => strtolower($_POST['code'] ?? ''),
            'name' => $_POST['name'] ?? '',
            'native_name' => $_POST['native_name'] ?? '',
            'flag' => $_POST['flag'] ?? '',
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'is_default' => isset($_POST['is_default']) ? 1 : 0
        ];
        
        // Validation
        if (empty($data['code']) || empty($data['name'])) {
            $_SESSION['error'] = 'Language code and name are required';
            redirect('languages/create');
            exit;
        }
        
        // Validate language code format (ISO 639-1)
        if (!preg_match('/^[a-z]{2}$/', $data['code'])) {
            $_SESSION['error'] = 'Language code must be 2 lowercase letters (ISO 639-1)';
            redirect('languages/create');
            exit;
        }
        
        // Check if code already exists
        if ($this->languageModel->findByCode($data['code'])) {
            $_SESSION['error'] = 'Language code already exists';
            redirect('languages/create');
            exit;
        }
        
        // If this is set as default, remove default from others
        if ($data['is_default']) {
            $this->languageModel->setDefault(0); // Remove all defaults first
        }
        
        if ($this->languageModel->create($data)) {
            $_SESSION['success'] = 'Language created successfully';
            
            // Create basic translations for new language
            $this->createBasicTranslations($data['code']);
        } else {
            $_SESSION['error'] = 'Failed to create language';
        }
        
        redirect('languages');
        exit;
    }
    
    public function edit($id)
    {
        $language = $this->languageModel->findById($id);
        
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            redirect('languages');
            exit;
        }
        
        $this->view('languages/edit', ['language' => $language]);
    }
    
    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('languages');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'native_name' => $_POST['native_name'] ?? '',
            'flag' => $_POST['flag'] ?? '',
            'is_active' => isset($_POST['is_active']) ? 1 : 0
        ];
        
        if (empty($data['name'])) {
            $_SESSION['error'] = 'Language name is required';
            redirect('languages/' . $id . '/edit');
            exit;
        }
        
        // Handle default language setting
        if (isset($_POST['is_default']) && $_POST['is_default']) {
            $this->languageModel->setDefault($id);
        }
        
        if ($this->languageModel->update($id, $data)) {
            $_SESSION['success'] = 'Language updated successfully';
        } else {
            $_SESSION['error'] = 'Failed to update language';
        }
        
        redirect('languages');
        exit;
    }
    
    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('languages');
            exit;
        }
        
        if ($this->languageModel->delete($id)) {
            $_SESSION['success'] = 'Language deleted successfully';
        } else {
            $_SESSION['error'] = 'Cannot delete language. It may be the default language or have existing translations.';
        }
        
        redirect('languages');
        exit;
    }
    
    public function translations($id)
    {
        $language = $this->languageModel->findById($id);
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            redirect('languages');
            exit;
        }

        // Current language translations
        $translations = $this->translationModel->getByLanguage($id);

        // English reference (if exists)
        $english = $this->languageModel->findByCode('en');
        $englishTranslations = $english ? $this->translationModel->getByLanguage($english['id']) : [];
        $englishMap = [];
        foreach ($englishTranslations as $row) {
            $englishMap[$row['translation_key']] = $row['translation_value'];
        }

        // Build current map
        $currentMap = [];
        foreach ($translations as $row) {
            $currentMap[$row['translation_key']] = $row['translation_value'];
        }

        // Collect all keys (english preferred) with categories
        $allMatrix = $this->translationModel->getTranslationsMatrix();
        $grouped = [];
        foreach ($allMatrix as $tKey => $data) {
            $category = $data['category'] ?? 'general';
            $grouped[$category][$tKey] = [
                'english' => $englishMap[$tKey] ?? '',
                'current' => $currentMap[$tKey] ?? ''
            ];
        }
        ksort($grouped);

        $this->view('languages/translations', [
            'language' => $language,
            'grouped' => $grouped,
            'englishExists' => !empty($englishTranslations)
        ]);
    }

    public function saveTranslations($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('languages/' . $id . '/translations');
            exit;
        }

        $language = $this->languageModel->findById($id);
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            redirect('languages');
            exit;
        }

    $posted = $_POST['translations'] ?? [];
    $updated = 0; $created = 0;

    // Preload matrix for categories so new keys inherit existing category classification (if any)
    $matrix = $this->translationModel->getTranslationsMatrix();
        foreach ($posted as $key => $value) {
            $key = trim($key);
            $value = trim($value);
            if ($key === '') continue;
            // Skip empty values (no deletion)
            if ($value === '') continue;

            $existing = $this->translationModel->getByKeyAndLanguage($key, $language['id']);
            if ($existing) {
                if ($this->translationModel->updateByKeyAndLanguage($key, $language['id'], $value)) {
                    $updated++;
                }
            } else {
        $category = isset($matrix[$key]['category']) ? $matrix[$key]['category'] : 'general';
        $this->translationModel->createTranslation($language['id'], $key, $value, $category);
                $created++;
            }
        }

        $_SESSION['success'] = "Saved translations: updated {$updated}, created {$created}.";
        redirect('languages/' . $id . '/translations');
        exit;
    }
    
    public function exportTranslations($id)
    {
        $language = $this->languageModel->findById($id);
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            redirect('languages');
            exit;
        }

        // Get all translations for this language
        $translations = $this->translationModel->getByLanguage($id);
        
        // Build export data structure
        $exportData = [
            'language' => [
                'code' => $language['code'],
                'name' => $language['name'],
                'native_name' => $language['native_name'],
                'flag' => $language['flag']
            ],
            'exported_at' => date('Y-m-d H:i:s'),
            'total_keys' => count($translations),
            'translations' => []
        ];
        
        // Group translations by category
        foreach ($translations as $trans) {
            $category = $trans['category'] ?? 'general';
            if (!isset($exportData['translations'][$category])) {
                $exportData['translations'][$category] = [];
            }
            $exportData['translations'][$category][$trans['translation_key']] = $trans['translation_value'];
        }
        
        // Set headers for JSON download
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename="translations_' . $language['code'] . '_' . date('Y-m-d') . '.json"');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        
        echo json_encode($exportData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    public function importTranslations($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('languages/' . $id . '/translations');
            exit;
        }

        $language = $this->languageModel->findById($id);
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            redirect('languages');
            exit;
        }

        // Check if file was uploaded
        if (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['error'] = 'No file uploaded or upload error occurred';
            redirect('languages/' . $id . '/translations');
            exit;
        }

        // Read and parse JSON file
        $jsonContent = file_get_contents($_FILES['import_file']['tmp_name']);
        $importData = json_decode($jsonContent, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            $_SESSION['error'] = 'Invalid JSON file: ' . json_last_error_msg();
            redirect('languages/' . $id . '/translations');
            exit;
        }

        // Validate structure
        if (!isset($importData['translations'])) {
            $_SESSION['error'] = 'Invalid translation file structure';
            redirect('languages/' . $id . '/translations');
            exit;
        }

        $imported = 0;
        $updated = 0;
        $skipped = 0;

        // Process translations by category
        foreach ($importData['translations'] as $category => $translations) {
            foreach ($translations as $key => $value) {
                if (empty($key) || empty($value)) {
                    $skipped++;
                    continue;
                }

                // Check if translation exists
                $existing = $this->translationModel->getByKeyAndLanguage($key, $language['id']);
                
                if ($existing) {
                    // Update existing translation
                    if ($this->translationModel->updateByKeyAndLanguage($key, $language['id'], $value)) {
                        $updated++;
                    }
                } else {
                    // Create new translation
                    if ($this->translationModel->createTranslation($language['id'], $key, $value, $category)) {
                        $imported++;
                    }
                }
            }
        }

        $_SESSION['success'] = "Import completed: {$imported} new translations imported, {$updated} updated" . 
                              ($skipped > 0 ? ", {$skipped} skipped" : "");
        redirect('languages/' . $id . '/translations');
        exit;
    }

    public function switchLanguage()
    {
        $languageCode = $_POST['language'] ?? $_GET['lang'] ?? 'en';
        
        // Validate language exists and is active
        $language = $this->languageModel->findByCode($languageCode);
        if ($language && $language['is_active']) {
            Translation::setLanguage($languageCode);
        }
        
        // Redirect back to previous page
        $redirect = $_POST['redirect'] ?? $_GET['redirect'] ?? '/samanta_crm/dashboard';
        header('Location: ' . $redirect);
        exit;
    }
    
    private function createBasicTranslations($languageCode)
    {
        $language = $this->languageModel->findByCode($languageCode);
        if (!$language) return;
        
        // Basic translations that every language should have
    $basicTranslations = [
            // Navigation
            'nav.dashboard' => 'Dashboard',
            'nav.users' => 'Users',
            'nav.admin' => 'Admin',
            'nav.logout' => 'Logout',
            
            // Common actions
            'action.create' => 'Create',
            'action.edit' => 'Edit',
            'action.delete' => 'Delete',
            'action.save' => 'Save',
            'action.cancel' => 'Cancel',
            'action.back' => 'Back',
            'action.submit' => 'Submit',
            'action.search' => 'Search',
            'action.filter' => 'Filter',
            'action.view' => 'View',
            
            // Common fields
            'field.name' => 'Name',
            'field.email' => 'Email',
            'field.password' => 'Password',
            'field.description' => 'Description',
            'field.status' => 'Status',
            'field.created' => 'Created',
            'field.updated' => 'Updated',
            
            // Status messages
            'status.active' => 'Active',
            'status.inactive' => 'Inactive',
            'message.success' => 'Operation completed successfully',
            'message.error' => 'An error occurred',
            'message.confirm_delete' => 'Are you sure you want to delete this item?',
            
            // Login
            'login.title' => 'Sign in to your account',
            'login.email' => 'Email address',
            'login.password' => 'Password',
            'login.submit' => 'Sign in',
            'login.invalid' => 'Invalid email or password',
            
            // Dashboard
            'dashboard.title' => 'Dashboard',
            'dashboard.total_users' => 'Total Users',
            'dashboard.welcome' => 'Welcome to Samanta CRM',
            // Stock Panels
            'panel.stock.title' => 'Ingredient Stock',
            'panel.stock.ledger' => 'Storage Ledger',
            'panel.stock.location.main' => 'Main',
            'panel.stock.location.rollback' => 'Rollback',
            'panel.stock.merge.rollback' => 'Merge Rollback',
            'panel.stock.adjust' => 'Adjust / Add Stock',
            'panel.stock.quantity' => 'Quantity',
            'panel.stock.location' => 'Location',
            'panel.stock.note' => 'Note',
            'panel.stock.unit' => 'Unit',
            'panel.stock.total' => 'Total',
            'panel.stock.export.csv' => 'Export CSV',
            'panel.stock.export.json' => 'Export JSON',
            'panel.stock.export.xls' => 'Export Excel',
            'panel.stock.export.print' => 'Print',
            'panel.stock.collapse' => 'Collapse Rollback',
            'panel.stock.expand' => 'Expand Rollback'
            ,
            // Products
            'products.title' => 'Products',
            'products.import' => 'Import',
            'products.confirm_delete' => 'Delete product?',
            'products.confirm_bulk_delete' => 'Delete selected products?',
            'action.add' => 'Add'
        ];
        
        $this->translationModel->importTranslations($language['id'], $basicTranslations, 'system');
    }
    
    private function view($view, $data = [])
    {
        extract($data);
        require_once "../app/Views/{$view}.php";
    }
}


