<?php
namespace App\Modules\System\Controllers;

class SystemController extends \Core\Controller {


    public function logs() {
        $model = $this->model('System/Models/SystemModel');
        $logs = $model->getLogs($this->userId, 300);
        $heatmap = $model->getActionHeatmap($this->userId);

        $this->view('System/Views/logs', [
            'title' => 'System Telemetry | OTIS',
            'logs' => $logs,
            'heatmap' => $heatmap
        ]);
    }

    public function notifications() {
        $model = $this->model('System/Models/SystemModel');
        $notifications = $model->getNotifications($this->userId);
        
        // Mark as read when accessed
        $model->markNotificationsRead($this->userId);

        $this->view('System/Views/notifications', [
            'title' => 'الإشعارات (Notifications)',
            'notifications' => $notifications
        ]);
    }

    public function pollNotifications() {
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
            $this->jsonError('Method Not Allowed', 405);
        }

        $userId = $this->userId ?? 1;
        $model = $this->model('System/Models/SystemModel');
        $unpushed = $model->getUnpushedNotifications($userId);
        
        $response = ['success' => true, 'notifications' => []];
        
        if (!empty($unpushed)) {
            $response['notifications'] = $unpushed;
            $ids = array_column($unpushed, 'id');
            $model->markNotificationsPushed($userId, $ids);
        }
        
