<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Models\ExemptData;
use App\Models\ExemptReason;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Log;

class CalendarController extends Controller
{
    public function create(Request $request)
    {
        $project_number = $request->input('project_number');
        $exempt_type = $request->input('exempt_type');
        $exempt_reason = $request->input('exempt_reason');
        $duration_unit = $request->input('duration_unit');
        $start_date = new Carbon($request->input('start'));
        $end_date_input = $request->input('end');
        $username = $request->input('username');
        $choice = $request->input('choice');
        $logOnce = $request->input('logOnce');

        try {
            if ($end_date_input != "") {
                // 如果結束日期不為空，使用批量插入
                $end_date = new Carbon($end_date_input);
                $interval = new \DateInterval('P1D');
                $period = new \DatePeriod($start_date, $interval, $end_date->add($interval)); // 確保結束日期包含在週期中

                $batchSize = 1000; // 每次插入1000筆資料
                $exemptDataToInsert = [];
                $exemptReasonToInsert = [];

                foreach ($period as $date) {
                    $currentDate = $date->format('Y-m-d');

                    $eventExists = ExemptData::where('project_number', $project_number)
                        ->whereDate('exempt_date', '=', $currentDate)
                        ->exists();

                    if (!$eventExists) {
                        $exemptDataToInsert[] = [
                            'project_number' => $project_number,
                            'duration_unit' => $duration_unit,
                            'exempt_date' => $currentDate,
                        ];

                        $exemptReasonToInsert[] = [
                            'project_number' => $project_number,
                            'exempt_type' => $exempt_type,
                            'exempt_reason' => $exempt_reason,
                        ];

                        if (count($exemptDataToInsert) >= $batchSize) {
                            $this->insertBatch($exemptDataToInsert, $exemptReasonToInsert);
                            $exemptDataToInsert = [];
                            $exemptReasonToInsert = [];
                        }
                    }
                }

                if (!empty($exemptDataToInsert)) {
                    $this->insertBatch($exemptDataToInsert, $exemptReasonToInsert);
                }
            } else {
                // 如果結束日期為空，將其設為與開始日期相同的日期
                $end_date = clone $start_date;

                $currentDate = $start_date->format('Y-m-d');

                $eventExists = ExemptData::where('project_number', $project_number)
                    ->whereDate('exempt_date', '=', $currentDate)
                    ->exists();

                if (!$eventExists) {
                    $exemptData = $this->createExemptData($project_number, $duration_unit, $currentDate);
                    $this->createExemptReason($project_number, $exempt_type, $exempt_reason, $exemptData->id);
                }
            }

            if ($logOnce == 0) {
                $this->logAction($username, $project_number, '新增篩選條件', '新增' . $choice . '篩選條件', '成功');
            }
            return response()->json(['message' => 'Data processed successfully']);
        } catch (\Exception $e) {
            $this->logAction($username, $project_number, '新增篩選條件', '新增' . $choice . '篩選條件', '失敗');
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }


    public function createBatch(Request $request)
    {
        $project_number = "";
        $username = "";
        $choice = "";

        try {
            $events = $request->input('events');

            if (empty($events)) {
                throw new \Exception('No events provided');
            }

            $batchSize = 1000; // 每次插入100筆資料
            $exemptDataToInsert = [];
            $exemptReasonToInsert = [];

            foreach ($events as $event) {

                $project_number = $event['project_number'];
                $exempt_type = $event['exempt_type'];
                $exempt_reason = $event['exempt_reason'];
                $duration_unit = $event['duration_unit'];
                $start_date = new Carbon($event['start']);
                $username = $event['username'];
                $choice = $event['choice'];

                $currentDate = $start_date->format('Y-m-d');

                $eventExists = ExemptData::where('project_number', $project_number)
                    ->whereDate('exempt_date', '=', $currentDate)
                    ->exists();

                if (!$eventExists) {
                    $exemptDataToInsert[] = [
                        'project_number' => $project_number,
                        'duration_unit' => $duration_unit,
                        'exempt_date' => $currentDate,
                    ];

                    $exemptReasonToInsert[] = [
                        'project_number' => $project_number,
                        'exempt_type' => $exempt_type,
                        'exempt_reason' => $exempt_reason,
                    ];

                    if (count($exemptDataToInsert) >= $batchSize) {
                        $this->insertBatch($exemptDataToInsert, $exemptReasonToInsert);
                        $exemptDataToInsert = [];
                        $exemptReasonToInsert = [];
                    }
                }
            }

            // 插入剩餘的資料
            if (!empty($exemptDataToInsert)) {
                $this->insertBatch($exemptDataToInsert, $exemptReasonToInsert);
            }

            $this->logAction($username, $project_number, '新增篩選條件', '新增' . $choice . '篩選條件', '成功');

            return response()->json([
                'message' => 'Batch creation data ready',
            ]);
        } catch (\Exception $e) {
            $this->logAction($username, $project_number, '新增篩選條件', '新增' . $choice . '篩選條件', '失敗');
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }


    private function insertBatch($exemptDataToInsert, $exemptReasonToInsert)
    {
        try {
            DB::transaction(function () use ($exemptDataToInsert, &$exemptReasonToInsert) {
                // 插入 ExemptData 数据
                ExemptData::insert($exemptDataToInsert);

                // 获取插入的 ExemptData 的 ID
                $insertedIds = ExemptData::whereIn('exempt_date', array_column($exemptDataToInsert, 'exempt_date'))
                    ->whereIn('project_number', array_column($exemptDataToInsert, 'project_number'))
                    ->pluck('id')->toArray();

                foreach ($exemptReasonToInsert as $index => $exemptReason) {
                    $exemptReasonToInsert[$index]['exempt_reason_id'] = $insertedIds[$index] ?? null;
                }

                // 插入 ExemptReason 数据
                ExemptReason::insert($exemptReasonToInsert);
            });
        } catch (\Exception $e) {
            throw $e;
        }
    }



    private function createExemptData($project_number, $duration_unit, $date)
    {
        $exemptData = new ExemptData();
        $exemptData->project_number = $project_number;
        $exemptData->duration_unit = $duration_unit;
        $exemptData->exempt_date = $date;
        $exemptData->save();

        return $exemptData;
    }

    private function createExemptReason($project_number, $exempt_type, $exempt_reason, $exemptDataId)
    {
        $exemptReason = new ExemptReason();
        $exemptReason->project_number = $project_number;
        $exemptReason->exempt_reason_id = $exemptDataId;
        $exemptReason->exempt_type = $exempt_type;
        $exemptReason->exempt_reason = $exempt_reason;
        $exemptReason->save();
    }

    public function read(Request $request)
    {
        $project_number = $request->input('project_number');
        $exemptDataList = ExemptData::where('project_number', $project_number)->get();
        $events = [];

        foreach ($exemptDataList as $exemptData) {
            $exemptReason = ExemptReason::where('exempt_reason_id', $exemptData->id)->first();
            if ($exemptReason) {
                $event = [
                    'id' => $exemptData->id,
                    'title' => $exemptReason->exempt_type,
                    'start' => $exemptData->exempt_date,
                    'end' => $exemptData->exempt_date,
                    'allDay' => true,
                    'work_duration' => $exemptData->duration_unit,
                    'exempt_type' => $exemptData->exempt_type,
                    'exempt_reason' => $exemptReason->exempt_reason,
                ];
                $events[] = $event;

                // 添加一個 title 為 $exemptData->duration_unit 的事件
                $durationEvent = [
                    'id' => 1000000 + $exemptData->id, // 確保這個 id 是唯一的
                    'title' => $exemptData->duration_unit,
                    'start' => $exemptData->exempt_date,
                    'end' => $exemptData->exempt_date,
                    'allDay' => true,
                    'work_duration' => $exemptData->duration_unit,
                    'exempt_type' => $exemptData->exempt_type,
                    'exempt_reason' => $exemptReason->exempt_reason,
                ];
                $events[] = $durationEvent;
            }
        }

        return response()->json($events);
    }

    public function update(Request $request)
    {
        try {
            $eventId = $request->input('id');
            $project_number = $request->input('project_number');
            $exempt_type = $request->input('exempt_type');
            $exempt_reason = $request->input('exempt_reason');
            $duration_unit = $request->input('duration_unit');
            $start_date = new Carbon($request->input('start'));
            $username = $request->input('username');

            // 更新 ExemptData 表中的資料
            $exemptData = ExemptData::where('project_number', $project_number)
                ->where('id', $eventId)
                ->first();

            if ($exemptData) {
                $exemptData->duration_unit = $duration_unit;
                $exemptData->exempt_date = $start_date;
                $exemptData->save();

                // 更新 ExemptReason 表中的資料，如果不存在則創建新的記錄
                $exemptReason = ExemptReason::where('project_number', $project_number)
                    ->where('exempt_reason_id', $eventId)
                    ->first();

                if ($exemptReason) {
                    $exemptReason->exempt_type = $exempt_type;
                    $exemptReason->exempt_reason = $exempt_reason;
                    $exemptReason->save();
                } else {
                    // 如果不存在，則創建一個新的 ExemptReason
                    $this->createExemptReason($project_number, $exempt_type, $exempt_reason, $exemptData->id);
                }

                $this->logAction($username, $project_number, '更新篩選條件', '更新篩選條件', '成功');

                return response()->json(['message' => 'Event updated successfully']);
            } else {
                return response()->json(['error' => 'Event not found'], 404);
            }
        } catch (\Exception $e) {
            $username = $request->input('username');
            $project_number = $request->input('project_number');
            $this->logAction($username, $project_number, '更新篩選條件', '更新篩選條件', '失敗');
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function delete(Request $request)
    {
        $project_number = $request->project_number;
        $username = $request->username;

        try {
            ExemptReason::where('project_number', $request->project_number)
                ->where('exempt_reason_id', $request->eventId)
                ->delete();
            ExemptData::where('project_number', $request->project_number)
                ->where('id', $request->eventId)
                ->delete();

            $this->logAction($username, $project_number, '刪除篩選條件', '刪除篩選條件', '成功');

            return response()->json([
                'message' => 'Event successfully deleted'
            ]);
        } catch (\Exception $e) {
            $this->logAction($username, $project_number, '刪除篩選條件', '刪除篩選條件', '失敗');
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function check(Request $request)
    {
        // 從請求中獲取必要的參數
        $project_number = $request->input('project_number');
        $date = $request->input('date'); // 假設請求中包含日期參數

        // 檢查是否存在該日期的事件
        $eventExists = ExemptData::where('project_number', $project_number)
            ->whereDate('exempt_date', '=', $date)
            ->exists();

        // 回傳是否存在事件的布爾值
        return response()->json(['eventExists' => $eventExists]);
    }

    private function logAction($username, $project_number, $action_type, $action_content, $action_result)
    {
        Log::create([
            'user' => $username,
            'project_number' => $project_number,
            'action_type' => $action_type,
            'action_content' => $action_content,
            'action_result' => $action_result,
            'action_timestamp' => Carbon::now('Asia/Taipei'),
        ]);
    }
}
