<?php
// app/Http/Controllers/SeasonalCalendarController.php

namespace App\Http\Controllers;

use App\Models\SeasonalCalendar;
use App\Models\SeasonalCache; // Add this import
use App\Services\SeasonalPriceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class SeasonalCalendarController extends Controller
{
    protected $seasonalPriceService;

    public function __construct(SeasonalPriceService $seasonalPriceService)
    {
        $this->seasonalPriceService = $seasonalPriceService;
    }

    /**
     * Get all seasonal calendars
     */
    public function index()
    {
        $calendars = SeasonalCalendar::orderBy('priority', 'desc')
            ->orderBy('start_date')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $calendars
        ]);
    }

    /**
     * Create new seasonal calendar
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'price_increase_percentage' => 'required|numeric|min:0|max:1000',
            'session_type' => 'required|in:regular,special',
            'color_code' => 'required|string|max:7',
            'recurring_yearly' => 'boolean',
            'is_active' => 'boolean',
            'priority' => 'integer|min:1|max:10'
        ]);

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

        try {
            $calendar = SeasonalCalendar::create($request->all());

            // Clear cache when new session is added
            $this->clearSeasonalCache();

            return response()->json([
                'success' => true,
                'message' => 'Seasonal calendar created successfully',
                'data' => $calendar
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to create seasonal calendar',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update seasonal calendar
     */
    public function update(Request $request, $id)
    {
        $calendar = SeasonalCalendar::find($id);

        if (!$calendar) {
            return response()->json([
                'success' => false,
                'error' => 'Seasonal calendar not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'sometimes|required|date',
            'end_date' => 'sometimes|required|date|after_or_equal:start_date',
            'price_increase_percentage' => 'sometimes|required|numeric|min:0|max:1000',
            'session_type' => 'sometimes|required|in:regular,special',
            'color_code' => 'sometimes|required|string|max:7',
            'recurring_yearly' => 'boolean',
            'is_active' => 'boolean',
            'priority' => 'integer|min:1|max:10'
        ]);

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

        try {
            $calendar->update($request->all());

            // Clear cache when session is updated
            $this->clearSeasonalCache();

            return response()->json([
                'success' => true,
                'message' => 'Seasonal calendar updated successfully',
                'data' => $calendar
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to update seasonal calendar',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete seasonal calendar
     */
    public function destroy($id)
    {
        $calendar = SeasonalCalendar::find($id);

        if (!$calendar) {
            return response()->json([
                'success' => false,
                'error' => 'Seasonal calendar not found'
            ], 404);
        }

        try {
            $calendar->delete();

            // Clear cache when session is deleted
            $this->clearSeasonalCache();

            return response()->json([
                'success' => true,
                'message' => 'Seasonal calendar deleted successfully'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to delete seasonal calendar',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Calculate seasonal price
     */
    public function calculatePrice(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'base_price' => 'required|numeric|min:0',
            'date' => 'required|date',
            'travel_agent_id' => 'required|exists:travel_agents,id'
        ]);

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

        try {
            $result = $this->seasonalPriceService->calculateAdjustedPrice(
                $request->base_price,
                Carbon::parse($request->date),
                $request->travel_agent_id
            );

            return response()->json([
                'success' => true,
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Price calculation failed',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Bulk calculate seasonal prices
     */
    public function calculateBulkPrices(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'dates' => 'required|array',
            'dates.*' => 'date',
            'travel_agent_id' => 'required|exists:travel_agents,id'
        ]);

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

        try {
            $results = $this->seasonalPriceService->getBulkMultipliers(
                $request->dates,
                $request->travel_agent_id
            );

            return response()->json([
                'success' => true,
                'data' => $results
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Bulk price calculation failed',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get seasonal calendar view
     */
    public function getCalendar(Request $request, $year, $month = null)
    {
        $validator = Validator::make(['year' => $year, 'month' => $month], [
            'year' => 'required|integer|min:2020|max:2030',
            'month' => 'nullable|integer|min:1|max:12'
        ]);

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

        try {
            $calendar = $this->seasonalPriceService->getSeasonalCalendar($year, $month);

            return response()->json([
                'success' => true,
                'data' => $calendar
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Failed to get calendar',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Pre-cache seasonal data
     */
    public function preCache(Request $request, $year)
    {
        $validator = Validator::make(['year' => $year], [
            'year' => 'required|integer|min:2020|max:2030'
        ]);

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

        try {
            $this->seasonalPriceService->preCacheYear($year);

            return response()->json([
                'success' => true,
                'message' => "Seasonal data pre-cached for year $year"
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => 'Pre-caching failed',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Clear seasonal cache
     */
    private function clearSeasonalCache()
    {
        try {
            // Clear Laravel cache
            \Cache::flush();
            
            // Clear database cache using the model
            SeasonalCache::truncate();
            
        } catch (\Exception $e) {
            // Log the error but don't fail the request
            \Log::error('Failed to clear seasonal cache: ' . $e->getMessage());
            
            // You can also log more details for debugging
            \Log::error('Cache clearing error details:', [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}