        $this->jsonResponse($response);
    }

    public function resolveReminder() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? 0;
            $status = $input['status'] ?? 'done';
            
            require_once __DIR__ . '/../../../../core/Services/ReminderService.php';
            $remService = new \Core\Services\ReminderService();
            if ($remService->markReminderStatus($this->userId, $id, $status)) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false]);
            }
            exit;
        }
    }

    // Generic Restore Function via API pattern
    public function restoreRecord() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token']);
            $tablePath = get_secure_post('model_path'); // e.g., Finance/Models/FinanceModel
            $recordId = get_secure_post('record_id');

            $model = $this->model($tablePath);
            if ($model->restore($recordId, $this->userId)) {
                set_flash_message('system', 'تم استعادة السجل المحذوف بنجاح.', 'success');
            } else {
                set_flash_message('system', 'فشل استعادة السجل.', 'danger');
            }
            redirect($_SERVER['HTTP_REFERER']);
        }
    }

    public function profile() {
        $model = $this->model('System/Models/SystemModel');
        $user = $model->getUser($this->userId);
        
        require_once __DIR__ . '/../../../../core/Services/BehaviorIntelligenceService.php';
        $intelligenceService = new \Core\Services\BehaviorIntelligenceService();
        $score = $intelligenceService->getUnifiedDisciplineScore($this->userId);
        $identity = $intelligenceService->getIdentityNarrative($score);

        // Map score to a "Military" rank purely for aesthetic and gamification
        $rank = 'مستجد (Recruit)';
        if ($score >= 95) $rank = 'القائد الاستراتيجي (Master Commander)';
        elseif ($score >= 80) $rank = 'عميل سري نخبة (Stealth Operator)';
        elseif ($score >= 60) $rank = 'عميل ميداني (Field Agent)';
        elseif ($score >= 40) $rank = 'متدرب (Cadet)';

        $this->view('System/Views/profile', [
            'title' => 'Operator Identity | OTIS',
            'user' => $user,
            'score' => $score,
            'identity' => $identity,
            'rank' => $rank
        ]);
    }

    public function updateProfile() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $username = $_POST['username'] ?? '';
            $model = $this->model('System/Models/SystemModel');
            
            if ($model->updateUsername($this->userId, $username)) {
                $_SESSION['username'] = $username;
                set_flash_message('system', 'تم تحديث البيانات بنجاح.', 'success');
            } else {
                set_flash_message('system', 'اسم المستخدم هذا محجوز بالفعل!', 'danger');
            }
            redirect('/system/profile');
        }
    }

    public function changePassword() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            $current = $_POST['current_password'] ?? '';
            $new = $_POST['new_password'] ?? '';
            $confirm = $_POST['confirm_password'] ?? '';
            
            if ($new !== $confirm) {
                set_flash_message('system', 'كلمات المرور الجديدة غير متطابقة!', 'warning');
            } else {
                $model = $this->model('System/Models/SystemModel');
                if ($model->updatePassword($this->userId, $current, $new)) {
                    set_flash_message('system', 'تم تغيير كلمة المرور بنجاح حفاظاً على الأمان.', 'success');
                } else {
                    set_flash_message('system', 'كلمة المرور الحالية غير صحيحة.', 'danger');
                }
            }
            redirect('/system/profile');
        }
    }

    public function toggleTheme() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $theme = $input['theme'] ?? 'light';
            
            $model = $this->model('System/Models/UserSettingsModel');
            $model->updateTheme($this->userId, $theme);
            $_SESSION['theme'] = $theme;
            
            echo json_encode(['success' => true, 'theme' => $theme]);
            exit;
        }
    }

    public function settings() {
        $model = $this->model('System/Models/UserSettingsModel');
        $settings = $model->getSettings($this->userId);

        $this->view('System/Views/settings', [
            'title' => 'إعدادات النظام (User Settings)',
            'settings' => $settings
        ]);
    }

    public function updateSettings() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            verify_csrf_token($_POST['csrf_token'] ?? '');
            
            $data = [
                'theme' => get_secure_post('theme') ?: 'light',
                'timezone' => get_secure_post('timezone') ?: 'Africa/Cairo',
                'currency' => get_secure_post('currency') ?: 'EGP',
                'focus_mode' => isset($_POST['focus_mode']) ? 1 : 0,
                'personality_mode' => get_secure_post('personality_mode') ?: 'strict'
            ];

            $model = $this->model('System/Models/UserSettingsModel');
            if ($model->updateSettings($this->userId, $data)) {
                $_SESSION['theme'] = $data['theme'];
                $_SESSION['timezone'] = $data['timezone'];
                $_SESSION['currency'] = $data['currency'];
                $_SESSION['personality_mode'] = $data['personality_mode'];
                
                set_flash_message('system', 'System Intelligence Rules Updated.', 'success');
            } else {
                set_flash_message('system', 'System update failed.', 'danger');
            }
            redirect('/system/settings');
        }
    }

    // ─── Backup & Restore Proxy ─────────────────────────────────────
    public function backup($action = null) {
        require_once ROOT_PATH . '/app/Modules/System/Controllers/BackupController.php';
        $bc = new \App\Modules\System\Controllers\BackupController();
        if ($action === 'export') {
            $bc->export();
        } elseif ($action === 'import') {
            $bc->import();
        } else {
            $bc->index();
        }
    }

    // ─── Dark Mode Persistence ──────────────────────────────────────
    public function saveTheme() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->jsonError('Method not allowed', 405);
        }
        $input = json_decode(file_get_contents('php://input'), true);
        $theme = in_array($input['theme'] ?? '', ['light', 'dark']) ? $input['theme'] : 'light';

        try {
            $db = \Core\Database::getInstance();
            $db->query(
                "INSERT INTO user_settings (user_id, theme) VALUES (?, ?)
                 ON DUPLICATE KEY UPDATE theme = VALUES(theme)",
                [$this->userId, $theme]
            );
            $_SESSION['theme'] = $theme;
            $this->jsonResponse(['success' => true]);
        } catch (\Throwable $e) {
            $this->handleException($e);
        }
    }

    // ─── Onboarding Complete ────────────────────────────────────────
    public function completeOnboarding() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->jsonError('Method not allowed', 405);
        }
        try {
            $db = \Core\Database::getInstance();
            $db->query(
                "INSERT INTO user_settings (user_id, onboarding_done) VALUES (?, 1)
                 ON DUPLICATE KEY UPDATE onboarding_done = 1",
                [$this->userId]
            );
            $_SESSION['onboarding_done'] = true;
            $this->jsonResponse(['success' => true]);
        } catch (\Throwable $e) {
            $this->handleException($e);
        }
    }

    // ─── System Reset (Danger Zone) ─────────────────────────────────
    public function reset() {
        require_once ROOT_PATH . '/app/Modules/System/Controllers/ResetController.php';
        $rc = new \App\Modules\System\Controllers\ResetController();
        $rc->execute();
    }

    // ─── Save Dashboard Layout ──────────────────────────────────────
    public function saveDashboardLayout() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->jsonError('Method not allowed', 405);
        }
        $input = json_decode(file_get_contents('php://input'), true);
        if(isset($input['layout']) && is_array($input['layout'])) {
            $layoutJson = json_encode($input['layout']);
            try {
                $db = \Core\Database::getInstance();
                $db->query(
                    "UPDATE user_settings SET dashboard_layout_json = ? WHERE user_id = ?",
                    [$layoutJson, $this->userId]
                );
                $this->jsonResponse(['success' => true]);
            } catch (\Throwable $e) {
                $this->handleException($e);
            }
        }
        $this->jsonError('Invalid layout data', 400);
    }
}
