<?php

namespace App\Http\Controllers;

use App\Models\Advertisement;
use Illuminate\Http\Request;

class AdvertisementController extends Controller
{
    /**
     * نمایش تبلیغات برای یک موقعیت خاص
     */
    public function show($position)
    {
        $advertisements = Advertisement::getActiveForPosition($position);
        return view('advertisements.show', compact('advertisements', 'position'));
    }

    /**
     * نمایش تبلیغات در صفحه اصلی
     */
    public function homepage()
    {
        $heroAds = Advertisement::getActiveForPosition('homepage_hero');
        $sidebarAds = Advertisement::getActiveForPosition('homepage_sidebar');
        $featuredAds = Advertisement::getActiveForPosition('homepage_featured');
        $middleAds = Advertisement::getActiveForPosition('homepage_middle');
        $bottomAds = Advertisement::getActiveForPosition('homepage_bottom');
        $popupAds = Advertisement::getActiveForPosition('popup');

        return view('advertisements.homepage', compact(
            'heroAds',
            'sidebarAds',
            'featuredAds',
            'middleAds',
            'bottomAds',
            'popupAds'
        ));
    }

    /**
     * Track advertisement views.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function trackView($id)
    {
        $advertisement = Advertisement::findOrFail($id);
        $advertisement->incrementViews();

        return response()->json(['success' => true]);
    }

    /**
     * Track advertisement clicks and redirect to target URL.
     *
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function trackClick($id)
    {
        $advertisement = Advertisement::findOrFail($id);
        $advertisement->incrementClicks();

        // Make sure to return a proper redirect response
        if (! $advertisement->target_url) {
            return redirect()->back();
        }

        return redirect()->away($advertisement->target_url);
    }

    /**
     * Get active advertisements for a specific position.
     *
     * @param  string  $position
     * @return \Illuminate\Http\Response
     */
    public function getAdsByPosition($position)
    {
        $ads = Advertisement::active()
            ->byPosition($position)
            ->orderBy('display_order')
            ->limit(5) // Limit the number of ads returned
            ->get();

        return response()->json($ads);
    }

    /**
     * Get active text advertisements for the ticker.
     *
     * @return \Illuminate\Http\Response
     */
    public function getTextAds()
    {
        $ads = Advertisement::active()
            ->where('is_active', true)
            ->select('id', 'title as content', 'target_url')
            ->orderBy('display_order')
            ->limit(10)
            ->get();

        return response()->json(['success' => true, 'ads' => $ads]);
    }
}
