<?php

namespace App\Http\Services;

use App\Http\Repositories\ApprovalDocRepository;
use App\Http\Repositories\AuthRepository;
use App\Http\Repositories\ChemicalBaseRepository;
use App\Http\Repositories\ChemicalOperationRepository;
use App\Http\Repositories\FactoryRepositories;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

use function PHPUnit\Framework\isEmpty;

class DeclareService
{
    function __construct(
        protected ChemicalOperationRepository $chem_operate,
        protected ChemicalBaseRepository $chem,
        protected AuthRepository $people,
        protected FactoryRepositories $factory,
        protected ApprovalDocRepository $doc,
    ) {}


    public function getMoenvlist($user, $request)
    {
        $query = $this->chem_operate->getMoenvlist($user, $request);

        return $query;
    }

    public function getDangerFactory($user,$request){
        return $this->chem_operate->getDeclarableFactoryCounts($user,$request);
    }
    public function getDangerlist($user, $request)
    {
        return $this->chem_operate->getDeclarableOperationsList($user, $request);
    }

    public function getMoenvReport($request, $user)
    {

        $chemReport = $this->chem_operate->manyReportGet($request, $user);
        $onlyReport = $this->chem_operate->onlyReportGet($request, $user);
        $chemData = $this->chem->useReport($request->chemical_id);
        $op_people = $this->people->getOpUser($onlyReport->custodian);
        $companyData = $this->people->getOpUser($onlyReport->company_id);
        $factoryData = $this->factory->getReportAddress($onlyReport->factory_id, $onlyReport->build_id, $onlyReport->area_id);
        $docData = $this->doc->docOnlyFind($onlyReport->doc_id);
        $remainder = $this->chem_operate->remainder($request, $user);
        //月報無運作
        if (count($chemReport) ===0 && !empty($request->month)) {
            $chemReport = [0 => ['type' => 'R', 'operate_date' => \Carbon\Carbon::createFromFormat('Y-m', $request->year . '-' . $request->month)->endOfMonth()->toDateString(), 'weight' => $remainder, 'remark' => '運作量無變動']];
        }
        //季報無運作
        if (count($chemReport) ===0 && !empty($request->season)) {
            switch ($request->season) {
                case '01-01':
                    $endDate = Carbon::createFromDate($request->year, 3, 31)->endOfDay();
                    break;
                case '04-01':
                    $endDate = Carbon::createFromDate($request->year, 6, 30)->endOfDay();
                    break;
                case '07-01':
                    $endDate = Carbon::createFromDate($request->year, 9, 30)->endOfDay();
                    break;
                case '10-01':

                    $endDate = Carbon::createFromDate($request->year, 12, 31)->endOfDay();
                    break;
                default:
                    // 如果季節無效，設為空或其他處理
                    $endDate = null;
                    break;
            }
            $chemReport = [0 => ['type' => 'R', 'operate_date' => $endDate->toDateString(), 'weight' => $remainder, 'remark' => '運作量無變動']];
        }
        if(count($chemReport) ===0 && $request->year && empty($request->season) && empty($request->month))
        {
            $chemReport = [0 => ['type' => 'R', 'operate_date' => \Carbon\Carbon::createFromFormat('Y-m', $request->year . '-' . 01)->endOfMonth()->toDateString(), 'weight' => $remainder, 'remark' => '運作量無變動']];
        }

                // //季報無運作
                // if (!empty($request->season)) {
                //     switch ($request->season) {
                //         case '01-01':
                //             $months = [1, 2, 3];
                //             break;
                //         case '04-01':
                //             $months = [4, 5, 6];
                //             break;
                //         case '07-01':
                //             $months = [7, 8, 9];
                //             break;
                //         case '10-01':
                //             $months = [10, 11, 12];
                //             break;
                //         default:
                //             $months = [];
                //             break;
                //     }
                //     $year = $request->year;
                //     $quarterlyReport = [];
                //     $existingDates = $chemReport->pluck('operate_date')->toArray();
                //     foreach ($months as $month) {
                //         $startDate = Carbon::createFromDate($year, $month, 1)->startOfMonth()->toDateString();
                //         $endDate = Carbon::createFromDate($year, $month, 1)->endOfMonth()->toDateString();
                //         $hasOperate = array_filter($existingDates, function ($date) use ($startDate, $endDate) {
                //             return $date >= $startDate && $date <= $endDate;
                //         });
                //         // 如果當月已有運作數據，則跳過
                //         if (!empty($hasOperate)) {
                //             continue;
                //         }
                //         $quarterlyReport[] = [
                //             'type' => 'R',
                //             'operate_date' => $endDate,
                //             'weight' => 0,
                //             'remark' => '運作量無變動'
                //         ];
                //     }
                //     // 合併當季有運作的資料與 `quarterlyReport`
                //     $chemReport = array_merge($quarterlyReport, $chemReport->toArray());
        
                //     // 根據 `operate_date` 進行排序
                //     usort($chemReport, function ($a, $b) {
                //         return strtotime($a['operate_date']) - strtotime($b['operate_date']);
                //     });
                // }
                // //年報
                // if ($request->year && empty($request->season) && empty($request->month)) {
                //     $year = $request->year;
                //     // $chemReport = $this->chem_operate->manyReportGet($request, $user);
        
                //     // 取得 `$chemReport` 裡的 `operate_date`
                //     $existingDates = $chemReport->pluck('operate_date')->toArray();
                //     $annualReport = [];
        
                //     for ($i = 1; $i <= 12; $i++) {
                //         $startDate = Carbon::createFromDate($year, $i, 1)->startOfMonth()->toDateString();
                //         $endDate = Carbon::createFromDate($year, $i, 1)->endOfMonth()->toDateString();
        
                //         // 檢查當月是否有運作記錄
                //         $hasOperate = array_filter($existingDates, function ($date) use ($startDate, $endDate) {
                //             return $date >= $startDate && $date <= $endDate;
                //         });
        
                //         // 如果該月已經有運作數據，則跳過
                //         if (!empty($hasOperate)) {
                //             continue;
                //         }
        
                //         // 加入「無運作」的預設資料
                //         $annualReport[] = [
                //             'type' => 'R',
                //             'operate_date' => $endDate,
                //             'weight' => 0,
                //             'remark' => '運作量無變動'
                //         ];
                //     }
        
                //     // 轉換 `$chemReport` 為陣列後合併
                //     $chemReport = array_merge($chemReport->toArray(), $annualReport);
        
                //     // 根據 `operate_date` 進行排序
                //     usort($chemReport, function ($a, $b) {
                //         return strtotime($a['operate_date']) - strtotime($b['operate_date']);
                //     });
                // }
        return [
            'chemOp' => $chemReport,
            'chemData' => $chemData,
            'op_people' => $op_people,
            'companyData' => $companyData,
            'docData'=>$docData,
            'remainder' => $remainder,
            'factoryData' => $factoryData
        ];
    }

