<?php

namespace App\Http\Controllers\Admin;

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

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $shopId = $this->shopId();
        $q = $request->get('q');

        $customers = Customer::where('shop_id', $shopId)
            ->when($q, function ($query) use ($q) {
                $query->where(function ($sub) use ($q) {
                    $sub->where('name', 'like', "%{$q}%")
                        ->orWhere('phone', 'like', "%{$q}%");
                });
            })
            ->withCount('orders')
            ->withSum('orders', 'total_amount')
            ->latest()
            ->paginate(15)
            ->withQueryString();

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

    public function create()
    {
        $user = Auth::guard('admin')->user();
        abort_unless($user->hasPermission('customers.create'), 403);

        return view('admin.customers.create');
    }

    public function store(Request $request)
    {
        $user = Auth::guard('admin')->user();
        abort_unless($user->hasPermission('customers.create'), 403);

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
        ]);

        $customer = Customer::create([
            'shop_id' => $this->shopId(),
            'name' => $data['name'],
            'phone' => $data['phone'] ?? null,
            'address' => $data['address'] ?? null,
        ]);

        return redirect()->route('customers.index')->with('status', "Customer \"{$customer->name}\" added.");
    }

    public function edit(Customer $customer)
    {
        abort_unless($customer->shop_id === $this->shopId(), 403);

        $user = Auth::guard('admin')->user();
        abort_unless($user->hasPermission('customers.edit'), 403);

        return view('admin.customers.edit', compact('customer'));
    }

    public function update(Request $request, Customer $customer)
    {
        abort_unless($customer->shop_id === $this->shopId(), 403);

        $user = Auth::guard('admin')->user();
        abort_unless($user->hasPermission('customers.edit'), 403);

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
        ]);

        $customer->update($data);

        return redirect()->route('customers.index')->with('status', "Customer \"{$customer->name}\" updated.");
    }

    public function destroy(Customer $customer)
    {
        abort_unless($customer->shop_id === $this->shopId(), 403);

        $user = Auth::guard('admin')->user();
        abort_unless($user->hasPermission('customers.delete'), 403);

        if ($customer->orders()->exists()) {
            return back()->withErrors(['delete' => "Can't delete \"{$customer->name}\" — they have existing orders."]);
        }

        $customer->delete();

        return redirect()->route('customers.index')->with('status', "Customer \"{$customer->name}\" deleted.");
    }

    protected function shopId(): int
    {
        return Auth::guard('admin')->user()->shop_id;
    }
}
