<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\BranchProductStock;
use App\Models\ConveyanceBill;
use App\Models\Product;
use App\Models\Purchase;
use App\Models\Sale;
use App\Support\SaleInvoiceMetrics;
use App\Support\AdminAudit;
use Illuminate\Http\Request;
class BranchController extends Controller
{
    public function index() {
        $branches = Branch::latest('id')->paginate(20);
        $products = Product::orderBy('product_name')->get();
        return view('admin.branches.index', compact('branches','products'));
    }
    public function store(Request $request) {
        $data = $request->validate([
            'name'=>'required|string|max:120','code'=>'required|string|max:40|unique:branches,code','type'=>'required|string|max:40',
            'address'=>'nullable|string|max:255','phone'=>'nullable|string|max:30','email'=>'nullable|email|max:150','manager_name'=>'nullable|string|max:100',
            'invoice_prefix'=>'nullable|string|max:20','status'=>'required|in:Active,Inactive','is_head_office'=>'nullable|boolean','is_central_warehouse'=>'nullable|boolean'
        ]);
        $branch = Branch::create($data + ['is_head_office'=>$request->boolean('is_head_office'),'is_central_warehouse'=>$request->boolean('is_central_warehouse')]);
        AdminAudit::log('Branch','Create',$branch->code,null,$branch->toArray());
        return back()->with('success','Branch created successfully.');
    }
    public function update(Request $request, Branch $branch) {
        $data = $request->validate([
            'name'=>'required|string|max:120','code'=>'required|string|max:40|unique:branches,code,'.$branch->id,'type'=>'required|string|max:40',
            'address'=>'nullable|string|max:255','phone'=>'nullable|string|max:30','email'=>'nullable|email|max:150','manager_name'=>'nullable|string|max:100',
            'invoice_prefix'=>'nullable|string|max:20','status'=>'required|in:Active,Inactive','is_head_office'=>'nullable|boolean','is_central_warehouse'=>'nullable|boolean'
        ]);
        $old = $branch->toArray();
        $branch->update($data + ['is_head_office'=>$request->boolean('is_head_office'),'is_central_warehouse'=>$request->boolean('is_central_warehouse')]);
        AdminAudit::log('Branch','Update',$branch->code,$old,$branch->fresh()->toArray());
        return back()->with('success','Branch updated successfully.');
    }
    public function destroy(Branch $branch) {
        AdminAudit::log('Branch','Delete',$branch->code,$branch->toArray(),null);
        $branch->delete();
        return back()->with('success','Branch deleted successfully.');
    }
    public function stocks(Request $request) {
        $branchId = $request->integer('branch_id');
        $branches = Branch::orderBy('name')->get();
        $products = Product::orderBy('product_name')->get();
        $stocks = BranchProductStock::with([])->when($branchId, fn($q)=>$q->where('branch_id',$branchId))->latest('id')->paginate(30)->withQueryString();
        return view('admin.branches.stocks', compact('stocks','branches','products','branchId'));
    }
    public function saveStock(Request $request) {
        $data = $request->validate([
            'branch_id'=>'required|exists:branches,id','product_id'=>'required|exists:products,id','stock_qty'=>'required|numeric','reorder_qty'=>'nullable|numeric',
            'selling_price'=>'nullable|numeric','wholesale_price'=>'nullable|numeric'
        ]);
        $stock = BranchProductStock::updateOrCreate(['branch_id'=>$data['branch_id'],'product_id'=>$data['product_id']], $data);
        AdminAudit::log('Branch Stock','Save',(string)$stock->id,null,$stock->toArray());
        return back()->with('success','Branch stock saved successfully.');
    }
    public function performance() {
        $branches = Branch::orderBy('name')->get()->map(function($branch){
            $branch->sales_total = SaleInvoiceMetrics::sumGrandTotal(Sale::where('branch_id', $branch->id));
            $branch->purchase_total = Purchase::where('branch_id',$branch->id)->sum('grand_total');
            $branch->expense_total = ConveyanceBill::where('branch_id',$branch->id)->sum('amount');
            $branch->net = $branch->sales_total - $branch->purchase_total - $branch->expense_total;
            return $branch;
        });
        return view('admin.branches.performance', compact('branches'));
    }
}
