<?php
use App\Modules\Finance\Models\AccountPayable;
use App\Modules\Inventory\Models\GoodsReceiptItem;

$ap = AccountPayable::latest()->first();
if ($ap) {
    if (!$ap->total_amount || $ap->total_amount == 0) {
        $sum = GoodsReceiptItem::where('goods_receipt_id', $ap->source_document_id)->sum('total_amount');
        if ($sum == 0) {
            // fallback: check if unit_price * quantity_received works
            $items = GoodsReceiptItem::where('goods_receipt_id', $ap->source_document_id)->get();
            foreach($items as $item) {
                $sum += ($item->quantity_received * $item->unit_price);
            }
        }
        $ap->total_amount = $sum;
        $ap->save();
        echo "Fixed AP {$ap->document_number} total_amount to {$sum}\n";
    } else {
        echo "AP total_amount is already set: {$ap->total_amount}\n";
    }
} else {
    echo "No AP found\n";
}
