<?php

namespace App\Filament\ReportFuncs;

use App\Models\Item;
use App\Models\CurrencyExchange;
use App\Models\Expense;

class ProfitReport
{


  public static function generate(string $fromDate, string $toDate): array
  {
    $totalSalesAfn = 0;
    $totalSalesUsd = 0;
    $totalCostAfn = 0;
    $totalCostUsd = 0;
    $grossProfitAfn = 0;
    $grossProfitUsd = 0;
    $testProfitAfn = 0;
    $testProfitUsd = 0;
    $exchangeProfitAfn = 0;
    $exchangeProfitUsd = 0;

    foreach (Item::all() as $item) {
      $sales = $item->trades()
        ->where('type', 'sale')
        ->whereDate('created_at', '>=', $fromDate)
        ->whereDate('created_at', '<=', $toDate)
        ->get();

      $tests = $item->tests()
        ->whereDate('created_at', '>=', $fromDate)
        ->whereDate('created_at', '<=', $toDate)
        ->get();

      foreach ($sales as $s) {
        $saleValue = $s->weight_gram * $s->price_per_gram;
        $costValue = $s->weight_gram * 10;
        if ($s->currency === 'AFN') {
          $totalSalesAfn += $saleValue;
          $totalCostAfn += $costValue;
          $grossProfitAfn += $saleValue - $costValue;
        } elseif ($s->currency === 'USD') {
          $totalSalesUsd += $saleValue;
          $totalCostUsd += $costValue;
          $grossProfitUsd += $saleValue - $costValue;
        }
      }

      foreach ($tests as $t) {
        $testProfit = $t->weight_gram * $t->rate_per_gram;
        if ($t->currency === 'AFN') {
          $testProfitAfn += $testProfit;
        } elseif ($t->currency === 'USD') {
          $testProfitUsd += $testProfit;
        }
      }
    }

    CurrencyExchange::whereDate('created_at', '>=', $fromDate)
      ->whereDate('created_at', '<=', $toDate)
      ->get()
      ->each(function ($r) use (&$exchangeProfitAfn, &$exchangeProfitUsd) {
        if ($r->profit_currency === 'AFN') {
          $exchangeProfitAfn += $r->profit_amount;
        } elseif ($r->profit_currency === 'USD') {
          $exchangeProfitUsd += $r->profit_amount;
        }
      });

    $expenseRows = [];
    $totalExpenseAfn = 0;
    $totalExpenseUsd = 0;

    $expenseAccounts = \App\Models\Account::where('type', 'expense')->pluck('id', 'name');
    foreach ($expenseAccounts as $accountName => $accountId) {
      $expenses = Expense::where('exp_account_id', $accountId)
        ->whereDate('date', '>=', $fromDate)
        ->whereDate('date', '<=', $toDate)
        ->get()
        ->groupBy('currency');

      foreach ($expenses as $currency => $items) {
        $sum = $items->sum('amount');
        if ($currency === 'AFN') {
          $totalExpenseAfn += $sum;
        } elseif ($currency === 'USD') {
          $totalExpenseUsd += $sum;
        }
        $expenseRows[] = [
          'desc' => $accountName,
          'afn' => $currency === 'AFN' ? round($sum, 2) : 0,
          'usd' => $currency === 'USD' ? round($sum, 2) : 0,
        ];
      }
    }

    $netProfitAfn = $grossProfitAfn + $testProfitAfn + $exchangeProfitAfn - $totalExpenseAfn;
    $netProfitUsd = $grossProfitUsd + $testProfitUsd + $exchangeProfitUsd - $totalExpenseUsd;

    return [
      'results' => [
        'gross_profit' => collect([
          ['desc' => 'Total Sales', 'afn' => round($totalSalesAfn, 2), 'usd' => round($totalSalesUsd, 2)],
          ['desc' => 'Total Cost of Sale', 'afn' => round($totalCostAfn, 2), 'usd' => round($totalCostUsd, 2)],
          ['desc' => 'Sales Gross Profit', 'afn' => round($grossProfitAfn, 2), 'usd' => round($grossProfitUsd, 2)],
          ['desc' => 'Total Test Profits', 'afn' => round($testProfitAfn, 2), 'usd' => round($testProfitUsd, 2)],
          ['desc' => 'Total Exchange Profits', 'afn' => round($exchangeProfitAfn, 2), 'usd' => round($exchangeProfitUsd, 2)],
        ]),
        'expenses' => collect($expenseRows),
        'net_profit' => collect([
          ['desc' => 'Net Profit', 'afn' => round($netProfitAfn, 2), 'usd' => round($netProfitUsd, 2)],
        ]),
      ],
    ];
  }
}
