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

class ReviewController extends \Core\Controller {

    public function index() {
        // Default: current ISO week
        $year = (int)($_GET['year'] ?? date('o'));
        $week = (int)($_GET['week'] ?? date('W'));

        // Clamp
        if ($week < 1)  { $week = 52; $year--; }
        if ($week > 52) { $week = 1;  $year++; }

        // Load model FIRST (registers the class before static call)
        $model = $this->model('Review/Models/ReviewModel');

        [$start, $end] = \ReviewModel::getWeekRange($year, $week);

        $tasks     = $model->getTaskStats($this->userId, $start, $end);
        $health    = $model->getHealthStats($this->userId, $start, $end);
        $finance   = $model->getFinanceStats($this->userId, $start, $end);
        $education = $model->getEducationStats($this->userId, $start, $end);

        // Radar chart data (scores 0-100)
        $radarData = [
            'labels' => ['المهام', 'الصحة', 'المالية', 'التعليم'],
            'values' => [
                $tasks['pct'],
                $health['fastings'] > 0 ? min(100, $health['fastings'] * 15 + $health['activities'] * 10) : 0,
                $finance['income'] > 0  ? min(100, round(($finance['income'] - $finance['expense']) / max(1, $finance['income']) * 100)) : 0,
                min(100, ($education['skills_leveled'] * 25) + ($education['courses_completed'] * 50)),
            ]
        ];

        // Previous / Next week links
        $prevWeek = $week - 1;
        $prevYear = $year;
        if ($prevWeek < 1)  { $prevWeek = 52; $prevYear--; }
        $nextWeek = $week + 1;
        $nextYear = $year;
        if ($nextWeek > 52) { $nextWeek = 1; $nextYear++; }

        $this->view('Review/Views/index', [
            'title'     => "مراجعة الأسبوع {$week} | OTIS",
            'year'      => $year,
            'week'      => $week,
            'start'     => $start,
            'end'       => $end,
            'tasks'     => $tasks,
            'health'    => $health,
            'finance'   => $finance,
            'education' => $education,
            'radarData' => json_encode($radarData),
            'prevWeek'  => $prevWeek,
            'prevYear'  => $prevYear,
            'nextWeek'  => $nextWeek,
            'nextYear'  => $nextYear,
        ]);
    }
}
