<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Repair;
use App\Models\Sale;
use App\Models\SecondHandBuy;
use App\Models\Tool;
use Inertia\Inertia;

class AccountsController extends Controller
{
    public function index()
    {
        // Sales Profit
        $salesProfit = Sale::join('products', 'sales.product_id', '=', 'products.id')
            ->selectRaw('SUM((products.selling_price - products.cost_price) * sales.quantity) as profit')
            ->value('profit') ?? 0;

        // Repair Income
        $repairIncome = Repair::where('status', 'done')->sum('charge_amount');

        // Tool Rent Income
        $toolRentIncome = Tool::where('type', 'rent')->sum('price');

        // Total Income
        $totalIncome = $salesProfit + $repairIncome + $toolRentIncome;

        // Second Hand Expense
        $secondHandExpense = SecondHandBuy::sum('buy_price');

        // Tool Buy Expense
        $toolBuyExpense = Tool::where('type', 'buy')->sum('price');

        // Total Expense
        $totalExpense = $secondHandExpense + $toolBuyExpense;

        // Final Profit/Loss
        $finalProfit = $totalIncome - $totalExpense;

        return Inertia::render('Admin/Pages/Accounts/Index', [
            'accounts' => [
                'sales_profit' => (float) $salesProfit,
                'repair_income' => (float) $repairIncome,
                'tool_rent_income' => (float) $toolRentIncome,
                'second_hand_expense' => (float) $secondHandExpense,
                'total_income' => (float) $totalIncome,
                'total_expense' => (float) $totalExpense,
                'final_profit' => (float) $finalProfit,
            ],
        ]);
    }
}