<?php
namespace App\Models;

use App\Core\Model;

class CurrencyHolding extends Model
{
    public function getForDate($currencyId, $date)
    {
        $stmt = $this->query(
            "SELECT * FROM currency_holdings WHERE currency_id = ? AND holding_date = ?",
            [$currencyId, $date]
        );
        return $stmt->fetch();
    }

    public function updateAfterTrade($currencyId, $tradeType, $amount, $rate)
    {
        $today = date('Y-m-d');
        $existing = $this->getForDate($currencyId, $today);

        if (!$existing) {
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            $prev = $this->getForDate($currencyId, $yesterday);
            $opening = $prev['closing_balance'] ?? 0;
            $avgCost = $prev['average_cost'] ?? 0;

            $data = [
                'currency_id' => $currencyId,
                'holding_date' => $today,
                'opening_balance' => $opening,
                'total_bought' => 0,
                'total_sold' => 0,
                'closing_balance' => $opening,
                'average_cost' => $avgCost
            ];
            $this->insert('currency_holdings', $data);
            $existing = $data;
        }

        if ($tradeType === 'buy') {
            $newBought = $existing['total_bought'] + $amount;
            $newClosing = $existing['closing_balance'] + $amount;
            $oldValue = $existing['closing_balance'] * $existing['average_cost'];
            $newValue = $oldValue + ($amount * $rate);
            $newAvgCost = ($newClosing != 0) ? $newValue / $newClosing : 0;
        } else { // sell
            $newSold = $existing['total_sold'] + $amount;
            $newClosing = $existing['closing_balance'] - $amount;
            $newAvgCost = $existing['average_cost'];
        }

        $updateData = [
            'total_bought' => $newBought ?? $existing['total_bought'],
            'total_sold'   => $newSold ?? $existing['total_sold'],
            'closing_balance' => $newClosing,
            'average_cost' => $newAvgCost
        ];
        $this->update('currency_holdings', $updateData, "currency_id = :cid AND holding_date = :date", [
            ':cid' => $currencyId,
            ':date' => $today
        ]);
    }

    public function getCurrentPositions()
    {
        $stmt = $this->query("
            SELECT c.code, ch.closing_balance, ch.average_cost 
            FROM currency_holdings ch
            JOIN currencies c ON ch.currency_id = c.id
            WHERE ch.holding_date = CURDATE()
        ");
        return $stmt->fetchAll();
    }
}