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

class AnalyticsModel extends \Core\Model {
    protected $moduleName = 'Analytics';
    protected $useSoftDeletes = false; // Read-only analytics aggregation

    // ─── TASKS ────────────────────────────────────────────
    /**
     * Returns daily task completion % for the past N days.
     */
    public function getTaskCompletion($userId, $days = 30) {
        $rows = $this->query(
            "SELECT target_date as date, COUNT(*) as total, SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as done
             FROM todo_tasks 
             WHERE user_id = ? AND target_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY) AND deleted_at IS NULL
             GROUP BY target_date",
            [$userId, $days - 1]
        )->fetchAll();

        $dataMap = [];
        foreach($rows as $r) {
            $dataMap[$r->date] = [
                'total' => (int)$r->total,
                'done'  => (int)$r->done,
                'pct'   => $r->total > 0 ? round(($r->done / $r->total) * 100) : 0
            ];
        }

        $result = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            if (isset($dataMap[$date])) {
                $result[] = ['date' => $date] + $dataMap[$date];
            } else {
                $result[] = ['date' => $date, 'pct' => 0, 'done' => 0, 'total' => 0];
            }
        }
        return $result;
    }

    // ─── WEIGHT ───────────────────────────────────────────
    public function getWeightTrend($userId, $days = 30) {
        return $this->query(
            "SELECT weight, logged_at as date FROM health_weight_logs
             WHERE user_id = ? AND deleted_at IS NULL AND logged_at >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
             ORDER BY logged_at ASC",
            [$userId, $days]
        )->fetchAll();
    }

    // ─── INCOME VS EXPENSE ────────────────────────────────
    public function getIncomeVsExpense($userId, $months = 6) {
        $minDate = date('Y-m-01', strtotime("-".($months-1)." months"));
        
        $incRows = $this->query(
            "SELECT YEAR(date_received) as yy, MONTH(date_received) as mm, SUM(amount) as total
             FROM finance_incomes 
             WHERE user_id=? AND date_received >= ? AND deleted_at IS NULL
             GROUP BY yy, mm",
            [$userId, $minDate]
        )->fetchAll();
        
        $expRows = $this->query(
            "SELECT YEAR(expense_date) as yy, MONTH(expense_date) as mm, SUM(amount) as total
             FROM finance_expenses 
             WHERE user_id=? AND expense_date >= ? AND deleted_at IS NULL
             GROUP BY yy, mm",
            [$userId, $minDate]
        )->fetchAll();

        $incMap = []; foreach($incRows as $r) { $incMap[$r->yy.'-'.str_pad($r->mm,2,'0',STR_PAD_LEFT)] = $r->total; }
        $expMap = []; foreach($expRows as $r) { $expMap[$r->yy.'-'.str_pad($r->mm,2,'0',STR_PAD_LEFT)] = $r->total; }

        $result = [];
        for ($i = $months - 1; $i >= 0; $i--) {
            $ym = date('Y-m', strtotime("-{$i} months"));
            $result[] = [
                'label'   => date('M Y', strtotime("-{$i} months")),
                'income'  => (float)($incMap[$ym] ?? 0),
                'expense' => (float)($expMap[$ym] ?? 0),
            ];
        }
        return $result;
    }

    // ─── SKILL GROWTH (bar chart) ─────────────────────────
    public function getSkillLevels($userId) {
        return $this->query(
            "SELECT name, level, progress_percent FROM edu_skills WHERE user_id = ? AND deleted_at IS NULL ORDER BY level DESC LIMIT 10",
            [$userId]
        )->fetchAll();
    }
}
