<?php

namespace App\Http\Controllers;

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

class CustomerController extends Controller
{
    /**
     * Get list of all customers.
     */
    public function index()
    {
        $customers = Customer::orderBy('name', 'asc')->get();
        return response()->json($customers);
    }

    /**
     * Store a new customer or update an existing one.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:20', 'regex:/^(\+62|62|0)8[1-9][0-9]{7,11}$/'],
            'address' => ['nullable', 'string', 'max:500'],
            'latitude' => ['nullable', 'numeric', 'between:-90,90'],
            'longitude' => ['nullable', 'numeric', 'between:-180,180'],
        ], [
            'phone.regex' => 'Format nomor HP tidak valid (contoh: 081234567890 atau +6281234567890).',
        ]);

        // Find customer with matching name (case-insensitive) to update, or create a new one
        $customer = Customer::whereRaw('LOWER(name) = ?', [strtolower($validated['name'])])->first();

        if ($customer) {
            $customer->update($validated);
        } else {
            $customer = Customer::create($validated);
        }

        return $this->index();
    }

    /**
     * Delete a customer.
     */
    public function destroy($id)
    {
        $customer = Customer::findOrFail($id);
        $customer->delete();

        return $this->index();
    }

    /**
     * Halaman riwayat order seluruh pesanan dari satu pelanggan.
     */
    public function history($id)
    {
        $customer = Customer::with(['orders.status', 'orders.courier'])
            ->findOrFail($id);

        $orders = $customer->orders()
            ->with(['status', 'courier'])
            ->orderBy('created_at', 'desc')
            ->get();

        $stats = [
            'total' => $orders->count(),
            'total_ongkir' => (int) $orders->sum('shipping_cost'),
            'avg_jarak' => $orders->count() ? round($orders->avg('distance'), 1) : 0,
            'last' => $orders->first()?->created_at?->format('d/m/Y H:i'),
        ];

        return view('admin.customer-history', compact('customer', 'orders', 'stats'));
    }
}
