<?php

$SQL = SQuery::select( DB_TABLE_PREFIX . "_loans", "1 ORDER BY id DESC" );

$result = Uss::$global['mysqli']->query( $SQL );

$tablet = new DOMTablet( 'loans' );

$tablet->data( $result );

$tablet->columns([
    'user',
    'date',
    'amount',
    'loan_type' => 'type',
    'reason',
    'status',
    'action' => ''
]);

$tablet->wrap( 'container-fluid' );

$tablet->prepare(function($data) {

    $user = Udash::fetch_assoc( DB_TABLE_PREFIX . "_users", $data['userid'] );

    if( $user ) {

        $href = Bank::userURL( $user['usercode'] );

        $data['user'] = "<a href='{$href}'>{$user['email']}</a>";

    } else $data['user'] = "<i class='bi bi-question-circle'></i>";

    $color = Udash::get_color( $data['status'] );

    $data['status'] = "<span class='badge bg-{$color}'>{$data['status']}</span>";

    if( empty($data['reason']) ) {
        $data['reason'] = "<i class='bi bi-question-circle'></i>";
    } else {
        $data['reason'] = "
            <a href='javascript:void(0)' data-viewer='{$data['id']}'>View Reason</a>
            <div class='d-none' data-reason='{$data['id']}'>
                {$data['reason']}
            </div>
        ";
    };

    $options = Bank::array_to_options([
        'pending' => 'pending',
        'approved' => 'approved',
        'declined' => 'declined'
    ], null, false);

    $data['action'] = "
        <form method='POST' data-uss-confirm='Press \"OK\" to continue.'>
            <input type='hidden' name='id' value='{$data['id']}'>
            <button class='input-group-append btn btn-outline-success' name='status' value='approved' title='Approve'>
                <i class='bi bi-check-circle'></i>
            </button>
            <button class='input-group-append btn btn-outline-secondary' name='status' value='declined' title='Decline'>
                <i class='bi bi-hand-thumbs-down-fill'></i>
            </button>
            <button class='input-group-append btn btn-outline-danger' name='status' value='delete' title='Delete'>
                <i class='bi bi-trash3'></i>
            </button>
        </form>
    ";

    $data['amount'] = '$' . number_format( $data['amount'], 2 );

    return $data;

}, true);
