<?php
namespace App\Controllers\results;

use App\Controllers\BaseController;
use App\Models\results\AssignModel;

class Assign extends BaseController
{
    private $assignModel;

    public function __construct()
    {
        $this->assignModel = new AssignModel();
    }

    public function lists(): string
    {
        $bonbu = $this->assignModel->getBonbuList();
        $team = $this->assignModel->getTeamList();
        $sido = $this->assignModel->getAreaList();

        $this->data['bonbu'] = $bonbu;
        $this->data['team'] = $team;
        $this->data['sido'] = $sido;


        return view("pages/results/assign/stats_a01", $this->data);
    }

    public function getUserList()
    {
        $start = (int) $this->request->getGet('start') ?: 0;
        $end = (int) $this->request->getGet('length') ?: 10;
        $draw = (int) $this->request->getGet('draw') ?: 1;

        $data = [
            'bonbu' => $this->request->getGet('bonbu'),
            'team' => $this->request->getGet('team'),
            'schDateGb' => $this->request->getGet('schDateGb'),
            'sdate' => $this->request->getGet('sdate'),
            'edate' => $this->request->getGet('edate'),
            'srchType' => $this->request->getGet('srchType'),
            'srchTxt' => $this->request->getGet('srchTxt'),
        ];

        $datas = $this->assignModel->getUserList($start, $end, $data);
        
        // 첫 번째 행에서 total_count 추출 (없으면 0)
        $totalCount = !empty($datas) ? (int)$datas[0]['total_count'] : 0;
        
        // 각 행에서 total_count 컬럼 제거
        foreach ($datas as &$row) {
            unset($row['total_count']);
        }

        return $this->response->setJSON(body: [
            'draw' => $draw,
            'recordsTotal' => $totalCount,
            'recordsFiltered' => $totalCount,
            'data' => $datas,
        ]);
    }

    // 엑셀 다운로드
    public function excel()
    {
        try {

            $data = [
                'bonbu' => $this->request->getGet('bonbu'),
                'team' => $this->request->getGet('team'),
                'schDateGb' => $this->request->getGet('schDateGb'),
                'sdate' => $this->request->getGet('sdate'),
                'edate' => $this->request->getGet('edate'),
                'srchType' => $this->request->getGet('srchType'),
                'srchTxt' => $this->request->getGet('srchTxt'),
            ];

            $datas = $this->assignModel->getExcelUserList($data);

            return $this->response->setJSON(body: [
                'data' => $datas,
            ]);

        } catch (\Exception $e) {
            $e->getPrevious()->getTraceAsString();
        }
    }
}