<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdNetwork;
use App\Models\AdUnit;
use Illuminate\Http\Request;

class MonetizationController extends Controller
{
    /**
     * Display the monetization dashboard.
     */
    public function index()
    {
        $networks = AdNetwork::with('adUnits')->get();
        // Separate networks for easier access in view
        $admob = $networks->where('name', 'admob')->first();
        $facebook = $networks->where('name', 'facebook')->first();

        // Common placements for dropdown - matches seeder
        $placements = [
            'home_banner' => 'Home Screen - Banner',
            'home_native' => 'Home Screen - Native Ad',
            'home_interstitial' => 'Home Screen - Interstitial',
            'ad_details_banner' => 'Ad Details - Banner',
            'ad_details_native' => 'Ad Details - Native Ad',
            'ad_details_mid_1' => 'Ad Details - Native Ad 1 (Mid)',
            'ad_details_mid_2' => 'Ad Details - Native Ad 2 (Map)',
            'category_banner' => 'Category Browse - Banner',
            'category_native' => 'Category Browse - Native Ad',
            'category_interstitial' => 'Category Browse - Interstitial',
            'search_banner' => 'Search Results - Banner',
            'search_native' => 'Search Results - Native Ad',
            'post_ad_interstitial' => 'Post Ad Success - Interstitial',
            'post_ad_rewarded' => 'Post Ad Boost - Rewarded Ad',
            'profile_banner' => 'Profile Screen - Banner',
            'my_ads_banner' => 'My Ads - Banner',
            'my_ads_native' => 'My Ads - Native Ad',
            'app_open' => 'App Launch - App Open Ad',
            'chat_banner' => 'Chat List - Banner',
            'chat_detail_banner' => 'Chat Detail - Banner',
            'favorites_native' => 'Favorites - Native Ad',
            'notification_native' => 'Notifications - Native Ad',
        ];

        return view('admin.monetization.index', compact('networks', 'admob', 'facebook', 'placements'));
    }

    /**
     * Update network settings (App ID, Status).
     */
    public function updateNetwork(Request $request, $id)
    {
        $network = AdNetwork::findOrFail($id);
        
        $validated = $request->validate([
            'app_id' => 'nullable|string',
            'is_active' => 'boolean',
            'priority' => 'integer|min:0',
        ]);

        // Handle toggle switch sending 'on' or missing
        $isActive = $request->has('is_active');
        
        $network->update([
            'app_id' => $validated['app_id'],
            'is_active' => $isActive,
            'priority' => $request->input('priority', 0),
        ]);

        return redirect()->route('admin.monetization.index')
            ->with('success', $network->display_name . ' settings updated successfully.');
    }

    /**
     * Store a new Ad Unit.
     */
    public function storeAdUnit(Request $request)
    {
        $validated = $request->validate([
            'ad_network_id' => 'required|exists:ad_networks,id',
            'name' => 'required|string|max:255',
            'placement_identifier' => 'required|string',
            'type' => 'required|in:banner,interstitial,native,rewarded,app_open',
            'ad_unit_id' => 'required|string',
            'is_active' => 'boolean',
            'frequency' => 'integer|min:1',
            'grid_frequency' => 'integer|min:1',
        ]);
        
        $validated['is_active'] = $request->has('is_active');
        $validated['frequency'] = $request->input('frequency', 10);
        $validated['grid_frequency'] = $request->input('grid_frequency', 8);

        AdUnit::create($validated);

        return redirect()->route('admin.monetization.index')
            ->with('success', 'Ad Unit created successfully.');
    }

    /**
     * Update an Ad Unit.
     */
    public function updateAdUnit(Request $request, $id)
    {
        $adUnit = AdUnit::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'ad_unit_id' => 'required|string',
            'is_active' => 'boolean',
            'frequency' => 'required|integer|min:1',
            'grid_frequency' => 'required|integer|min:1',
        ]);

        $validated['is_active'] = $request->has('is_active');

        \Log::info('Updating Ad Unit', [
            'id' => $id,
            'frequency' => $validated['frequency'],
            'grid_frequency' => $validated['grid_frequency'],
        ]);

        $adUnit->update([
            'name' => $validated['name'],
            'ad_unit_id' => $validated['ad_unit_id'],
            'is_active' => $validated['is_active'],
            'frequency' => $validated['frequency'],
            'grid_frequency' => $validated['grid_frequency'],
        ]);

        return redirect()->route('admin.monetization.index')
            ->with('success', 'Ad Unit updated successfully.');
    }

    /**
     * Delete an Ad Unit.
     */
    public function destroyAdUnit($id)
    {
        $adUnit = AdUnit::findOrFail($id);
        $adUnit->delete();

        return redirect()->route('admin.monetization.index')
            ->with('success', 'Ad Unit deleted successfully.');
    }
}
