<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Services\Admin\SettingsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class SchedulerController extends Controller
{
    protected $settingsService;

    public function __construct(SettingsService $settingsService)
    {
        $this->settingsService = $settingsService;
    }

    /**
     * Get scheduler status, token, configuration, and next run time.
     */
    public function index(): JsonResponse
    {
        // 1. Get or create the secure web cron token
        $token = Setting::where('key', 'scheduler_token')->first();
        if (!$token) {
            $token = Setting::create([
                'group' => 'system',
                'key' => 'scheduler_token',
                'value' => Str::random(32),
            ]);
        }

        // 2. Fetch Scheduler Settings
        $settings = $this->settingsService->getGroup('scheduler');

        // Parse Values with Defaults
        $isEnabled = ($settings['rss_schedule_enabled'] ?? 'true') === 'true';
        $frequency = (int) ($settings['rss_schedule_frequency'] ?? 60); // Minutes
        
        // Ensure we get a valid integer for the timestamp
        $lastRun = isset($settings['rss_last_scheduled_run']) ? (int) $settings['rss_last_scheduled_run'] : 0;

        // 3. Calculate Next Run Time
        $nextRun = null;
        if ($isEnabled) {
            if ($lastRun === 0) {
                $nextRun = now()->timestamp; // Pending immediately
            } else {
                $nextRun = $lastRun + ($frequency * 60);
            }
        }

        return response()->json([
            'token' => $token->value,
            'config' => [
                'rss_schedule_enabled' => $isEnabled,
                'rss_schedule_frequency' => $frequency,
                'rss_last_scheduled_run' => $lastRun,
                'rss_next_scheduled_run' => $nextRun,
            ]
        ]);
    }

    /**
     * Update RSS Schedule Settings (Frequency & Enable/Disable).
     */
    public function updateSettings(Request $request): JsonResponse
    {
        $data = $request->validate([
            'rss_schedule_enabled' => 'required|boolean',
            'rss_schedule_frequency' => 'required|integer|min:1|max:1440',
        ]);

        $settings = [
            'rss_schedule_enabled' => $data['rss_schedule_enabled'] ? 'true' : 'false',
            'rss_schedule_frequency' => $data['rss_schedule_frequency'],
        ];

        // Save to Database
        $this->settingsService->updateGroup('scheduler', $settings);

        Cache::forget('settings.scheduler');

        return response()->json(['message' => 'Scheduler settings updated successfully.']);
    }

    /**
     * Regenerate the web cron security token.
     */
    public function regenerateToken(): JsonResponse
    {
        $newToken = Str::random(32);

        Setting::updateOrCreate(
            ['key' => 'scheduler_token'],
            ['group' => 'system', 'value' => $newToken]
        );

        return response()->json([
            'message' => 'Token regenerated successfully.',
            'token' => $newToken,
        ]);
    }

    /**
     * Run the RSS Crawler via Web Request (External Cron like cron-job.org).
     */
    public function runScheduler(Request $request, $token): JsonResponse
    {
        $storedToken = Setting::where('key', 'scheduler_token')->value('value');

        if (!$storedToken || $token !== $storedToken) {
            abort(403, 'Unauthorized access.');
        }

        // Increase timeout for web requests
        set_time_limit(300);

        try {
            // 1. Call command WITHOUT --force. 
            Artisan::call('rss:crawl');

            Cache::forget('settings.scheduler');

            return response()->json([
                'success' => true,
                'message' => 'Web Cron ping processed successfully.',
            ]);
        } catch (\Exception $e) {
            Log::error("Web Cron Failed: " . $e->getMessage());
            return response()->json(['success' => false, 'message' => 'Web Cron failed.'], 500);
        }
    }

    /**
     * Manually trigger the RSS Crawler via Admin UI ("Run Now" button).
     */
    public function runGlobalCrawl(): JsonResponse
    {
        set_time_limit(300);

        try {
            // 1. Dispatch Jobs (--force bypasses the frequency timer & disable switch)
            Artisan::call('rss:crawl', ['--force' => true]);
            
            // 2. Update Last Run Time in Database so UI reflects the manual run immediately
            Setting::updateOrCreate(
                ['key' => 'rss_last_scheduled_run'], 
                ['group' => 'scheduler', 'value' => (string) now()->timestamp]
            );

            // Clear cache for fresh UI data
            Cache::forget('settings.scheduler');

            return response()->json([
                'success' => true,
                'message' => 'Crawl jobs dispatched and processed successfully.',
            ]);
        } catch (\Exception $e) {
            Log::error("Manual Crawl Failed: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to process crawler: ' . $e->getMessage()
            ], 500);
        }
    }
}