<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Customer;
use App\Models\InstallmentPayment;
use App\Models\InstallmentSale;
use App\Support\AdminAudit;
use Illuminate\Http\Request;
class InstallmentController extends Controller
{
    public function index() {
        $plans = InstallmentSale::latest('id')->paginate(20);
        $customers = Customer::orderBy('name')->get();
        $branches = Branch::orderBy('name')->get();
        return view('admin.installments.index', compact('plans','customers','branches'));
    }
    public function store(Request $request) {
        $data = $request->validate([
            'sale_invoice_no'=>'nullable|string|max:60','customer_id'=>'required|exists:customers,id','branch_id'=>'nullable|exists:branches,id',
            'principal_amount'=>'required|numeric|min:0','down_payment'=>'nullable|numeric|min:0','installment_amount'=>'required|numeric|min:0','installment_count'=>'required|integer|min:1',
            'interval_days'=>'required|integer|min:1','start_date'=>'required|date','penalty_per_late_day'=>'nullable|numeric|min:0','status'=>'required|in:Active,Closed,Defaulted','notes'=>'nullable|string'
        ]);
        $plan = InstallmentSale::create($data);
        for ($i=0; $i < (int)$data['installment_count']; $i++) {
            InstallmentPayment::create([
                'installment_sale_id'=>$plan->id,
                'scheduled_date'=>\Carbon\Carbon::parse($data['start_date'])->addDays($i*(int)$data['interval_days'])->toDateString(),
                'amount_due'=>$data['installment_amount'],'amount_paid'=>0,'late_fee'=>0,'status'=>'Pending'
            ]);
        }
        AdminAudit::log('EMI','Create',(string)$plan->id,null,$plan->toArray());
        return back()->with('success','Installment plan created successfully.');
    }
    public function collect(Request $request, InstallmentSale $plan) {
        $data = $request->validate(['payment_id'=>'required|exists:installment_payments,id','amount_paid'=>'required|numeric|min:0','paid_date'=>'required|date','late_fee'=>'nullable|numeric|min:0','notes'=>'nullable|string']);
        $payment = InstallmentPayment::where('installment_sale_id',$plan->id)->findOrFail($data['payment_id']);
        $payment->update(['amount_paid'=>$data['amount_paid'],'paid_date'=>$data['paid_date'],'late_fee'=>$data['late_fee'] ?? 0,'status'=>'Paid','notes'=>$data['notes'] ?? null]);
        if (!InstallmentPayment::where('installment_sale_id',$plan->id)->where('status','!=','Paid')->exists()) $plan->update(['status'=>'Closed']);
        AdminAudit::log('EMI','Collect',(string)$plan->id,null,$payment->toArray());
        return back()->with('success','Installment payment collected successfully.');
    }
    public function defaulters() {
        $today = now()->toDateString();
        $payments = InstallmentPayment::where('scheduled_date','<',$today)->where('status','!=','Paid')->latest('scheduled_date')->paginate(30);
        return view('admin.installments.defaulters', compact('payments'));
    }
}
