<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Reservation;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class ReservationApprovalController extends Controller
{
    /**
     * Approve reservation
     */
    public function approve(Request $request, int $id): JsonResponse
    {
        $reservation = Reservation::findOrFail($id);

        if (!in_array($reservation->status, ['pending', 'awaiting_approval'])) {
            return response()->json([
                'message' => 'Reservation cannot be approved'
            ], 422);
        }

        try {
            DB::beginTransaction();

            $reservation->update([
                'status' => 'approved',
                'approved_by' => $request->user()->id,
                'approved_at' => now(),
            ]);

            // Change status to payment_pending after approval
            $reservation->update(['status' => 'payment_pending']);

            // TODO: Create payment link and send email
            // Event: ReservationApproved
            // Listener: CreatePaymentLink, SendPaymentLinkEmail

            DB::commit();

            return response()->json([
                'message' => 'Reservation approved successfully',
                'reservation' => $reservation->fresh(),
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'Approval failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Reject reservation
     */
    public function reject(Request $request, int $id): JsonResponse
    {
        $reservation = Reservation::findOrFail($id);

        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'reason' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        if (!in_array($reservation->status, ['pending', 'awaiting_approval'])) {
            return response()->json([
                'message' => 'Reservation cannot be rejected'
            ], 422);
        }

        try {
            DB::beginTransaction();

            $reservation->update([
                'status' => 'cancelled',
                'admin_notes' => $request->reason ?? 'Rejected by admin',
            ]);

            // Refund tour date booked count
            $totalGuests = $reservation->guests()->count();
            $reservation->tourDate->decrement('booked', $totalGuests);

            // TODO: Send rejection email
            // Event: ReservationRejected
            // Listener: SendRejectionEmail

            DB::commit();

            return response()->json([
                'message' => 'Reservation rejected successfully',
                'reservation' => $reservation->fresh(),
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'message' => 'Rejection failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk approve reservations
     */
    public function bulkApprove(Request $request): JsonResponse
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'reservation_ids' => 'required|array',
            'reservation_ids.*' => 'exists:reservations,id',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        $reservations = Reservation::whereIn('id', $request->reservation_ids)
            ->whereIn('status', ['pending', 'awaiting_approval'])
            ->get();

        $approved = 0;
        foreach ($reservations as $reservation) {
            try {
                $reservation->update([
                    'status' => 'payment_pending',
                    'approved_by' => $request->user()->id,
                    'approved_at' => now(),
                ]);
                $approved++;
            } catch (\Exception $e) {
                // Continue with next
            }
        }

        return response()->json([
            'message' => "{$approved} reservations approved successfully",
            'approved_count' => $approved,
        ]);
    }

    /**
     * Bulk reject reservations
     */
    public function bulkReject(Request $request): JsonResponse
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'reservation_ids' => 'required|array',
            'reservation_ids.*' => 'exists:reservations,id',
            'reason' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation error',
                'errors' => $validator->errors()
            ], 422);
        }

        $reservations = Reservation::whereIn('id', $request->reservation_ids)
            ->whereIn('status', ['pending', 'awaiting_approval'])
            ->get();

        $reason = $request->reason ?? 'Toplu red';
        $rejected = 0;

        foreach ($reservations as $reservation) {
            try {
                $reservation->update([
                    'status' => 'cancelled',
                    'admin_notes' => $reason,
                ]);
                $totalGuests = $reservation->guests()->count();
                if ($reservation->tourDate) {
                    $reservation->tourDate->decrement('booked', $totalGuests);
                }
                $rejected++;
            } catch (\Exception $e) {
                // continue
            }
        }

        return response()->json([
            'message' => "{$rejected} rezervasyon reddedildi",
            'rejected_count' => $rejected,
        ]);
    }
}
