<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;

class BrandController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $brands = Brand::latest()->paginate(15);
        return view('dashboard.brands', compact('brands'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:brands,name'],
            'mobile_number' => ['nullable', 'string', 'max:20'],
            'domain' => ['nullable', 'string', 'max:255'],
            'whatsapp_number' => ['nullable', 'string', 'max:20'],
            'support_mail' => ['nullable', 'email', 'max:255'],
            'fees_type' => ['required', 'boolean'],
            'fees' => ['required', 'numeric'],
            'status' => ['required', 'boolean'],
            'brand_logo' => ['nullable', 'image', 'mimes:jpg,jpeg,png', 'max:2048'],
        ]);

        $data = [
            'user_id' => Auth::id(),
            'name' => $request->name,
            'brand_key' => Str::random(32),
            'mobile_number' => $request->mobile_number,
            'domain' => $request->domain,
            'whatsapp_number' => $request->whatsapp_number,
            'support_mail' => $request->support_mail,
            'fees_type' => $request->fees_type,
            'fees' => $request->fees,
            'status' => $request->status,
        ];

        if ($request->hasFile('brand_logo')) {
            $file = $request->file('brand_logo');
            $filename = time() . '_' . Str::slug($request->name) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/brands'), $filename);
            $data['brand_logo'] = 'uploads/brands/' . $filename;
        }

        $brand = Brand::create($data);

        if ($request->ajax() || $request->wantsJson()) {
            return response()->json(['message' => 'Brand created successfully.', 'brand' => $brand]);
        }
        return back()->with('success', 'Brand created successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Brand $brand)
    {
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json($brand->toArray());
        }
        // Fallback for non-ajax, though our setup is ajax-based
        return view('dashboard.brands.edit', compact('brand'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Brand $brand)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:brands,name,' . $brand->id],
            'mobile_number' => ['nullable', 'string', 'max:20'],
            'domain' => ['nullable', 'string', 'max:255'],
            'whatsapp_number' => ['nullable', 'string', 'max:20'],
            'support_mail' => ['nullable', 'email', 'max:255'],
            'fees_type' => ['required', 'boolean'],
            'fees' => ['required', 'numeric'],
            'status' => ['required', 'boolean'],
            'brand_logo' => ['nullable', 'image', 'mimes:jpg,jpeg,png', 'max:2048'],
        ]);

        $data = $request->except('brand_logo');

        if ($request->hasFile('brand_logo')) {
            // Delete old logo if it exists
            if ($brand->brand_logo && file_exists(public_path($brand->brand_logo))) {
                unlink(public_path($brand->brand_logo));
            }

            $file = $request->file('brand_logo');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/brands'), $filename);
            $data['brand_logo'] = 'uploads/brands/' . $filename;
        }

        $brand->update($data);
        if ($request->ajax() || $request->wantsJson()) {
            return response()->json(['message' => 'Brand updated successfully.', 'brand' => $brand]);
        }

        return back()->with('success', 'Brand updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Brand $brand)
    {
        $brand->delete();
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json(['message' => 'Brand deleted successfully.']);
        }
        return back()->with('success', 'Brand deleted successfully.');
    }

    /**
     * Change the status of the specified resource.
     */
    public function changeStatus(Request $request)
    {
        $request->validate([
            'id' => ['required', 'exists:brands,id'],
            'status' => ['required', 'boolean'],
        ]);

        $brand = Brand::findOrFail($request->id);
        $brand->update(['status' => $request->status]);

        if ($request->ajax() || $request->wantsJson()) {
            $statusText = $request->status ? 'Active' : 'Inactive';
            return response()->json(['message' => "Brand status changed to {$statusText}."]);
        }
        return back()->with('success', 'Brand status changed successfully.');
    }

    /**
     * Reset the API key for the specified resource.
     */
    public function resetKey(Request $request, Brand $brand)
    {
        $newKey = Str::random(32);
        $brand->update(['brand_key' => $newKey]);
        if (request()->ajax() || request()->wantsJson()) {
            return response()->json(['message' => 'Brand API key reset successfully.', 'brand_key' => $newKey, 'brand_id' => $brand->id]);
        }
        return back()->with('success', 'Brand API key reset successfully.');
    }
}
