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

class SettingController {
    private $settingModel;
    private $languageModel;

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

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

    public function index() {
        $settings = [
            'site_name' => $this->settingModel->get('site_name', 'Samanta CRM'),
            'default_language' => $this->settingModel->get('default_language', 'pl'),
            'maintenance_mode' => $this->settingModel->get('maintenance_mode', '0'),
            'maintenance_message' => $this->settingModel->get('maintenance_message', 'The system is under maintenance. Please check back soon.'),
            'site_logo' => $this->settingModel->get('site_logo', ''),
            'show_site_name_with_logo' => $this->settingModel->get('show_site_name_with_logo', '1')
        ];
        $languages = $this->languageModel->getAll();
        $this->view('settings/index', compact('settings','languages'));
    }

    public function save() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { redirect('settings'); exit; }
        $site_name = trim($_POST['site_name'] ?? 'Samanta CRM');
        $default_language = trim($_POST['default_language'] ?? 'pl');
        $maintenance_mode = isset($_POST['maintenance_mode']) ? '1' : '0';
        $maintenance_message = trim($_POST['maintenance_message'] ?? '');
    $show_site_name_with_logo = isset($_POST['show_site_name_with_logo']) ? '1':'0';

        $this->settingModel->set('site_name', $site_name);
        $this->settingModel->set('default_language', $default_language);
        $this->settingModel->set('maintenance_mode', $maintenance_mode);
        $this->settingModel->set('maintenance_message', $maintenance_message);
    $this->settingModel->set('show_site_name_with_logo', $show_site_name_with_logo);

        // Logo upload (optional)
        if (!empty($_FILES['site_logo']['name']) && is_uploaded_file($_FILES['site_logo']['tmp_name'])) {
            $f = $_FILES['site_logo'];
            $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
            $allowed = ['png','jpg','jpeg','gif','webp','svg'];
            if (in_array($ext,$allowed)) {
                $targetDir = __DIR__ . '/../../public/uploads';
                if (!is_dir($targetDir)) { 
                    @mkdir($targetDir, 0777, true);
                    @chmod($targetDir, 0777);
                }
                $fileName = 'logo_'.date('Ymd_His').'.'.$ext;
                $fullPath = $targetDir . '/' . $fileName;
                if (@move_uploaded_file($f['tmp_name'], $fullPath)) {
                    @chmod($fullPath, 0644);
                    // store relative path for web
                    $relative = '/samanta_crm/public/uploads/'.$fileName;
                    $this->settingModel->set('site_logo', $relative);
                } else {
                    $_SESSION['error'] = 'Failed to upload logo. Check directory permissions.';
                }
            }
        }

        // Also adjust language default if changed
        $lang = $this->languageModel->findByCode($default_language);
        if ($lang) { $this->languageModel->setDefault($lang['id']); }

        $_SESSION['success'] = 'Settings saved.';
        redirect('settings');
        exit;
    }

    public function importDatabase() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { redirect('settings'); exit; }
        
        if (empty($_FILES['sql_file']['tmp_name'])) {
            $_SESSION['error'] = 'No SQL file uploaded';
            redirect('settings');
            exit;
        }
        
        $file = $_FILES['sql_file'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if ($ext !== 'sql') {
            $_SESSION['error'] = 'Only .sql files are allowed';
            redirect('settings');
            exit;
        }
        
        // Read SQL file
        $sql = file_get_contents($file['tmp_name']);
        if ($sql === false) {
            $_SESSION['error'] = 'Failed to read SQL file';
            redirect('settings');
            exit;
        }
        
        // Get database connection
        global $pdo;
        
        try {
            // Disable foreign key checks
            $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
            $pdo->exec('SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"');
            $pdo->exec('SET AUTOCOMMIT = 0');
            $pdo->exec('START TRANSACTION');
            
            // Get all tables in the database
            $stmt = $pdo->query("SHOW TABLES");
            $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Drop all existing tables
            foreach ($tables as $table) {
                $pdo->exec("DROP TABLE IF EXISTS `$table`");
            }
            
            // Execute the entire SQL file at once
            $pdo->exec($sql);
            
            // Commit transaction
            $pdo->exec('COMMIT');
            $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
            
            $_SESSION['success'] = 'Database imported successfully. All tables replaced.';
        } catch (Exception $e) {
            $pdo->exec('ROLLBACK');
            $_SESSION['error'] = 'Import failed: ' . $e->getMessage();
        }
        
        redirect('settings');
        exit;
    }

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


