<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use CodeIgniter\Database\Exceptions\DatabaseException;

class Dashboard extends BaseController
{
    public function index(): string
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();

        $stats = [
            'order_count'      => 0,
            'order_amount'     => 0,
            'sale_count'       => 0,
            'sale_amount'      => 0,
            'inventory_count'  => 0,
            'issue_count_month'=> 0,
            'recent_orders'    => [],
            'recent_sales'     => [],
            'stats_unavailable'=> false,
        ];

        if ($lgIdx) {
            $db = \Config\Database::connect();

            try {
                // 총 발주 건수/금액
                $orderStats = $db->query("
                    SELECT COUNT(*) as cnt,
                           COALESCE(SUM(sub.total_amt), 0) as total_amount
                    FROM bag_order bo
                    LEFT JOIN (
                        SELECT boi_bo_idx, SUM(boi_amount) as total_amt
                        FROM bag_order_item GROUP BY boi_bo_idx
                    ) sub ON sub.boi_bo_idx = bo.bo_idx
                    WHERE bo.bo_lg_idx = ? AND bo.bo_status = 'normal'
                      AND (bo.bo_uuid, bo.bo_version) IN (
                          SELECT bo_uuid, MAX(bo_version) FROM bag_order WHERE bo_lg_idx = ? GROUP BY bo_uuid
                      )
                ", [$lgIdx, $lgIdx])->getRow();
                $stats['order_count']  = (int) ($orderStats->cnt ?? 0);
                $stats['order_amount'] = (int) ($orderStats->total_amount ?? 0);

                // 총 판매 건수/금액
                $saleStats = $db->query("
                    SELECT COUNT(*) as cnt, COALESCE(SUM(bs_amount), 0) as total_amount
                    FROM bag_sale
                    WHERE bs_lg_idx = ? AND bs_type = 'sale'
                ", [$lgIdx])->getRow();
                $stats['sale_count']  = (int) ($saleStats->cnt ?? 0);
                $stats['sale_amount'] = (int) ($saleStats->total_amount ?? 0);

                // 현재 재고 품목 수
                $invCount = $db->query("
                    SELECT COUNT(*) as cnt FROM bag_inventory WHERE bi_lg_idx = ? AND bi_qty > 0
                ", [$lgIdx])->getRow();
                $stats['inventory_count'] = (int) ($invCount->cnt ?? 0);

                // 이번 달 불출 건수
                $monthStart = date('Y-m-01');
                $issueCount = $db->query("
                    SELECT COUNT(*) as cnt FROM bag_issue
                    WHERE bi2_lg_idx = ? AND bi2_status = 'normal' AND bi2_issue_date >= ?
                ", [$lgIdx, $monthStart])->getRow();
                $stats['issue_count_month'] = (int) ($issueCount->cnt ?? 0);

                // 최근 발주 5건
                $stats['recent_orders'] = $db->query("
                    SELECT bo_idx, bo_lot_no, bo_order_date, bo_status
                    FROM bag_order
                    WHERE bo_lg_idx = ?
                      AND (bo_uuid, bo_version) IN (
                          SELECT bo_uuid, MAX(bo_version) FROM bag_order WHERE bo_lg_idx = ? GROUP BY bo_uuid
                      )
                    ORDER BY bo_order_date DESC, bo_idx DESC
                    LIMIT 5
                ", [$lgIdx, $lgIdx])->getResult();

                // 최근 판매 5건
                $stats['recent_sales'] = $db->query("
                    SELECT bs_idx, bs_ds_name, bs_bag_name, bs_qty, bs_amount, bs_sale_date, bs_type
                    FROM bag_sale
                    WHERE bs_lg_idx = ?
                    ORDER BY bs_sale_date DESC, bs_idx DESC
                    LIMIT 5
                ", [$lgIdx])->getResult();
            } catch (DatabaseException $e) {
                $stats['stats_unavailable'] = true;
                log_message('error', '[Dashboard] 통계 조회 실패(테이블 미생성 등): ' . $e->getMessage());
            }
        }

        return view('admin/layout', [
            'title'   => '대시보드',
            'content' => view('admin/dashboard/index', ['stats' => $stats, 'lgIdx' => $lgIdx]),
        ]);
    }
}