    public function getIdaReport($request, $user)
    {   
        $chemReport = $this->chem_operate->IdaReportGet($request, $user)->select('chemical_operations.supplier_id')
            ->addSelect(DB::raw('TO_CHAR(operate_date, \'MM\') as month'))
            ->addSelect(DB::raw('
        SUM(CASE WHEN type = \'C\' THEN chemical_operations.weight ELSE 0 END) as total_weight_production'))
            ->addSelect(DB::raw('
        SUM(CASE WHEN type = \'B\' THEN chemical_operations.weight ELSE 0 END) as total_weight_use'))
            ->addSelect(DB::raw('
        SUM(CASE WHEN type IN (\'A\', \'O\') THEN chemical_operations.weight ELSE 0 END) as total_weight_In'))
            ->addSelect(DB::raw('
        SUM(CASE WHEN type IN (\'P\',\'Q\') THEN chemical_operations.weight ELSE 0 END) as total_weight_Out'))
            ->addSelect(DB::raw('
        SUM(CASE WHEN type IN (\'N\') THEN chemical_operations.weight ELSE 0 END) as total_weight_sold'))
            ->groupBy(DB::raw('TO_CHAR(operate_date, \'MM\')'))
            ->groupBy('operate_date', 'chemical_operations.supplier_id')  // 保證 operate_date 在 group by 中
            ->orderBy('month', 'asc')->get();
        $otherReport = $this->chem_operate->IdaOtherReportGet($request, $user);
        $add = $this->chem_operate->IdaReportGet($request, $user)->whereIn('type', ['C', 'A', 'O'])->sum('chemical_operations.weight');
        $sub = $this->chem_operate->IdaReportGet($request, $user)->whereIn('type', ['B', 'N', 'P', 'Q'])->sum('chemical_operations.weight');
        $remainderSum = round($add - $sub, 8);
        $onlyReport = $this->chem_operate->onlyReportGet($request, $user);
        $chemData = $this->chem->useReport($request->chemical_id);
        $op_people = $this->people->getOpUser($onlyReport->custodian);
        $companyData = $this->people->getOpUser($onlyReport->company_id);
        $factoryData = $this->factory->getReportAddress($onlyReport->factory_id, $onlyReport->build_id, $onlyReport->area_id);
        $remainder = $this->chem_operate->remainder($request, $user);

        return [
            'chemOp' => $chemReport,
            'chemData' => $chemData,
            'op_people' => $op_people,
            'companyData' => $companyData,
            'remainder' => $remainder,
            'remainderSum' => $remainderSum + $remainder,
            'factoryData' => $factoryData,
            'otherReport' => $otherReport
        ];
    }
}
