<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreMediaRequest;
use App\Models\Media;
use Inertia\Inertia;

class MediaController extends Controller
{
    public function index()
    {
        $medias = Media::query()->where('user_id',auth()->id())->get();
        return Inertia::render('Links/Index', [
            'medias' => $medias
        ]);
    }

    public function create()
    {
        return Inertia::render('Links/Create');
    }

    public function store(StoreMediaRequest $request)
    {
        if ($request->name == 'whatsapp') {
            $url = 'https://wa.me/' . (int)$request->url;
        } else if ($request->name == 'telegram') {
            $url = 'https://t.me/' . $request->url;
        } else if ($request->name == 'messenger') {
            $url = 'http://m.me/' . $request->url;
        } else {
            $url = $request->url;
        }

        Media::create([
            'name' => $request->name,
            'title' => $request->title,
            'url' => $url,
            'user_id' => auth()->id(),
        ]);

        return to_route('links')->with('success','Link added successfully!');
    }


    public function update(StoreMediaRequest $request, $id)
    {
        if ($request->name == 'whatsapp') {
            $url = 'https://wa.me/' . (int)$request->url;
        } else if ($request->name == 'whatsapp Business') {
            $url = 'https://wa.me/' . (int)$request->url;
        } else if ($request->name == 'telegram') {
            $url = 'https://t.me/' . $request->url;
        } else if ($request->name == 'messenger') {
            $url = 'http://m.me/' . $request->url;
        } else {
            $url = $request->url;
        }

        $media = Media::findOrFail($id);

        $media->update([
            'name' => $request->name,
            'title' => $request->title,
            'url' => $url,
            'user_id' => auth()->id(),
        ]);

        return to_route('links')->with('success','Information updated successfully.');
    }


    public function destroye($id)
    {
        $media = Media::findOrFail($id);
        $media->delete();
        return to_route('links')->with('success','Link removed successfully!');;
    }
}
