<?php
namespace App\Modules\Goals\Models;

class GoalsModel extends \Core\Model {
    protected $moduleName = 'Goals';
    // Aggregates data from other modules via custom queries. No base Model delete needed.
    protected $useSoftDeletes = false;

    /**
     * Returns an aggregated list of all goals from Health, Finance, and Skills.
     * Each goal has: source, title, current, target, pct, color, icon, link
     */
    public function getAllGoals($userId) {
        $goals = [];

        // ── Health Goals ─────────────────────────────────
        $healthGoals = $this->query(
            "SELECT * FROM health_goals WHERE user_id = ? AND deleted_at IS NULL ORDER BY created_at DESC",
            [$userId]
        )->fetchAll();

        foreach ($healthGoals as $g) {
            $target  = (float)$g->target_value;
            $current = (float)$g->current_value;
            $pct     = $target > 0 ? min(100, round(($current / $target) * 100)) : 0;
            $goals[] = [
                'source'  => 'health',
                'source_label' => 'الصحة',
                'icon'    => 'fa-heart-pulse',
                'color'   => 'danger',
                'title'   => $g->title,
                'current' => $current,
                'target'  => $target,
                'unit'    => '',
                'pct'     => $pct,
                'due'     => $g->expected_date ?? null,
                'link'    => '/health?tab=goals',
            ];
        }

        // ── Finance Saving Goals ──────────────────────────
        $finGoals = $this->query(
            "SELECT * FROM finance_saving_goals WHERE user_id = ? AND deleted_at IS NULL ORDER BY created_at DESC",
            [$userId]
        )->fetchAll();

        foreach ($finGoals as $g) {
            $target  = (float)$g->target_amount;
            $current = (float)$g->current_amount;
            $pct     = $target > 0 ? min(100, round(($current / $target) * 100)) : 0;
            $goals[] = [
                'source'  => 'finance',
                'source_label' => 'التوفير',
                'icon'    => 'fa-piggy-bank',
                'color'   => 'success',
                'title'   => $g->title,
                'current' => number_format($current),
                'target'  => number_format($target),
                'unit'    => 'ج.م',
                'pct'     => $pct,
                'due'     => $g->expected_date ?? null,
                'link'    => '/finance?tab=savings',
            ];
        }

        // ── Skill Goals (skills not yet at max level 10) ──
        $skills = $this->query(
            "SELECT * FROM edu_skills WHERE user_id = ? AND deleted_at IS NULL AND level < 10 ORDER BY level DESC LIMIT 10",
            [$userId]
        )->fetchAll();

        foreach ($skills as $s) {
            // Total progress = (level - 1) * 100 + progress_percent  out of 900 (level 1→10)
            $totalProgress = (($s->level - 1) * 100) + $s->progress_percent;
            $pct = round($totalProgress / 9);
            $goals[] = [
                'source'  => 'skill',
                'source_label' => 'مهارة',
                'icon'    => 'fa-graduation-cap',
                'color'   => 'primary',
                'title'   => 'إتقان: ' . $s->name,
                'current' => "المستوى {$s->level}",
                'target'  => 'المستوى 10',
                'unit'    => '',
                'pct'     => $pct,
                'due'     => null,
                'link'    => '/education',
            ];
        }

        // Sort by progress ascending (least done first)
        usort($goals, fn($a, $b) => $a['pct'] <=> $b['pct']);
        return $goals;
    }

    /**
     * Overall system health score (0–100) based on all goals average
     */
    public function getOverallScore($userId) {
        $goals = $this->getAllGoals($userId);
        if (empty($goals)) return 0;
        $sum = array_sum(array_column($goals, 'pct'));
        return round($sum / count($goals));
    }
}
