<?php
/**
 * HuSNS - 签到管理控制器
 */
class PointSigninController extends Controller
{
    private $pointModel;

    public function __construct()
    {
        parent::__construct();
        $this->view->setLayout('admin');
        $this->pointModel = new PointModel();
    }

    /**
     * 签到管理页面（主入口）
     */
    public function index()
    {
        $this->checkAdmin();

        $tab = trim(Helper::get('tab', 'stats'));
        $page = max(1, (int)Helper::get('page', 1));
        $keyword = trim(Helper::get('keyword', ''));
        $limit = 20;

        // 获取统计数据（所有 tab 都需要）
        $stats = $this->getSigninStats();
        $config = $this->getSigninConfig();

        // 根据 tab 获取不同数据
        $data = [
            'tab' => $tab,
            'stats' => $stats,
            'config' => $config,
            'page' => $page,
            'keyword' => $keyword
        ];

        switch ($tab) {
            case 'config':
                // 配置页面 - 不需要额外数据
                break;

            case 'logs':
                // 签到记录
                $result = $this->getSigninLogs($page, $limit, $keyword);
                $data['logs'] = $result['logs'];
                $data['total'] = $result['total'];
                $data['pages'] = $result['pages'];
                break;

            case 'leaderboard':
                // 签到排行榜
                $result = $this->getSigninLeaderboard($page, 50);
                $data['users'] = $result['users'];
                $data['total'] = $result['total'];
                $data['pages'] = $result['pages'];
                break;

            case 'stats':
            default:
                // 统计页面 - 获取趋势数据
                $data['daily'] = $this->getSigninDaily(30);
                break;
        }

        $this->render('admin/signin', $data);
    }

    /**
     * 签到配置保存（API）
     */
    public function config()
    {
        $this->checkAdmin();

        if (!Helper::verifyCsrf()) {
            $this->jsonError('安全验证失败');
        }

        $enabled = Helper::post('enabled') == '1' ? 1 : 0;
        $basePoints = (int)Helper::post('base_points', 10);
        $bonusDays = Helper::post('bonus_days', []);
        $bonusAmount = Helper::post('bonus_amount', []);

        $continuousBonus = [];
        foreach ($bonusDays as $i => $days) {
            if (!empty($days) && isset($bonusAmount[$i])) {
                $continuousBonus[] = [
                    'days' => (int)$days,
                    'bonus' => (int)$bonusAmount[$i]
                ];
            }
        }

        usort($continuousBonus, function($a, $b) {
            return $a['days'] - $b['days'];
        });

        $this->saveSigninConfig([
            'enabled' => $enabled,
            'base_points' => $basePoints,
            'continuous_bonus' => $continuousBonus
        ]);

        $this->jsonSuccess(null, '配置保存成功');
    }

    /**
     * 签到统计数据（API）
     */
    public function stats()
    {
        $this->checkAdmin();

        $daily = $this->getSigninDaily(30);
        $this->jsonSuccess(['daily' => $daily]);
    }

    /**
     * 获取签到配置（带错误处理）
     */
    private function getSigninConfig()
    {
        try {
            return $this->pointModel->getSigninConfig();
        } catch (Exception $e) {
            return [
                'enabled' => 1,
                'base_points' => 10,
                'continuous_bonus' => []
            ];
        }
    }

    /**
     * 保存签到配置（带错误处理）
     */
    private function saveSigninConfig($data)
    {
        $this->pointModel->saveSigninConfig($data);
    }

    /**
     * 获取签到统计数据（带错误处理）
     */
    private function getSigninStats()
    {
        try {
            return $this->pointModel->getSigninStats();
        } catch (Exception $e) {
            return [
                'today_count' => 0,
                'yesterday_count' => 0,
                'month_count' => 0,
                'total_count' => 0,
                'total_users' => 0
            ];
        }
    }

    /**
     * 获取每日签到数据
     */
    private function getSigninDaily($days = 30)
    {
        try {
            return $this->pointModel->getSigninDaily($days);
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * 获取签到记录
     */
    private function getSigninLogs($page = 1, $limit = 20, $keyword = '')
    {
        try {
            return $this->pointModel->getSigninLogs($page, $limit, $keyword);
        } catch (Exception $e) {
            return [
                'logs' => [],
                'total' => 0,
                'page' => $page,
                'pages' => 0
            ];
        }
    }

    /**
     * 获取签到排行榜
     */
    private function getSigninLeaderboard($page = 1, $limit = 50)
    {
        try {
            return $this->pointModel->getSigninLeaderboard($page, $limit);
        } catch (Exception $e) {
            return [
                'users' => [],
                'total' => 0,
                'page' => $page,
                'pages' => 0
            ];
        }
    }
}
