<?php

namespace App\Modules\Quotes;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\BaseController;
use App\Modules\Quotes\Quote;
use App\Settings;

class QuoteController extends BaseController
{

    /**
     * Display the Quote of the Day management page.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $quotes = Quote::orderBy('created_at', 'desc')->paginate(20);
        
        // Get current page tracking info
        $setting = Settings::find('quotes_last_page');
        $currentPage = $setting ? (int)$setting->value : 1;
        
        $data = [
            'quotes' => $quotes,
            'totalQuotes' => Quote::count(),
            'currentPage' => $currentPage,
        ];
        
        return view('quotes::index', $data);
    }

    /**
     * Store a new manually entered quote.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'text' => 'required|string|max:1000',
            'author' => 'required|string|max:255',
            'category' => 'nullable|string|max:100',
        ]);

        // Check if quote already exists
        if (Quote::existsByText($request->text)) {
            return redirect()->back()->with('error', 'This quote already exists in the database.');
        }

        Quote::create([
            'text' => $request->text,
            'author' => $request->author,
            'category' => $request->category,
        ]);

        return redirect()->back()->with('success', 'Quote added successfully!');
    }

    /**
     * Update an existing quote.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $request->validate([
                'text' => 'required|string|max:1000',
                'author' => 'required|string|max:255',
                'category' => 'nullable|string|max:100',
            ]);

            $quote = Quote::findOrFail($id);

            // Check if quote text already exists (excluding current quote)
            if (Quote::where('text', $request->text)->where('id', '!=', $id)->exists()) {
                $errorMessage = 'This quote already exists in the database.';
                
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $errorMessage
                    ], 422);
                }
                
                return redirect()->back()->with('error', $errorMessage);
            }

            $quote->update([
                'text' => $request->text,
                'author' => $request->author,
                'category' => $request->category,
            ]);

            $successMessage = 'Quote updated successfully!';
            
            // If AJAX request, return JSON response
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => $successMessage,
                    'quote' => $quote
                ]);
            }

            return redirect()->back()->with('success', $successMessage);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $e->errors()
                ], 422);
            }
            
            return redirect()->back()->withErrors($e->errors())->withInput();
            
        } catch (\Exception $e) {
            Log::error('Error updating quote: ' . $e->getMessage());
            
            $errorMessage = 'Error updating quote. Please try again.';
            
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $errorMessage
                ], 500);
            }

            return redirect()->back()->with('error', $errorMessage);
        }
    }

    /**
     * Delete a quote.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        try {
            $quote = Quote::findOrFail($id);
            $quote->delete();

            // If AJAX request, return JSON response
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Quote deleted successfully!'
                ]);
            }

            return redirect()->back()->with('success', 'Quote deleted successfully!');
        } catch (\Exception $e) {
            Log::error('Error deleting quote: ' . $e->getMessage());
            
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error deleting quote. Please try again.'
                ], 500);
            }

            return redirect()->back()->with('error', 'Error deleting quote. Please try again.');
        }
    }

    /**
     * Fetch quotes from Real Inspire API
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function fetchQuotes(Request $request)
    {
        try {
            // Get the last fetched page from settings (defaults to 1)
            $setting = Settings::find('quotes_last_page');
            $lastPage = $setting ? (int)$setting->value : 1;
            
            // Fetch 20 quotes from the Real Inspire API
            $apiUrl = 'https://api.realinspire.live/v1/quotes';
            $response = Http::timeout(30)->get($apiUrl, [
                'page' => $lastPage,
                'limit' => 20
            ]);
            
            if (!$response->successful()) {
                $errorMessage = 'Failed to fetch quotes from Real Inspire API. Please try again later.';
                
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $errorMessage
                    ], 500);
                }
                
                return redirect()->back()->with('error', $errorMessage);
            }

            $data = $response->json();
            
            if (!isset($data['results']) || !is_array($data['results'])) {
                $errorMessage = 'Invalid response format from Real Inspire API.';
                
                if ($request->expectsJson() || $request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $errorMessage
                    ], 500);
                }
                
                return redirect()->back()->with('error', $errorMessage);
            }
            
            $quotesAdded = 0;
            $quotesSkipped = 0;
            
            // Process each quote from the API response
            foreach ($data['results'] as $quoteData) {
                try {
                    $quoteText = trim($quoteData['content'] ?? '');
                    $author = trim($quoteData['author'] ?? 'Unknown');
                    
                    // Skip if text is empty or too short
                    if (empty($quoteText) || strlen($quoteText) < 10) {
                        continue;
                    }
                    
                    // Check if quote already exists
                    if (Quote::existsByText($quoteText)) {
                        $quotesSkipped++;
                        continue;
                    }
                    
                    // Create the quote
                    Quote::create([
                        'text' => $quoteText,
                        'author' => $author,
                        'category' => 'Real Inspire',
                    ]);
                    
                    $quotesAdded++;
                } catch (\Exception $e) {
                    Log::error('Error processing quote: ' . $e->getMessage());
                }
            }
            
            // Update the last fetched page for next time
            $currentPage = $data['currentPage'] ?? $lastPage;
            $totalPages = $data['totalPages'] ?? 1;
            
            // Move to next page, or reset to 1 if we've reached the end
            $nextPage = ($currentPage >= $totalPages) ? 1 : $currentPage + 1;
            
            // Store the next page in settings
            $setting = Settings::find('quotes_last_page');
            if ($setting) {
                $setting->value = $nextPage;
                $setting->save();
            } else {
                Settings::create([
                    'key' => 'quotes_last_page',
                    'value' => $nextPage
                ]);
            }
            
            // Log API information
            Log::info("Real Inspire API fetch completed", [
                'current_page' => $currentPage,
                'total_pages' => $totalPages,
                'next_page' => $nextPage,
                'quotes_added' => $quotesAdded,
                'quotes_skipped' => $quotesSkipped
            ]);
            
            $message = "Quotes fetched successfully from Real Inspire API! Added: {$quotesAdded} quotes";
            if ($quotesSkipped > 0) {
                $message .= ", Skipped: {$quotesSkipped} duplicates";
            }
            $message .= " (Page {$currentPage} of {$totalPages})";
            
            // If AJAX request, return JSON response
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => true,
                    'message' => $message,
                    'data' => [
                        'quotesAdded' => $quotesAdded,
                        'quotesSkipped' => $quotesSkipped,
                        'currentPage' => $currentPage,
                        'totalPages' => $totalPages,
                        'nextPage' => $nextPage
                    ]
                ]);
            }
            
            return redirect()->back()->with('success', $message);
            
        } catch (\Exception $e) {
            Log::error('Error fetching quotes from Real Inspire API: ' . $e->getMessage());
            
            $errorMessage = 'An error occurred while fetching quotes from Real Inspire API. Please try again later.';
            
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $errorMessage
                ], 500);
            }
            
            return redirect()->back()->with('error', $errorMessage);
        }
    }

    /**
     * Reset the page tracking for quote fetching (for debugging/admin use)
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function resetPageTracking(Request $request)
    {
        // Reset page tracking to 1
        $setting = Settings::find('quotes_last_page');
        if ($setting) {
            $setting->value = 1;
            $setting->save();
        } else {
            Settings::create([
                'key' => 'quotes_last_page',
                'value' => 1
            ]);
        }
        
        Log::info('Quote page tracking reset to start from page 1');
        
        if ($request->expectsJson() || $request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Page tracking reset to start from page 1'
            ]);
        }
        
        return redirect()->back()->with('success', 'Page tracking reset to start from page 1');
    }
}