<?php

namespace App\Http\Controllers;

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

class CustomerController extends Controller
{
    public function index()
    {
        $customers = Customer::latest()->paginate(15);

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

    public function create()
    {
        return view('customers.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'         => ['required', 'string', 'max:255'],
            'phone'        => ['nullable', 'string', 'max:50'],
            'email'        => ['nullable', 'email', 'max:255'],
            'address'      => ['nullable', 'string'],
            'credit_limit' => ['nullable', 'numeric', 'min:0'],
            'current_due'  => ['nullable', 'numeric', 'min:0'],
            'status'       => ['required', 'in:active,inactive'],
            'notes'        => ['nullable', 'string'],
        ]);

        $data['credit_limit'] = $data['credit_limit'] ?? 0;
        $data['current_due']  = $data['current_due'] ?? 0;

        Customer::create($data);

        return redirect()->route('customers.index')->with('success', __('Customer profile created successfully.'));
    }

    public function destroy(Customer $customer)
    {
        $customer->delete();

        return redirect()->route('customers.index')->with('success', __('Customer removed successfully.'));
    }
}
