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

class AdvisorController extends \Core\Controller {

    public function index() {
        require_once __DIR__ . '/../../../../core/Services/UserProfileEngine.php';
        $engine = \Core\Services\UserProfileEngine::getInstance();
        $intel = $engine->getIntelligence($this->userId);

        $this->view('Advisor/Views/index', [
            'title'    => 'النواة الذكية (العقل) | OTIS',
            'insights' => $intel['insights'],
            'decisions'=> $intel['decisions'],
            'discipline_score' => $intel['discipline_score']
        ]);
    }

    /**
     * AJAX endpoint — returns quick insights JSON for dashboard widget
     */
    public function quickInsights() {
        require_once __DIR__ . '/../../../../core/Services/AdvisorEngine.php';
        $engine = new \Core\Services\AdvisorEngine();
        $quick  = $engine->getQuickInsights($this->userId);
        $this->jsonResponse(['success' => true, 'insights' => $quick]);
    }

    /**
     * AJAX endpoint — refresh/regenerate all insights
     */
    public function refresh() {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            require_once __DIR__ . '/../../../../core/Services/AdvisorEngine.php';
            $engine   = new \Core\Services\AdvisorEngine();
            $insights = $engine->generateInsights($this->userId);
            $this->jsonResponse(['success' => true, 'insights' => $insights]);
        }
        set_flash_message('advisor', 'تم تحديث التحليل بنجاح!', 'success');
        redirect('/advisor');
    }

    public function createTask() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') abort(404);
        verify_csrf_token($_POST['csrf_token'] ?? '');

        $data = [
            'title'          => sanitize_input($_POST['title'] ?? 'مهمة من المستشار الذكي'),
            'description'    => 'مهمة مولدة تلقائياً من AdvisorEngine 2.0',
            'category'       => sanitize_input($_POST['category'] ?? 'عام'),
            'priority'       => 'high',
            'estimated_time' => 30,
            'energy_level'   => 'high',
            'target_date'    => date('Y-m-d'),
            'skill_id'       => $_POST['skill_id'] ?? null,
        ];

        $todoModel = $this->model('Todo/Models/TodoModel');
        $todoModel->addTask($this->userId, $data);

        set_flash_message('todo', "✅ تم إضافة المهمة '{$data['title']}' من المستشار الذكي!", 'success');
        redirect('/todo');
    }

    public function createCalendarEvent() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') abort(404);
        verify_csrf_token($_POST['csrf_token'] ?? '');

        $target = date('Y-m-d', strtotime('+1 day'));
        $data = [
            'title'            => sanitize_input($_POST['title'] ?? 'جلسة مقترحة'),
            'description'      => 'مقترحة من المستشار الذكي 2.0',
            'category'         => 'other',
            'event_date'       => $target,
            'start_time'       => '18:00',
            'end_time'         => '19:00',
            'color_hex'        => '#8b5cf6',
            'recurrence_type'  => 'none',
            'recurrence_end_date' => null,
        ];

        $calModel = $this->model('Calendar/Models/CalendarModel');
        $calModel->addEvent($this->userId, $data);

        set_flash_message('calendar', 'تمت جدولة الجلسة المقترحة بنجاح ليوم الغد.', 'success');
        redirect("/calendar/index?view=day&date={$target}");
    }
}
