diff --git a/source/packages/plg_system_mokosuiteauto/src/Helper/TradeInHelper.php b/source/packages/plg_system_mokosuiteauto/src/Helper/TradeInHelper.php new file mode 100644 index 0000000..e87d6aa --- /dev/null +++ b/source/packages/plg_system_mokosuiteauto/src/Helper/TradeInHelper.php @@ -0,0 +1,90 @@ +get(DatabaseInterface::class); + + $tradeIn = (object) [ + 'vin' => strtoupper($vin), + 'owner_contact_id' => $ownerContactId, + 'mileage' => max(0, $mileage), + 'vehicle_condition'=> $condition, + 'appraisal_value' => round($appraisalValue, 2), + 'status' => 'pending_review', + 'appraised_by' => (int) Factory::getApplication()->getIdentity()->id, + 'appraised_at' => Factory::getDate()->toSql(), + ]; + + $db->insertObject('#__mokosuiteauto_trade_ins', $tradeIn, 'id'); + + return (object) ['success' => true, 'trade_in_id' => (int) $tradeIn->id]; + } + + /** + * Calculate trade equity (trade value minus payoff). + */ + public static function calculateEquity(int $tradeInId): object + { + $db = Factory::getContainer()->get(DatabaseInterface::class); + + $db->setQuery($db->getQuery(true) + ->select('ti.appraisal_value, ti.payoff_amount') + ->from($db->quoteName('#__mokosuiteauto_trade_ins', 'ti')) + ->where('ti.id = ' . (int) $tradeInId)); + $ti = $db->loadObject(); + + if (!$ti) { + return (object) ['success' => false, 'error' => 'Trade-in not found']; + } + + $equity = (float) $ti->appraisal_value - (float) ($ti->payoff_amount ?? 0); + + return (object) [ + 'trade_in_id' => $tradeInId, + 'appraisal_value' => (float) $ti->appraisal_value, + 'payoff_amount' => (float) ($ti->payoff_amount ?? 0), + 'equity' => round($equity, 2), + 'is_negative' => $equity < 0, + ]; + } + + /** + * Get pending trade-in appraisals needing manager review. + */ + public static function getPendingReview(): array + { + $db = Factory::getContainer()->get(DatabaseInterface::class); + + $db->setQuery($db->getQuery(true) + ->select('ti.*, cd.name AS owner_name, cd.telephone') + ->from($db->quoteName('#__mokosuiteauto_trade_ins', 'ti')) + ->join('LEFT', $db->quoteName('#__contact_details', 'cd') . ' ON cd.id = ti.owner_contact_id') + ->where($db->quoteName('ti.status') . ' = ' . $db->quote('pending_review')) + ->order('ti.appraised_at ASC')); + + return $db->loadObjectList() ?: []; + } +}