<?php

namespace App\Http\Controllers\Admin;

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

class AdvertisementController extends Controller
{
    public function index()
    {
        $ads = Advertisement::latest()->paginate(12);

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

    public function create()
    {
        return view('admin.ads.form', ['ad' => new Advertisement()]);
    }

    public function store(Request $request)
    {
        $data = $this->validateAd($request);
        $data['is_active'] = $request->boolean('is_active');
        $data['sort_order'] = (int) ($data['sort_order'] ?? 0);
        unset($data['image'], $data['video']);
        $this->applyMediaFiles($request, $data, null);
        Advertisement::create($data);

        return redirect()->route('admin.ads.index')->with('success', 'تم إضافة الإعلان');
    }

    public function edit($id)
    {
        $ad = Advertisement::findOrFail($id);

        return view('admin.ads.form', compact('ad'));
    }

    public function update(Request $request, $id)
    {
        $ad = Advertisement::findOrFail($id);
        $data = $this->validateAd($request);
        $data['is_active'] = $request->boolean('is_active');
        $data['sort_order'] = (int) ($data['sort_order'] ?? 0);
        unset($data['image'], $data['video']);
        $this->applyMediaFiles($request, $data, $ad);
        $ad->update($data);

        return redirect()->route('admin.ads.index')->with('success', 'تم تحديث الإعلان');
    }

    public function destroy($id)
    {
        $ad = Advertisement::findOrFail($id);
        if ($ad->image) {
            Storage::disk('public')->delete($ad->image);
        }
        if ($ad->video_path) {
            Storage::disk('public')->delete($ad->video_path);
        }
        $ad->delete();

        return back()->with('success', 'تم حذف الإعلان');
    }

    public function toggle($id)
    {
        $ad = Advertisement::findOrFail($id);
        $ad->update(['is_active' => ! $ad->is_active]);

        return back()->with('success', $ad->is_active ? 'تم تفعيل الإعلان' : 'تم إيقاف الإعلان');
    }

    private function validateAd(Request $request): array
    {
        return $request->validate([
            'title'        => 'required|string|max:200',
            'title_ar'     => 'nullable|string|max:200',
            'description'  => 'nullable|string',
            'image'        => 'nullable|file|mimes:jpeg,jpg,png,webp,gif|max:5120',
            'video'        => 'nullable|file|mimes:mp4,webm|max:30720',
            'link_url'     => 'nullable|url',
            'link_text'    => 'nullable|string|max:50',
            'display_mode' => 'required|in:slider,splash',
            'media_type'   => 'required|in:image,gif,video',
            'position'     => 'required|in:home_top,home_middle,search_results,doctor_profile',
            'target'       => 'required|in:all,patients,doctors',
            'starts_at'    => 'nullable|date',
            'ends_at'      => 'nullable|date|after_or_equal:starts_at',
            'sort_order'   => 'nullable|integer|min:0',
        ]);
    }

    /**
     * يملأ مسارات التخزين ويتحقق من وجود وسيط مناسب.
     */
    private function applyMediaFiles(Request $request, array &$data, ?Advertisement $existing): void
    {
        if (($data['media_type'] ?? '') === 'video') {
            if ($request->hasFile('video')) {
                if ($existing?->video_path) {
                    Storage::disk('public')->delete($existing->video_path);
                }
                $data['video_path'] = $request->file('video')->store('ads', 'public');
            } elseif ($existing?->video_path) {
                $data['video_path'] = $existing->video_path;
            } else {
                throw ValidationException::withMessages([
                    'video' => 'يرجى رفع ملف فيديو (MP4 أو WebM).',
                ]);
            }
            if ($existing?->image) {
                Storage::disk('public')->delete($existing->image);
            }
            $data['image'] = null;
        } else {
            if ($request->hasFile('image')) {
                if ($existing?->image) {
                    Storage::disk('public')->delete($existing->image);
                }
                $data['image'] = $request->file('image')->store('ads', 'public');
            } elseif ($existing?->image) {
                $data['image'] = $existing->image;
            } else {
                throw ValidationException::withMessages([
                    'image' => 'يرجى رفع صورة أو صورة متحركة (GIF).',
                ]);
            }
            if ($existing?->video_path) {
                Storage::disk('public')->delete($existing->video_path);
            }
            $data['video_path'] = null;
        }
    }
}
