<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;

class DashboardController extends ResourceController
{
    use ResponseTrait;

    /**
     * 대시보드 통계 조회
     */
    public function getStats()
    {
        try {
            $db = \Config\Database::connect();

            // 팝업 개수
            $popupCount = 0;
            if ($db->tableExists('popups')) {
                $popupCount = $db->table('popups')->countAllResults();
            }

            // 지점 개수
            $branchCount = 0;
            if ($db->tableExists('branches')) {
                $branchCount = $db->table('branches')->countAllResults();
            }

            // 직원 개수 (영업사원 + 어드바이저)
            $salesCount = 0;
            if ($db->tableExists('sales_staff')) {
                $salesCount = $db->table('sales_staff')->countAllResults();
            }

            $advisorCount = 0;
            if ($db->tableExists('advisors')) {
                $advisorCount = $db->table('advisors')->countAllResults();
            }

            $employeeCount = $salesCount + $advisorCount;

            // 브로셔 요청 개수
            $brochureCount = 0;
            if ($db->tableExists('brochure_requests')) {
                $brochureCount = $db->table('brochure_requests')->countAllResults();
            }

            $stats = [
                'popups' => $popupCount,
                'branches' => $branchCount,
                'employees' => $employeeCount,
                'brochures' => $brochureCount
            ];

            return $this->respond([
                'success' => true,
                'data' => $stats
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Dashboard stats error: ' . $e->getMessage());
            log_message('error', 'Stack trace: ' . $e->getTraceAsString());

            return $this->respond([
                'success' => false,
                'message' => '통계 조회 중 오류가 발생했습니다.',
                'error' => $e->getMessage(),
                'trace' => ENVIRONMENT === 'development' ? $e->getTraceAsString() : null
            ], 500);
        }
    }
}
