<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Dealer;
use App\Models\DealerLedger;
use App\Support\AdminAudit;
use Illuminate\Http\Request;
class DealerController extends Controller
{
    public function index() {
        $dealers = Dealer::latest('id')->paginate(20);
        return view('admin.dealers.index', compact('dealers'));
    }
    public function store(Request $request) {
        $data = $request->validate([
            'name'=>'required|string|max:120','code'=>'required|string|max:40|unique:dealers,code','phone'=>'nullable|string|max:30','email'=>'nullable|email|max:150',
            'address'=>'nullable|string|max:255','area_name'=>'nullable|string|max:80','dealer_type'=>'required|in:Dealer,Reseller,Wholesale','commission_percent'=>'nullable|numeric|min:0',
            'credit_limit'=>'nullable|numeric|min:0','status'=>'required|in:Active,Inactive','rating'=>'nullable|integer|min:1|max:5','notes'=>'nullable|string'
        ]);
        $dealer = Dealer::create($data);
        AdminAudit::log('Dealer','Create',$dealer->code,null,$dealer->toArray());
        return back()->with('success','Dealer account created successfully.');
    }
    public function update(Request $request, Dealer $dealer) {
        $data = $request->validate([
            'name'=>'required|string|max:120','code'=>'required|string|max:40|unique:dealers,code,'.$dealer->id,'phone'=>'nullable|string|max:30','email'=>'nullable|email|max:150',
            'address'=>'nullable|string|max:255','area_name'=>'nullable|string|max:80','dealer_type'=>'required|in:Dealer,Reseller,Wholesale','commission_percent'=>'nullable|numeric|min:0',
            'credit_limit'=>'nullable|numeric|min:0','status'=>'required|in:Active,Inactive','rating'=>'nullable|integer|min:1|max:5','notes'=>'nullable|string'
        ]);
        $old = $dealer->toArray(); $dealer->update($data);
        AdminAudit::log('Dealer','Update',$dealer->code,$old,$dealer->fresh()->toArray());
        return back()->with('success','Dealer updated successfully.');
    }
    public function ledger(Dealer $dealer, Request $request) {
        if ($request->isMethod('post')) {
            $data = $request->validate(['txn_date'=>'required|date','reference_no'=>'nullable|string|max:60','type'=>'required|string|max:60','debit'=>'nullable|numeric|min:0','credit'=>'nullable|numeric|min:0','notes'=>'nullable|string']);
            DealerLedger::create($data + ['dealer_id'=>$dealer->id]);
            return back()->with('success','Dealer ledger entry saved successfully.');
        }
        $entries = DealerLedger::where('dealer_id',$dealer->id)->latest('id')->get();
        $balance = $entries->sum('debit') - $entries->sum('credit');
        return view('admin.dealers.ledger', compact('dealer','entries','balance'));
    }
}
