<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Shop;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class ShopController extends Controller
{
    public function index()
    {
        $shops = Shop::latest()->paginate(10);

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

    public function create()
    {
        return view('admin.shops.form', ['shop' => new Shop()]);
    }

    public function store(Request $request)
    {
        $data = $this->validated($request);
        $ownerData = $this->validatedOwner($request);

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('shops', 'public');
        }

        DB::transaction(function () use ($data, $ownerData) {
            $shop = Shop::create($data);

            User::create([
                'name' => $ownerData['owner_login_name'],
                'phone' => $ownerData['owner_phone'],
                'password' => Hash::make($ownerData['owner_password']),
                'type_id' => 2,
                'shop_id' => $shop->id,
                'is_active' => true,
            ]);
        });

        return redirect()->route('superadmin.shops.index')->with('status', 'Shop and owner account created successfully.');
    }

    public function edit(Shop $shop)
    {
        return view('admin.shops.form', compact('shop'));
    }

    public function update(Request $request, Shop $shop)
    {
        $data = $this->validated($request, $shop->id);

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('shops', 'public');
        }

        $shop->update($data);

        return redirect()->route('superadmin.shops.index')->with('status', 'Shop updated successfully.');
    }

    public function destroy(Shop $shop)
    {
        $shop->delete();

        return back()->with('status', 'Shop removed.');
    }

    protected function validated(Request $request, $ignoreId = null): array
    {
        return $request->validate([
            'name' => 'required|string|max:255',
            'owner_name' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'gst_number' => 'nullable|string|max:20',
            'logo' => 'nullable|image|max:2048',
            'is_active' => 'boolean',
        ]);
    }

    protected function validatedOwner(Request $request): array
    {
        return $request->validate([
            'owner_login_name' => 'required|string|max:255',
            'owner_phone' => 'required|string|max:20|unique:users,phone',
            'owner_password' => 'required|min:6',
        ]);
    }
    public function resetOwnerCredentials(Request $request, Shop $shop)
{
    $owner = $shop->users()->where('type_id', 2)->first();

    if (! $owner) {
        return back()->withErrors(['owner_phone' => 'No owner account found for this shop.']);
    }

    $data = $request->validate([
        'owner_phone' => 'required|string|max:20|unique:users,phone,' . $owner->id,
        'owner_password' => 'nullable|min:6',
    ]);

    $owner->update([
        'phone' => $data['owner_phone'],
        ...(filled($data['owner_password'] ?? null) ? ['password' => \Illuminate\Support\Facades\Hash::make($data['owner_password'])] : []),
    ]);

    return back()->with('status', "Login details updated for {$shop->name}'s owner.");
}
}
