<?php

namespace Modules\Bms\Http\Controllers;

use App\Product;
use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsProductMedia;
use Modules\Bms\Services\Contracts\MediaServiceContract;

/**
 * Marketing media manager for a core ERP product (image / video / 360°), keyed
 * by product_id. Opened from the product create/edit page's injected BMS
 * section; the gallery is reused by every package/add-on referencing the product.
 */
class ProductMediaController extends BmsBaseController
{
    public function media($id)
    {
        $this->guard('bms.packages.manage');
        $product = Product::where('business_id', $this->businessId())->findOrFail($id);
        $items = BmsProductMedia::where('product_id', $product->id)->orderBy('sort_order')->get();
        $media = app(MediaServiceContract::class);

        return view('bms::products.media', compact('product', 'items', 'media'));
    }

    public function storeMedia(Request $request, $id)
    {
        $this->guard('bms.packages.manage');
        $request->validate([
            'file'  => 'required_without:url|file|max:51200', // 50 MB
            'url'   => 'nullable|url',
            'type'  => 'required|in:image,video,360',
            'title' => 'nullable|string|max:191',
        ]);

        $product = Product::where('business_id', $this->businessId())->findOrFail($id);

        $row = [
            'business_id' => $this->businessId(),
            'product_id'  => $product->id,
            'type'        => $request->input('type'),
            'title'       => $request->input('title'),
            'is_cover'    => ! BmsProductMedia::where('product_id', $product->id)->where('is_cover', true)->exists(),
            'sort_order'  => (int) BmsProductMedia::where('product_id', $product->id)->max('sort_order') + 1,
        ];

        if ($request->hasFile('file')) {
            $stored = app(MediaServiceContract::class)->store($this->businessId(), "products/{$product->id}", $request->file('file'));
            $row['disk'] = $stored['disk'];
            $row['path'] = $stored['path'];
            $row['url'] = $stored['url'];
        } else {
            $row['url'] = $request->input('url'); // external/CDN URL (e.g. a hosted 360)
        }

        BmsProductMedia::create($row);

        return redirect()->route('bms.products.media', $product->id)
            ->with('status', ['success' => 1, 'msg' => __('bms::lang.added_success')]);
    }

    public function destroyMedia($id, $mediaId)
    {
        $this->guard('bms.packages.manage');
        $item = BmsProductMedia::where('business_id', $this->businessId())
            ->where('product_id', $id)->findOrFail($mediaId);
        if ($item->disk && $item->path) {
            app(MediaServiceContract::class)->delete($item->disk, $item->path);
        }
        $item->delete();

        return redirect()->route('bms.products.media', $id)
            ->with('status', ['success' => 1, 'msg' => __('bms::lang.deleted_success')]);
    }
}
