<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Customer;   // -> table: rm_customers
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class CustomersController extends Controller
{
    /** List + search */
    public function index(Request $request)
    {
        $q = trim((string) $request->get('q'));

        $customers = Customer::query()
            ->when($q, function ($w) use ($q) {
                $like = "%{$q}%";
                $w->where(function ($s) use ($like) {
                    $s->where('name', 'like', $like)
                      ->orWhere('company_name', 'like', $like)
                      ->orWhere('personal_phone', 'like', $like)
                      ->orWhere('email', 'like', $like)
                      ->orWhere('address', 'like', $like);
                });
            })
            ->orderByDesc('id')
            ->paginate(25)
            ->withQueryString();

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

    /** Create form */
    public function create()
    {
        // If you have $areas / $partyTypes etc, pass them here.
        return view('party.customers.create');
    }

    /** Store */
    public function store(Request $request)
    {
        $v = $request->validate([
            'name'             => ['required','string','max:191'],
            'personal_phone'   => ['required','string','max:191'],
            'email'            => ['nullable','email','max:191'],
            'address'          => ['nullable','string','max:191'],
            'company_name'     => ['nullable','string','max:191'],
            'bussiness_phone'  => ['nullable','integer'],
            'customerId'       => ['nullable','string','max:191'],
            'account_id'       => ['nullable','integer'],
            'opening_balance'  => ['nullable','numeric'],
            'current_balance'  => ['nullable','numeric'],
            'due_limit'        => ['nullable','numeric'],
            'remarks'          => ['nullable','string','max:191'],
            'customer_type'    => ['nullable','in:0,1'],
            'executive_name'   => ['nullable','string','max:191'],
            'area_id'          => ['nullable','integer'],
            'employee_id'      => ['nullable','integer'],
            'discount_type'    => ['nullable','in:1,2'],
            'discount'         => ['nullable','numeric'],
            'assume_rate'      => ['nullable','numeric'],
            'party_type_id'    => ['nullable','integer'],
            'status'           => ['nullable','in:0,1'],
            'image'            => ['nullable','image','max:1024'],
        ]);

        // Sane defaults to avoid NULL constraint surprises
        $data = array_merge([
            'opening_balance' => 0,
            'current_balance' => 0,
            'due_limit'       => 0,
            'status'          => 1,
        ], $v);

        // Optional image upload → store path in "image" column
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('customers', 'public');
        }

        // FK (NOT NULL)
        $data['created_by'] = Auth::id();
        $data['updated_by'] = Auth::id();

        DB::transaction(fn() => Customer::create($data));

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

    /** Edit form (optional) */
    public function edit(Customer $customer)
    {
        return view('party.customers.create', compact('customer')); // reuse the same form
    }

    /** Update (optional) */
    public function update(Request $request, Customer $customer)
    {
        $v = $request->validate([
            'name'             => ['required','string','max:191'],
            'personal_phone'   => ['required','string','max:191'],
            'email'            => ['nullable','email','max:191'],
            'address'          => ['nullable','string','max:191'],
            'company_name'     => ['nullable','string','max:191'],
            'bussiness_phone'  => ['nullable','integer'],
            'customerId'       => ['nullable','string','max:191'],
            'account_id'       => ['nullable','integer'],
            'opening_balance'  => ['nullable','numeric'],
            'current_balance'  => ['nullable','numeric'],
            'due_limit'        => ['nullable','numeric'],
            'remarks'          => ['nullable','string','max:191'],
            'customer_type'    => ['nullable','in:0,1'],
            'executive_name'   => ['nullable','string','max:191'],
            'area_id'          => ['nullable','integer'],
            'employee_id'      => ['nullable','integer'],
            'discount_type'    => ['nullable','in:1,2'],
            'discount'         => ['nullable','numeric'],
            'assume_rate'      => ['nullable','numeric'],
            'party_type_id'    => ['nullable','integer'],
            'status'           => ['nullable','in:0,1'],
            'image'            => ['nullable','image','max:1024'],
        ]);

        $data = $v;

        if ($request->hasFile('image')) {
            if ($customer->image) {
                Storage::disk('public')->delete($customer->image);
            }
            $data['image'] = $request->file('image')->store('customers', 'public');
        }

        $data['updated_by'] = Auth::id();

        DB::transaction(fn() => $customer->update($data));

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

    /** Delete (optional) */
    public function destroy(Customer $customer)
    {
        DB::transaction(function () use ($customer) {
            if ($customer->image) {
                Storage::disk('public')->delete($customer->image);
            }
            $customer->delete();
        });

        return back()->with('success', 'Customer deleted successfully.');
    }
}


