<?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'])) { 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() {
        $settings = [
            'site_name' => $this->settingModel->get('site_name', 'Samanta CRM'),
            'default_language' => $this->settingModel->get('default_language', 'en'),
            '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') { header('Location: /samanta_crm/settings'); exit; }
        $site_name = trim($_POST['site_name'] ?? 'Samanta CRM');
        $default_language = trim($_POST['default_language'] ?? 'en');
        $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,0775,true); }
                $fileName = 'logo_'.date('Ymd_His').'.'.$ext;
                $fullPath = $targetDir . '/' . $fileName;
                if (move_uploaded_file($f['tmp_name'],$fullPath)) {
                    // store relative path for web
                    $relative = '/samanta_crm/uploads/'.$fileName;
                    $this->settingModel->set('site_logo',$relative);
                }
            }
        }

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

        $_SESSION['success'] = 'Settings saved.';
        header('Location: /samanta_crm/settings');
        exit;
    }

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