<?php

namespace App\Http\Controllers;

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

class TikTokShopsManagementController extends Controller
{
    /**
     * Display a listing of TikTok Shops
     */
    public function index()
    {
        // Only admins can manage TikTok Shops
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Only administrators can manage TikTok Shops.');
        }

        $shops = TikTokShop::withCount(['users', 'transactions'])
            ->orderBy('is_active', 'desc')
            ->orderBy('name')
            ->get();

        return view('tiktok-shops-management.index', compact('shops'));
    }

    /**
     * Show the form for creating a new TikTok Shop
     */
    public function create()
    {
        // Only admins can manage TikTok Shops
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Only administrators can manage TikTok Shops.');
        }

        return view('tiktok-shops-management.create');
    }

    /**
     * Store a newly created TikTok Shop
     */
    public function store(Request $request)
    {
        // Only admins can manage TikTok Shops
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Only administrators can manage TikTok Shops.');
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:tiktok_shops,name',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'manager_ids' => 'nullable|array',
            'manager_ids.*' => 'exists:users,id',
        ]);

        $shop = TikTokShop::create([
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'is_active' => $validated['is_active'] ?? true,
        ]);

        // Assign managers to this shop
        if (!empty($validated['manager_ids'])) {
            $shop->users()->sync($validated['manager_ids']);
        }

        return redirect()->route('tiktok-shops-management.index')
            ->with('success', 'TikTok Shop "' . $shop->name . '" created successfully!');
    }

    /**
     * Show the form for editing a TikTok Shop
     */
    public function edit($id)
    {
        // Only admins can manage TikTok Shops
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Only administrators can manage TikTok Shops.');
        }

        $shop = TikTokShop::with('users')->findOrFail($id);

        return view('tiktok-shops-management.edit', compact('shop'));
    }

    /**
     * Update the specified TikTok Shop
     */
    public function update(Request $request, $id)
    {
        // Only admins can manage TikTok Shops
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Only administrators can manage TikTok Shops.');
        }

        $shop = TikTokShop::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:tiktok_shops,name,' . $id,
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'manager_ids' => 'nullable|array',
            'manager_ids.*' => 'exists:users,id',
        ]);

        $shop->update($validated);

        // Sync manager assignments
        $shop->users()->sync($validated['manager_ids'] ?? []);

        return redirect()->route('tiktok-shops-management.index')
            ->with('success', 'TikTok Shop "' . $shop->name . '" updated successfully!');
    }

    /**
     * Remove the specified TikTok Shop
     */
    public function destroy($id)
    {
        // Only admins can manage TikTok Shops
        if (!auth()->user()->isAdmin()) {
            abort(403, 'Only administrators can manage TikTok Shops.');
        }

        $shop = TikTokShop::findOrFail($id);
        $shopName = $shop->name;

        // Check if shop has transactions
        if ($shop->transactions()->exists() || $shop->adsTransactions()->exists()) {
            return back()->with('error', 'Cannot delete "' . $shopName . '" because it has associated transactions. Consider deactivating it instead.');
        }

        $shop->delete();

        return redirect()->route('tiktok-shops-management.index')
            ->with('success', 'TikTok Shop "' . $shopName . '" deleted successfully!');
    }
}
