<?php

Uss::route( $statementRoute . "/\d{4}-\w+", function() {

    Events::addListener('@head:after', function() {
        echo "
            <style>
                @media print {
                    .btn {
                        display: none;
                    }
                }
            </style>
        ";
    }, 'statement-print');

    Uss::view(function() {

        $datetime = new DateTime( Uss::query(3) );

        $bankNumber = Uss::$global['usermeta']->get('bank:number', Uss::$global['user']['id']);

        $date = $datetime->format('Y-m');

        $SQL = "
            SELECT 
                %{prefix}_transfers.tx_date,
                %{prefix}_transfers.tx_reason,
                %{prefix}_transfer_meta.tx_type,
                SUM(CASE
                    WHEN %{prefix}_transfer_meta.tx_type = 'debit'
                    THEN %{prefix}_transfer_meta.amount
                    ELSE 0
                END) AS money_out,
                SUM(CASE
                    WHEN %{prefix}_transfer_meta.tx_type = 'credit'
                    THEN %{prefix}_transfer_meta.amount
                    ELSE 0
                END) AS money_in
            FROM
                %{prefix}_transfers
            INNER JOIN
                %{prefix}_transfer_meta
            ON
                %{prefix}_transfers.tx_ref = %{prefix}_transfer_meta.tx_ref
            WHERE 
                %{prefix}_transfer_meta.account_number = '{$bankNumber}'
                AND %{prefix}_transfers.tx_date LIKE '{$date}%'
            GROUP BY DATE(%{prefix}_transfers.tx_date)
        ";

        $SQL = Core::replace_var($SQL, ['prefix' => DB_TABLE_PREFIX]);

        $result = Uss::$global['mysqli']->query( $SQL );
        $resultArray = Udash::mysqli_to_array( $result );
        
        $money = [
            'in' => [
                'amount' => array_sum( array_column( $resultArray, "money_in" ) )
            ],
            'out' => [
                'amount' => array_sum( array_column( $resultArray, "money_out" ) )
            ]
        ];
        
        $converter = new Converter( Uss::$global['user']['id'], 'to' );

        $money['in']['conversion'] = $converter->from('USD')->amount( $money['in']['amount'] )->convert();
        $money['in']['value'] = $money['in']['conversion']->symbol . number_format($money['in']['conversion']->amount, 2);

        $money['out']['conversion'] = $converter->from('USD')->amount( $money['out']['amount'] )->convert();
        $money['out']['value'] = $money['out']['conversion']->symbol . number_format($money['out']['conversion']->amount, 2);

        $final = $money['in']['conversion']->amount - $money['out']['conversion']->amount;
        $money['recurring'] = $money['in']['conversion']->symbol . number_format($final, 2);

        require_once ACC_DIR . "/templates/statement-card.php";

    }, ['viewport']);

});