<?php
namespace App\Models;

use App\Core\Model;

class ClientTransaction extends Model
{
    public function create(array $data): int
    {
        $pdo = self::getPDO();
        $pdo->beginTransaction();
        try {
            $transactionId = $this->insert('client_transactions', $data);
            $clientModel = new Client();
            if ($data['transaction_type'] === 'credit') {
                $clientModel->updateBalance($data['client_id'], $data['amount'], 'add');
            } else { // debit
                $clientModel->updateBalance($data['client_id'], $data['amount'], 'subtract');
            }
            $pdo->commit();
            return $transactionId;
        } catch (\Exception $e) {
            $pdo->rollBack();
            throw $e;
        }
    }

    public function getForClient(int $clientId): array
    {
        $stmt = $this->query(
            "SELECT * FROM client_transactions WHERE client_id = ? ORDER BY transaction_date DESC",
            [$clientId]
        );
        return $stmt->fetchAll();
    }
}