<?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'])) {
            header('Location: /samanta_crm/login');
            exit;
        }
    }
    
    private function checkAdminAccess()
    {
        if ($_SESSION['user_role'] !== 'admin') {
            $_SESSION['error'] = 'Access denied. Admin privileges required.';
            header('Location: /samanta_crm/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') {
            header('Location: /samanta_crm/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';
            header('Location: /samanta_crm/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)';
            header('Location: /samanta_crm/languages/create');
            exit;
        }
        
        // Check if code already exists
        if ($this->languageModel->findByCode($data['code'])) {
            $_SESSION['error'] = 'Language code already exists';
            header('Location: /samanta_crm/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';
        }
        
        header('Location: /samanta_crm/languages');
        exit;
    }
    
    public function edit($id)
    {
        $language = $this->languageModel->findById($id);
        
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            header('Location: /samanta_crm/languages');
            exit;
        }
        
        $this->view('languages/edit', ['language' => $language]);
    }
    
    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/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';
            header('Location: /samanta_crm/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';
        }
        
        header('Location: /samanta_crm/languages');
        exit;
    }
    
    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/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.';
        }
        
        header('Location: /samanta_crm/languages');
        exit;
    }
    
    public function translations($id)
    {
        $language = $this->languageModel->findById($id);
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            header('Location: /samanta_crm/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') {
            header('Location: /samanta_crm/languages/' . $id . '/translations');
            exit;
        }

        $language = $this->languageModel->findById($id);
        if (!$language) {
            $_SESSION['error'] = 'Language not found';
            header('Location: /samanta_crm/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}.";
        header('Location: /samanta_crm/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";
    }
}
