<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Leave;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;

class LeaveController extends Controller
{
    public function index(Request $request)
    {
        if (! Schema::hasTable('leaves')) {
            return response()->json([
                'leaves' => [],
                'has_approved_today' => false,
            ]);
        }

        $user = $request->user();
        $user->loadMissing('employee');

        $tz = 'Asia/Baghdad';
        $today = Carbon::now($tz)->toDateString();

        $hasApprovedToday = Leave::query()
            ->where('user_id', $user->id)
            ->where('status', 'approved')
            ->whereDate('leave_date', $today)
            ->exists();

        $startOfMonth = Carbon::now($tz)->startOfMonth()->toDateString();
        $endOfMonth = Carbon::now($tz)->endOfMonth()->toDateString();

        $usedPaidLeaves = Leave::query()
            ->where('user_id', $user->id)
            ->where('leave_type', 'full_day')
            ->where('is_paid', true)
            ->whereIn('status', ['pending', 'approved'])
            ->whereBetween('leave_date', [$startOfMonth, $endOfMonth])
            ->count();

        $leaves = Leave::query()
            ->where('user_id', $user->id)
            ->orderByDesc('leave_date')
            ->orderByDesc('id')
            ->get()
            ->map(fn (Leave $leave) => $this->serializeLeave($leave))
            ->values();

        return response()->json([
            'leaves' => $leaves,
            'has_approved_today' => $hasApprovedToday,
            'used_paid_leaves_this_month' => $usedPaidLeaves,
        ]);
    }

    public function store(Request $request)
    {
        if (! Schema::hasTable('leaves')) {
            return response()->json([
                'message' => 'الخادم غير جاهز للإجازات بعد. يرجى تشغيل ترحيلات قاعدة البيانات (php artisan migrate).',
            ], 409);
        }

        $user = $request->user();
        $user->loadMissing('employee');

        if (! $user->employee) {
            return response()->json([
                'message' => 'لا يوجد موظف مرتبط بهذا المستخدم',
            ], 409);
        }

        $validated = $request->validate([
            'leave_type' => 'required|in:full_day,timed',
            'leave_date' => 'required|date',
            'leave_time' => 'nullable|date_format:H:i',
            'reason' => 'nullable|string|max:2000',
            'is_paid' => 'nullable|boolean',
        ]);

        if ($validated['leave_type'] === 'timed' && empty($validated['leave_time'])) {
            return response()->json([
                'message' => 'يرجى اختيار الوقت للإجازة الزمنية',
            ], 422);
        }

        $isPaid = $validated['leave_type'] === 'timed'
            ? true
            : ($validated['is_paid'] ?? false);

        if ($validated['leave_type'] === 'full_day' && $isPaid) {
            $tz = 'Asia/Baghdad';
            $startOfMonth = Carbon::now($tz)->startOfMonth()->toDateString();
            $endOfMonth = Carbon::now($tz)->endOfMonth()->toDateString();

            $usedPaidLeaves = Leave::query()
                ->where('user_id', $user->id)
                ->where('leave_type', 'full_day')
                ->where('is_paid', true)
                ->whereIn('status', ['pending', 'approved'])
                ->whereBetween('leave_date', [$startOfMonth, $endOfMonth])
                ->count();

            if ($usedPaidLeaves >= 3) {
                return response()->json([
                    'message' => 'لقد استنفذت رصيد الإجازات المدفوعة لهذا الشهر (3 أيام)',
                ], 422);
            }
        }

        $leaveDate = Carbon::parse($validated['leave_date'])->toDateString();
        $leaveTime = isset($validated['leave_time']) && trim((string) $validated['leave_time']) !== ''
            ? trim((string) $validated['leave_time']).':00'
            : null;

        $leave = Leave::create([
            'user_id' => $user->id,
            'employee_id' => $user->employee->id,
            'leave_type' => $validated['leave_type'],
            'is_paid' => $isPaid,
            'leave_date' => $leaveDate,
            'leave_time' => $leaveTime,
            'reason' => $validated['reason'] ?? null,
            'status' => 'pending',
        ]);

        return response()->json([
            'message' => 'تم إرسال طلب الإجازة',
            'leave' => $this->serializeLeave($leave),
        ], 201);
    }

    private function serializeLeave(Leave $leave): array
    {
        return [
            'id' => $leave->id,
            'leave_type' => $leave->leave_type,
            'is_paid' => (bool) $leave->is_paid,
            'leave_date' => $leave->leave_date?->toDateString(),
            'leave_time' => $leave->leave_time,
            'reason' => $leave->reason,
            'status' => $leave->status,
            'created_at' => $leave->created_at?->toIso8601String(),
        ];
    }
}
