<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CronJobSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class CronJobController extends Controller
{
    public function index()
    {
        $jobs = CronJobSetting::orderBy('id')->get();
        return view('backEnd.cronjob.index', compact('jobs'));
    }

    public function toggle(Request $request, $id)
    {
        $job = CronJobSetting::findOrFail($id);
        $job->is_enabled = !$job->is_enabled;
        $job->save();

        $state = $job->is_enabled ? 'চালু' : 'বন্ধ';
        return response()->json([
            'success'    => true,
            'is_enabled' => $job->is_enabled,
            'message'    => "\"{$job->job_title}\" এখন {$state} করা হয়েছে।",
        ]);
    }

    public function update_settings(Request $request, $id)
    {
        $request->validate([
            'frequency_minutes' => 'required|integer|min:1|max:1440',
            'order_limit'       => 'required|integer|min:0|max:500',
        ]);

        $job = CronJobSetting::findOrFail($id);
        $job->update([
            'frequency_minutes' => $request->frequency_minutes,
            'order_limit'       => $request->order_limit,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'সেটিংস সেভ হয়েছে।',
        ]);
    }

    public function run_now(Request $request, $id)
    {
        $job = CronJobSetting::findOrFail($id);

        if (!in_array($job->job_key, ['courier_status_sync', 'system_clear_junks'])) {
            return response()->json(['success' => false, 'message' => 'Unknown job.'], 400);
        }

        if ($job->last_run_status === 'running') {
            // If it's been running for more than 10 minutes, assume it crashed and allow rerun
            if ($job->last_run_at && $job->last_run_at->diffInMinutes(now()) < 10) {
                return response()->json(['success' => false, 'message' => 'ইতিমধ্যে চলছে, একটু অপেক্ষা করুন।'], 409);
            }
        }

        try {
            \Illuminate\Support\Facades\Log::info("Manually running cron job: " . $job->job_key);
            
            // Mark as running before start
            $job->update(['last_run_status' => 'running', 'last_run_result' => 'প্রসেস শুরু হচ্ছে...']);

            if ($job->job_key === 'courier_status_sync') {
                $limit = $job->order_limit ?: 50;
                $exitCode = Artisan::call('courier:check-status', [
                    '--limit' => (int)$limit,
                    '--force' => true
                ]);
            } elseif ($job->job_key === 'system_clear_junks') {
                $exitCode = Artisan::call('system:clear-junks');
                
                // For system clear junks, we manually update the result if successful
                if ($exitCode === 0) {
                    $job->update([
                        'last_run_at' => now(),
                        'last_run_status' => 'success',
                        'last_run_result' => 'সিস্টেম ক্যাশ এবং জাঙ্ক ফাইল সফলভাবে ডিলিট করা হয়েছে।',
                    ]);
                }
            } else {
                $exitCode = 1;
            }

            $output = Artisan::output();
            \Illuminate\Support\Facades\Log::info("Cron job output for {$job->job_key}: " . $output);

            // Reload to get updated stats (courier sync updates its own stats)
            $job->refresh();

            if ($exitCode !== 0) {
                $job->update(['last_run_status' => 'failed', 'last_run_result' => 'ত্রুটি: ' . trim($output)]);
            }

            return response()->json([
                'success'        => $exitCode === 0,
                'message'        => $exitCode === 0 ? 'সফলভাবে রান করা হয়েছে।' : 'রান ব্যর্থ হয়েছে।',
                'last_run_at'    => $job->last_run_at ? $job->last_run_at->format('d M Y, h:i A') : null,
                'last_run_status'=> $job->last_run_status,
                'last_run_result'=> $job->last_run_result,
                'updated_count'  => $job->last_updated_count,
                'failed_count'   => $job->last_failed_count,
                'output'         => trim($output),
            ]);
        } catch (\Throwable $e) {
            \Illuminate\Support\Facades\Log::error("Cron Job Error ({$job->job_key}): " . $e->getMessage());
            $job->update(['last_run_status' => 'failed', 'last_run_result' => 'Error: ' . $e->getMessage()]);
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function status(Request $request, $id)
    {
        $job = CronJobSetting::findOrFail($id);
        return response()->json([
            'is_enabled'      => $job->is_enabled,
            'last_run_at'     => $job->last_run_at ? $job->last_run_at->format('d M Y, h:i A') : null,
            'last_run_status' => $job->last_run_status,
            'last_run_result' => $job->last_run_result,
            'updated_count'   => $job->last_updated_count,
            'failed_count'    => $job->last_failed_count,
        ]);
    }
}
