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

class SystemModel extends \Core\Model {
    protected $moduleName = 'System';
    protected $useSoftDeletes = false;
    
    public function getLogs($userId, $limit = 300) {
        return $this->query("SELECT * FROM action_logs WHERE user_id = ? ORDER BY created_at DESC LIMIT " . (int)$limit, [$userId])->fetchAll();
    }

    public function getActionHeatmap($userId) {
        // Group action_logs by date for the last 90 days
        $rows = $this->query(
            "SELECT DATE(created_at) as log_date, COUNT(*) as action_count 
             FROM action_logs 
             WHERE user_id = ? AND created_at >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
             GROUP BY log_date ORDER BY log_date ASC",
             [$userId]
        )->fetchAll();

        $heatmap = [];
        // Fill 90 days
        for ($i = 90; $i >= 0; $i--) {
            $d = date('Y-m-d', strtotime("-$i days"));
            $heatmap[$d] = 0;
        }
        
        foreach ($rows as $r) {
            $heatmap[$r->log_date] = (int)$r->action_count;
        }
        return $heatmap;
    }

    public function getNotifications($userId, $limit = 50) {
        return $this->query("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT " . (int)$limit, [$userId])->fetchAll();
    }

    public function markNotificationsRead($userId) {
        return $this->query("UPDATE notifications SET is_read = 1 WHERE user_id = ?", [$userId]);
    }

    public function getUnpushedNotifications($userId) {
        // Fetch notifications that haven't been pushed to the browser yet
        return $this->query("SELECT id, title, message, type FROM notifications WHERE user_id = ? AND is_pushed = 0 ORDER BY created_at ASC LIMIT 5", [$userId])->fetchAll();
    }

    public function markNotificationsPushed($userId, $ids) {
        if(empty($ids)) return false;
        $in = implode(',', array_fill(0, count($ids), '?'));
        $params = array_merge([$userId], $ids);
        return $this->query("UPDATE notifications SET is_pushed = 1 WHERE user_id = ? AND id IN ($in)", $params);
    }

    public function getUser($userId) {
        return $this->query("SELECT id, username, created_at FROM users WHERE id = ?", [$userId])->fetch();
    }

    public function updateUsername($userId, $newUsername) {
        $check = $this->query("SELECT id FROM users WHERE username = ? AND id != ?", [$newUsername, $userId])->fetch();
        if ($check) return false;
        return $this->query("UPDATE users SET username = ? WHERE id = ?", [$newUsername, $userId]);
    }

    public function updatePassword($userId, $current, $new) {
        $user = $this->query("SELECT password_hash FROM users WHERE id = ?", [$userId])->fetch();
        if ($user && password_verify($current, $user->password_hash)) {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            return $this->query("UPDATE users SET password_hash = ? WHERE id = ?", [$hash, $userId]);
        }
        return false;
    }

    public function getSettings($userId) {
        return $this->query("SELECT * FROM user_settings WHERE user_id = ?", [$userId])->fetch();
    }

    public function updateTheme($userId, $theme) {
        return $this->query(
            "INSERT INTO user_settings (user_id, theme) VALUES (?, ?) ON DUPLICATE KEY UPDATE theme = VALUES(theme)",
            [$userId, $theme]
        );
    }
}
