<?php

namespace App\Http\Controllers;

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

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

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

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

        if ($courier) {
            $courier->update($validated);
        } else {
            $courier = Courier::create($validated);
        }

        return $this->index();
    }

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

        return $this->index();
    }
}
