<?php

namespace Modules\WebPilotAI\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Helpers\UserAccessHelper;
use App\Models\FeatureCreditCost;
use App\Models\FeatureUsageLog; // Assuming this model exists for logging usage
use App\Services\CreditService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Modules\WebPilotAI\Models\AiWebsite; // Assuming this model exists
use Nwidart\Modules\Facades\Module;

class WebPilotAIController extends Controller
{
    /**
     * @var CreditService
     */
    protected CreditService $creditService;

    public function __construct(CreditService $creditService)
    {
        $this->creditService = $creditService;
        $this->middleware('auth'); // Ensure user is authenticated for all methods
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('webpilotai::index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('webpilotai::create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request) {
        // This could be an alias or the actual endpoint for generateWebsite
        // For clarity, let's assume generateWebsite is a separate, more descriptive method.
        // If store is meant to be the generation endpoint, move the logic from generateWebsite here.
        return $this->generateWebsite($request);
    }

    /**
     * Handles the generation of a new AI website.
     */
    public function generateWebsite(Request $request)
    {
        $user = Auth::user();
        $featureKey = 'webpilotai_generate_website'; // Key for this feature

        // 1. Check initial access
        if (!UserAccessHelper::canAccessFeature($user, $featureKey)) {
            return back()->with('error', 'You do not have access to generate AI websites or insufficient credits.');
        }

        // 2. Determine credit cost for this specific feature
        $creditCost = FeatureCreditCost::where('feature_key', $featureKey)->value('credit_cost');
        if (is_null($creditCost)) {
            $module = Module::find('WebPilotAI');
            $featureDef = null;
            if ($module) {
                $featureDef = collect($module->get('features'))->firstWhere('key', $featureKey);
            }
            $creditCost = $featureDef['credit_cost'] ?? 0;
        }
        $creditCost = (int) $creditCost;

        // 3. If feature costs credits, check balance
        if ($creditCost > 0) {
            if ($user->credit_balance < $creditCost) {
                return back()->with('error', "Generating a website costs {$creditCost} credits. Your balance is {$user->credit_balance}. Please top up.");
            }
        }

        // --- Perform the actual website generation logic ---
        // For example, creating a record in a hypothetical AiWebsite model
        // In a real scenario, this would involve more complex service calls.
        $generatedSite = AiWebsite::create([
            'user_id' => $user->id,
            'name' => $request->input('site_name', 'New AI Site - ' . now()->toDateTimeString()),
            // ... other site data from $request or defaults ...
            'status' => 'generated', // Example status
        ]);
        // --- End of website generation logic ---

        // 4. If generation was successful AND it cost credits, spend them
        if ($generatedSite && $creditCost > 0) {
            $transaction = $this->creditService->spendCredits(
                $user,
                $creditCost,
                'spend_feature_webpilotai', // More specific transaction type
                "Spent {$creditCost} credits for generating AI website: {$generatedSite->name}",
                $generatedSite // Optional: relate transaction to the generated site
            );

            if (!$transaction) {
                Log::critical("Failed to deduct credits for user {$user->id} after generating AiWebsite ID {$generatedSite->id}. Rolling back.");
                $generatedSite->delete(); // Example rollback
                return back()->with('error', 'Could not deduct credits after website generation. The operation was rolled back. Please try again or contact support.');
            }

            // Optional: Log feature usage
            if (class_exists(FeatureUsageLog::class)) {
                FeatureUsageLog::create([
                    'user_id' => $user->id,
                    'feature_key' => $featureKey,
                    'credits_spent' => $creditCost,
                    'details' => json_encode(['website_id' => $generatedSite->id, 'name' => $generatedSite->name]),
                ]);
            }
        }

        // Assuming you have a route named 'frontend.webpilotai.websites.show'
        // If not, adjust to an appropriate route, e.g., back to the websites index or the newly created site's edit page.
        return redirect()->route('frontend.webpilotai.websites.index') // Adjusted to index as show route might not exist yet
                         ->with('success', "AI Website '{$generatedSite->name}' generated successfully!");
    }

    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        return view('webpilotai::show');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        return view('webpilotai::edit');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id) {}

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id) {}
}
