<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Advertisement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AdvertisementController extends Controller
{
    /**
     * Display a listing of the advertisements.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $advertisements = Advertisement::query()
            ->orderBy('display_order')
            ->orderBy('id', 'desc')
            ->paginate(15);

        return view('admin.advertisements.index', compact('advertisements'));
    }

    /**
     * Show the form for creating a new advertisement.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $positions = $this->getAvailablePositions();
        $adTypes = $this->getAvailableAdTypes();

        return view('admin.advertisements.create', compact('positions', 'adTypes'));
    }

    /**
     * Store a newly created advertisement in storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'ad_type' => 'required|string|max:255',
            'position' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'html_content' => 'nullable|string',
            'target_url' => 'nullable|url|max:255',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'is_active' => 'boolean',
            'display_order' => 'integer|min:0',
            'speed' => 'integer|min:5|max:60',
            'direction' => 'required|in:rtl,ltr',
            'animation_type' => 'required|in:none,blink,fade,pulse,slide',
            'text_color' => 'required|string|max:20',
            'size' => 'nullable|string|max:255',
            'advertiser_name' => 'nullable|string|max:255',
            'advertiser_contact' => 'nullable|string|max:255',
        ]);

        // Handle image upload
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('advertisements', 'public');
            $validated['image_path'] = $imagePath;
        }

        // Set default speed if not provided
        if (! isset($validated['speed'])) {
            $validated['speed'] = 20;
        }

        Advertisement::create($validated);

        return redirect()->route('admin.advertisements.index')
            ->with('success', 'تبلیغ با موفقیت ایجاد شد.');
    }

    /**
     * Show the form for editing the specified advertisement.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $advertisement = Advertisement::findOrFail($id);
        $positions = $this->getAvailablePositions();
        $adTypes = $this->getAvailableAdTypes();

        return view('admin.advertisements.edit', compact('advertisement', 'positions', 'adTypes'));
    }

    /**
     * Update the specified advertisement in storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $advertisement = Advertisement::findOrFail($id);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'ad_type' => 'required|string|max:255',
            'position' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
            'html_content' => 'nullable|string',
            'target_url' => 'nullable|url|max:255',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'is_active' => 'boolean',
            'display_order' => 'integer|min:0',
            'speed' => 'integer|min:5|max:60',
            'direction' => 'required|in:rtl,ltr',
            'animation_type' => 'required|in:none,blink,fade,pulse,slide',
            'text_color' => 'required|string|max:20',
            'size' => 'nullable|string|max:255',
            'advertiser_name' => 'nullable|string|max:255',
            'advertiser_contact' => 'nullable|string|max:255',
        ]);

        // Handle image upload
        if ($request->hasFile('image')) {
            // Delete old image
            if ($advertisement->image_path) {
                Storage::disk('public')->delete($advertisement->image_path);
            }

            $imagePath = $request->file('image')->store('advertisements', 'public');
            $validated['image_path'] = $imagePath;
        }

        // Set default speed if not provided
        if (! isset($validated['speed'])) {
            $validated['speed'] = 20;
        }

        $advertisement->update($validated);

        return redirect()->route('admin.advertisements.index')
            ->with('success', 'تبلیغ با موفقیت بروزرسانی شد.');
    }

    /**
     * Remove the specified advertisement from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $advertisement = Advertisement::findOrFail($id);

        // Delete the image file if it exists
        if ($advertisement->image_path) {
            Storage::disk('public')->delete($advertisement->image_path);
        }

        $advertisement->delete();

        return redirect()->route('admin.advertisements.index')
            ->with('success', 'تبلیغ با موفقیت حذف شد.');
    }

    /**
     * Toggle the active status of an advertisement.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function toggleActive($id)
    {
        $advertisement = Advertisement::findOrFail($id);
        $advertisement->is_active = ! $advertisement->is_active;
        $advertisement->save();

        return redirect()->route('admin.advertisements.index')
            ->with('success', 'وضعیت تبلیغ با موفقیت تغییر کرد.');
    }

    /**
     * Get all available ad positions for dropdown.
     *
     * @return array
     */
    private function getAvailablePositions()
    {
        return [
            'text_ticker' => 'نوار متنی متحرک بالای صفحه',
            'homepage_hero' => 'هدر صفحه اصلی (بنر بزرگ بالایی)',
            'homepage_sidebar' => 'سایدبار صفحه اصلی',
            'homepage_featured' => 'محتوای ویژه صفحه اصلی',
            'homepage_middle' => 'میانه صفحه اصلی',
            'homepage_bottom' => 'پایین صفحه اصلی',
            'popup' => 'پاپ آپ',
            'category_page' => 'صفحه دسته بندی',
            'location_page' => 'صفحه مکان',
            'sidebar_top' => 'بالای سایدبار',
            'sidebar_middle' => 'میانه سایدبار',
            'sidebar_bottom' => 'پایین سایدبار',
            'footer' => 'فوتر سایت',
        ];
    }

    /**
     * Get all available ad types for dropdown.
     *
     * @return array
     */
    private function getAvailableAdTypes()
    {
        return [
            'banner' => 'بنر تصویری',
            'html' => 'محتوای HTML',
            'text' => 'متن تبلیغاتی',
            'popup' => 'پاپ آپ',
            'video' => 'ویدیو',
            'slider' => 'اسلایدر',
            'featured' => 'محتوای ویژه',
        ];
    }
}
