<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Sale;
use App\Support\SaleInvoiceMetrics;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CustomerController extends Controller
{
    public function index(Request $request): View
    {
        $query = Customer::query();
        if ($request->filled('q')) {
            $q = trim((string) $request->input('q'));
            $query->where(function ($sub) use ($q) {
                $sub->where('name', 'like', "%{$q}%")
                    ->orWhere('phone_number', 'like', "%{$q}%")
                    ->orWhere('email', 'like', "%{$q}%")
                    ->orWhere('address', 'like', "%{$q}%");
            });
        }
        $customers = $query->latest('id')->paginate(20)->withQueryString();
        return view('admin.customers.index', compact('customers'));
    }

    public function create(): View
    {
        return view('admin.customers.form', ['customer' => new Customer()]);
    }

    public function store(Request $request): RedirectResponse
    {
        Customer::create($this->validated($request));
        return redirect()->route('admin.customers.index')->with('success', 'Customer created successfully.');
    }

    public function edit(Customer $customer): View
    {
        return view('admin.customers.form', compact('customer'));
    }

    public function update(Request $request, Customer $customer): RedirectResponse
    {
        $customer->update($this->validated($request, $customer->id));
        return redirect()->route('admin.customers.index')->with('success', 'Customer updated successfully.');
    }

    public function destroy(Customer $customer): RedirectResponse
    {
        $customer->delete();
        return back()->with('success', 'Customer deleted successfully.');
    }

    public function show(Customer $customer): View
    {
        $salesQuery = Sale::query()->where(function ($query) use ($customer) {
            $query->where('customer_id', $customer->id);

            if (!empty($customer->phone_number)) {
                $query->orWhere('customer_phone', $customer->phone_number);
            }
        });

        $sales = (clone $salesQuery)->latest('id')->paginate(20);
        $totalPurchase = SaleInvoiceMetrics::sumGrandTotal(clone $salesQuery);
        $totalDue = SaleInvoiceMetrics::sumDue(clone $salesQuery);

        return view('admin.customers.show', compact('customer','sales','totalPurchase','totalDue'));
    }

    private function validated(Request $request, ?int $id = null): array
    {
        return $request->validate([
            'name' => ['required','string','max:150'],
            'phone_number' => ['nullable','string','max:30'],
            'email' => ['nullable','email','max:150'],
            'address' => ['nullable','string','max:255'],
            'customer_group' => ['required','in:Retail,Wholesale,VIP'],
            'opening_balance' => ['nullable','numeric','min:0'],
            'points' => ['nullable','integer','min:0'],
            'wallet_balance' => ['nullable','numeric','min:0'],
            'membership_no' => ['nullable','string','max:60'],
            'membership_tier' => ['nullable','string','max:40'],
            'special_discount_percent' => ['nullable','numeric','min:0'],
            'sms_opt_in' => ['nullable'],
            'status' => ['required','in:Active,Inactive'],
        ]);
    }
}
