<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BagInventoryModel;

class BagInventory extends BaseController
{
    public function index()
    {
        helper('admin');
        $lgIdx = admin_effective_lg_idx();
        if (! $lgIdx) {
            return redirect()->to(work_area_home_url())->with('error', '지자체를 선택해 주세요.');
        }

        $invModel = model(BagInventoryModel::class);
        $list     = $invModel->where('bi_lg_idx', $lgIdx)->orderBy('bi_bag_code', 'ASC')->paginate(20);
        $pager    = $invModel->pager;

        return $this->renderWorkPage('재고 현황', 'admin/bag_inventory/index', ['list' => $list, 'pager' => $pager]);
    }

    public function export()
    {
        helper(['admin', 'export']);
        $lgIdx = admin_effective_lg_idx();
        if (! $lgIdx) {
            return redirect()->to(mgmt_url('bag-inventory'))->with('error', '지자체를 선택해 주세요.');
        }

        $list = model(BagInventoryModel::class)->where('bi_lg_idx', $lgIdx)->orderBy('bi_bag_code', 'ASC')->findAll();

        $rows = [];
        foreach ($list as $row) {
            $rows[] = [
                $row->bi_idx,
                $row->bi_bag_code,
                $row->bi_bag_name,
                (int) $row->bi_qty,
                $row->bi_updated_at,
            ];
        }

        export_xlsx(
            '재고현황_' . date('Ymd') . '.xlsx',
            '재고현황',
            ['번호', '봉투코드', '봉투명', '현재재고(낱장)', '최종갱신'],
            $rows
        );
    }
}
