<?php

namespace App\Http\Controllers\Api;

use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class TailorCalendarController extends BaseController
{
    /**
     * Get calendar bookings for the month
     */
    public function getCalendarBookings($month, $year)
    {
        try {
            // Log input parameters
            \Log::info('Calendar request:', [
                'month' => $month,
                'year' => $year,
                'user_id' => Auth::id(),
                'user_role' => Auth::user()->role
            ]);

            // Validate month and year
            if (!is_numeric($month) || !is_numeric($year) ||
                $month < 1 || $month > 12 ||
                $year < 2024 || $year > 2100) {
                \Log::warning('Invalid date parameters', [
                    'month' => $month,
                    'year' => $year
                ]);
                return $this->sendError('Invalid date', ['error' => 'Bulan atau tahun tidak valid'], 422);
            }

            // Create Carbon instances for start and end of month
            try {
                $startOfMonth = Carbon::create($year, $month, 1)->startOfMonth();
                $endOfMonth = Carbon::create($year, $month, 1)->endOfMonth();

                \Log::info('Date range:', [
                    'start' => $startOfMonth->format('Y-m-d'),
                    'end' => $endOfMonth->format('Y-m-d')
                ]);
            } catch (\Exception $e) {
                \Log::error('Date creation error:', [
                    'message' => $e->getMessage(),
                    'month' => $month,
                    'year' => $year
                ]);
                return $this->sendError('Invalid date', ['error' => 'Format tanggal tidak valid'], 422);
            }

            // Get all bookings for the month
            $bookings = Booking::where('tailor_id', Auth::id())
                ->whereBetween('appointment_date', [
                    $startOfMonth->format('Y-m-d'),
                    $endOfMonth->format('Y-m-d')
                ])
                ->with(['customer:id,name,phone_number'])
                ->orderBy('appointment_date')
                ->orderBy('appointment_time')
                ->get();

            \Log::info('Bookings found:', [
                'count' => $bookings->count(),
                'date_range' => [
                    $startOfMonth->format('Y-m-d'),
                    $endOfMonth->format('Y-m-d')
                ]
            ]);

            // Initialize calendar array
            $calendar = [];
            $currentDate = $startOfMonth->copy();

            // Initialize all dates of the month
            while ($currentDate <= $endOfMonth) {
                $dateStr = $currentDate->format('Y-m-d');
                $calendar[$dateStr] = [
                    'date' => $dateStr,
                    'day' => $currentDate->format('d'),
                    'day_name' => $currentDate->isoFormat('dddd'),
                    'bookings' => []
                ];
                $currentDate->addDay();
            }

            // Add bookings to their respective dates
            foreach ($bookings as $booking) {
                $date = Carbon::parse($booking->appointment_date)->format('Y-m-d');
                if (isset($calendar[$date])) {
                    $calendar[$date]['bookings'][] = [
                        'id' => $booking->id,
                        'time' => $booking->appointment_time,
                        'customer_name' => $booking->customer->name,
                        'customer_phone' => $booking->customer->phone_number,
                        'service_type' => $booking->service_type,
                        'category' => $booking->category,
                        'status' => $booking->status,
                        'payment_status' => $booking->payment_status
                    ];
                }
            }

            // Get month summary
            $summary = [
                'total_bookings' => $bookings->count(),
                'pending_bookings' => $bookings->where('status', 'reservasi')->count(),
                'ongoing_bookings' => $bookings->where('status', 'diproses')->count(),
                'completed_bookings' => $bookings->where('status', 'selesai')->count(),
                'cancelled_bookings' => $bookings->where('status', 'dibatalkan')->count(),
            ];

            \Log::info('Calendar response prepared', [
                'total_dates' => count($calendar),
                'summary' => $summary
            ]);

            return $this->sendResponse([
                'month' => (int)$month,
                'year' => (int)$year,
                'month_name' => Carbon::create($year, $month, 1)->isoFormat('MMMM'),
                'calendar' => array_values($calendar),
                'summary' => $summary
            ], 'Data kalender berhasil diambil');

        } catch (\Exception $e) {
            \Log::error('Calendar error:', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data kalender: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Get bookings for specific date
     */
    public function getDateBookings($date)
    {
        try {
            // Validate date format
            try {
                $bookingDate = Carbon::parse($date);
            } catch (\Exception $e) {
                return $this->sendError('Invalid date', ['error' => 'Format tanggal tidak valid'], 422);
            }

            // Get all bookings for the date
            $bookings = Booking::where('tailor_id', Auth::id())
                ->whereDate('appointment_date', $bookingDate->format('Y-m-d'))
                ->with([
                    'customer:id,name,phone_number,address'
                ])
                ->orderBy('appointment_time')
                ->get();

            // Format bookings with detailed information
            $formattedBookings = $bookings->map(function ($booking) {
                return [
                    'id' => $booking->id,
                    'transaction_code' => $booking->transaction_code,
                    'time' => $booking->appointment_time,
                    'customer' => [
                        'name' => $booking->customer->name,
                        'phone' => $booking->customer->phone_number,
                        'address' => $booking->customer->address
                    ],
                    'service_type' => $booking->service_type,
                    'category' => $booking->category,
                    'status' => $booking->status,
                    'payment_status' => $booking->payment_status,
                    'payment_method' => $booking->payment_method,
                    'notes' => $booking->notes,
                    'measurements' => $booking->measurements,
                    'total_price' => $booking->total_price,
                    'design_photo' => $booking->design_photo ? url('storage/designs/' . $booking->design_photo) : null,
                    'completion_photo' => $booking->completion_photo ? url('storage/completions/' . $booking->completion_photo) : null
                ];
            });

            // Get day summary
            $summary = [
                'total_bookings' => $bookings->count(),
                'pending_bookings' => $bookings->where('status', 'reservasi')->count(),
                'ongoing_bookings' => $bookings->where('status', 'diproses')->count(),
                'completed_bookings' => $bookings->where('status', 'selesai')->count(),
                'cancelled_bookings' => $bookings->where('status', 'dibatalkan')->count(),
            ];

            return $this->sendResponse([
                'date' => $bookingDate->format('Y-m-d'),
                'day_name' => $bookingDate->isoFormat('dddd'),
                'bookings' => $formattedBookings,
                'summary' => $summary
            ], 'Data pesanan tanggal ' . $bookingDate->format('Y-m-d') . ' berhasil diambil');

        } catch (\Exception $e) {
            \Log::error('Calendar date error: ' . $e->getMessage());
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data pesanan: ' . $e->getMessage()], 500);
        }
    }
}
