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

class ExportController {
    private $languageModel;
    private $translationModel;

    public function __construct() {
        $this->languageModel = new Language();
        $this->translationModel = new Translation();
        $this->checkAuth();
        $this->checkAdmin();
    }

    private function checkAuth() {
        if (!isset($_SESSION['user_id'])) { header('Location: /samanta_crm/login'); exit; }
    }
    private function checkAdmin() {
        if (($_SESSION['user_role'] ?? '') !== 'admin') { $_SESSION['error']='Admin only'; header('Location: /samanta_crm/dashboard'); exit; }
    }

    public function index() {
        $this->view('export/index');
    }

    public function exportLanguages() {
        $format = strtolower($_GET['format'] ?? 'json');
        $langs = $this->languageModel->getAll();
        if ($format === 'csv') {
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="languages_export_'.date('Ymd_His').'.csv"');
            $out = fopen('php://output','w');
            fputcsv($out, ['code','name','native_name','flag','is_active','is_default']);
            foreach ($langs as $l) {
                fputcsv($out, [$l['code'],$l['name'],$l['native_name'],$l['flag'],$l['is_active'],$l['is_default']]);
            }
            fclose($out); exit;
        } else {
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="languages_export_'.date('Ymd_His').'.json"');
            echo json_encode(['languages'=>$langs], JSON_PRETTY_PRINT); exit;
        }
    }

    public function exportTranslations() {
        $format = strtolower($_GET['format'] ?? 'json');
        $matrix = $this->translationModel->getTranslationsMatrix();
        // Build flat list
        $translations = [];
        // Need mapping translation key -> category already included; each language value present
        // Get languages list for order
        $languages = $this->languageModel->getAll();
        $languageCodes = array_map(fn($l)=>$l['code'],$languages);
        foreach ($matrix as $key => $rows) {
            $category = $rows['category'] ?? 'general';
            foreach ($languageCodes as $code) {
                if (isset($rows[$code])) {
                    $translations[] = [
                        'language_code' => $code,
                        'key' => $key,
                        'value' => $rows[$code],
                        'category' => $category
                    ];
                }
            }
        }
        if ($format === 'csv') {
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="translations_export_'.date('Ymd_His').'.csv"');
            $out = fopen('php://output','w');
            fputcsv($out,['language_code','key','value','category']);
            foreach ($translations as $t) { fputcsv($out, $t); }
            fclose($out); exit;
        } else {
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="translations_export_'.date('Ymd_His').'.json"');
            echo json_encode(['translations'=>$translations], JSON_PRETTY_PRINT); exit;
        }
    }

    public function importLanguages() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['file']['tmp_name'])) { header('Location: /samanta_crm/export'); exit; }
        $content = file_get_contents($_FILES['file']['tmp_name']);
        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        $rows = [];
        if ($ext === 'json') {
            $data = json_decode($content,true);
            if (isset($data['languages']) && is_array($data['languages'])) { $rows = $data['languages']; }
        } else { // assume CSV
            $fh = fopen($_FILES['file']['tmp_name'],'r');
            $header = fgetcsv($fh); if ($header){ $map = array_flip($header); }
            while(($line=fgetcsv($fh))!==false){
                $rows[] = [
                    'code'=>$line[$map['code']] ?? '',
                    'name'=>$line[$map['name']] ?? '',
                    'native_name'=>$line[$map['native_name']] ?? '',
                    'flag'=>$line[$map['flag']] ?? '',
                    'is_active'=>$line[$map['is_active']] ?? 1,
                    'is_default'=>$line[$map['is_default']] ?? 0
                ];
            }
            fclose($fh);
        }
        $created=0;$updated=0; foreach ($rows as $r){
            if (empty($r['code'])||empty($r['name'])) continue;
            $existing = $this->languageModel->findByCode($r['code']);
            if ($existing){
                $this->languageModel->update($existing['id'], [
                    'name'=>$r['name'],
                    'native_name'=>$r['native_name'] ?? '',
                    'flag'=>$r['flag'] ?? '',
                    'is_active'=>(int)($r['is_active']??1)
                ]); $updated++;
                if (!empty($r['is_default'])) { $this->languageModel->setDefault($existing['id']); }
            } else {
                $this->languageModel->create([
                    'code'=>strtolower($r['code']),
                    'name'=>$r['name'],
                    'native_name'=>$r['native_name'] ?? '',
                    'flag'=>$r['flag'] ?? '',
                    'is_active'=>(int)($r['is_active']??1),
                    'is_default'=>(int)($r['is_default']??0)
                ]); $created++;
            }
        }
        $_SESSION['success'] = "Languages import: created $created, updated $updated.";
        header('Location: /samanta_crm/export'); exit;
    }

    public function importTranslations() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['file']['tmp_name'])) { header('Location: /samanta_crm/export'); exit; }
        $content = file_get_contents($_FILES['file']['tmp_name']);
        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        $entries = [];
        if ($ext === 'json') {
            $data = json_decode($content,true);
            if (isset($data['translations']) && is_array($data['translations'])) { $entries = $data['translations']; }
        } else { // CSV
            $fh = fopen($_FILES['file']['tmp_name'],'r');
            $header = fgetcsv($fh); if($header){ $map=array_flip($header);} else { $map=[]; }
            while(($line=fgetcsv($fh))!==false){
                $entries[] = [
                    'language_code'=>$line[$map['language_code']] ?? '',
                    'key'=>$line[$map['key']] ?? '',
                    'value'=>$line[$map['value']] ?? '',
                    'category'=>$line[$map['category']] ?? 'general'
                ];
            }
            fclose($fh);
        }
        $created=0;$updated=0;$skipped=0; 
        foreach ($entries as $e){
            if (empty($e['language_code'])||empty($e['key'])) { $skipped++; continue; }
            $lang = $this->languageModel->findByCode($e['language_code']);
            if (!$lang) { $skipped++; continue; }
            $existing = $this->translationModel->getByKeyAndLanguage($e['key'], $lang['id']);
            $val = $e['value'] ?? '';
            if ($existing){
                if ($val !== '') { $this->translationModel->updateByKeyAndLanguage($e['key'],$lang['id'],$val); $updated++; }
            } else {
                if ($val === '') { $skipped++; continue; }
                $this->translationModel->createTranslation($lang['id'],$e['key'],$val,$e['category'] ?? 'general');
                $created++;
            }
        }
        $_SESSION['success'] = "Translations import: created $created, updated $updated, skipped $skipped.";
        header('Location: /samanta_crm/export'); exit;
    }

    private function view($view, $data=[]) { extract($data); require_once "../app/Views/$view.php"; }
}