<?php
/**
 * SeekQuarry/Yioop --
 * Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 * Copyright (C) 2009 - 2026  Chris Pollett chris@pollett.org
 *
 * LICENSE:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * END LICENSE
 *
 * @author Chris Pollett
 * @license https://www.gnu.org/licenses/ GPL3
 * @link https://www.seekquarry.com/
 * @copyright 2009 - 2026
 * @filesource
 */
namespace seekquarry\yioop\views\elements;

use seekquarry\yioop as B;
use seekquarry\yioop\configs as C;
use seekquarry\yioop\library as L;
use seekquarry\yioop\library\UrlParser;

/**
 * Element responsible for displaying Ad credits purchase form and
 * recent transaction table
 */
class ManagecreditsElement extends Element
{
    /**
     * Draws create advertisement form and existing campaigns
     * @param array $data containing field values that have already been
     *  been filled in, data about existing campaigns and the anti-CSRF attack token
     */
    public function render($data)
    {
        ?>
        <div class="current-activity">
        <h2><?=tl('managecredits_element_balance', $data['BALANCE']) ?></h2>
        <?php
            $data['TABLE_TITLE'] = tl('managecredits_element_transactions');
            $data['ACTIVITY'] = 'manageCredits';
            if (empty($data['FORM_TYPE'])) {
                $data['FORM_TYPE'] = "credit-form";
            }
            if (in_array($data['FORM_TYPE'], ['search'])) {
                $data['DISABLE_ADD_TOGGLE'] = true;
            }
            $data['VIEW'] = $this->view;
            $num_columns = 4;
        ?>
        <table class="admin-table">
            <tr><td class="no-border" colspan="<?=
                $num_columns ?>"><?php $this->view->helper(
                "pagingtable")->render($data); ?>
                <div id='admin-form-row' class='admin-form-row'><?php
                if ($data['FORM_TYPE'] == "search") {
                    $this->renderSearchForm($data);
                } else {
                    $this->renderCreditsForm($data);
                }?>
                </div>
                </td>
            </tr>
            <tr>
                <th><?= tl('managecredits_element_type')?>
                </th>
                <th><?= tl('managecredits_element_amount')?>
                </th>
                <th><?= tl('managecredits_element_date')?>
                </th>
                 <th><?= tl('managecredits_element_total')?>
                </th>
            </tr>
            <?php
            foreach ($data['TRANSACTIONS'] as $tr) {
                ?>
                <tr>
                <td><?=tl($tr['TYPE']) ?></td>
                <td><?=$tr['AMOUNT'] ?></td>
                <td><?=date("r", $tr['TIMESTAMP']) ?></td>
                <td><?=$tr['BALANCE'] ?></td>
                </tr>
                <?php
            }
            ?>
        </table>
        </div>
        <script>
        function switchTab(newtab, oldtab, oldtab2)
        {
            setDisplay(newtab, true);
            setDisplay(oldtab, false);
            setDisplay(oldtab2, false);
            ntab = elt(newtab + "item");
            if (ntab) {
                ntab.className = 'active';
            }
            otab = elt(oldtab + "item");
            if (otab) {
                otab.className = '';
            }
            otab2 = elt(oldtab2 + "item");
            if (otab2) {
                otab2.className = '';
            }
            function removeElementsAttributes(elt_attribute_map)
            {
                for (let elt_name in elt_attribute_map) {
                    let elt_obj = elt(elt_name);
                    if (elt_obj && elt_obj.hasAttribute(
                        elt_attribute_map[elt_name])) {
                        elt_obj.removeAttribute(elt_attribute_map[elt_name]);
                    }
                }
            }
            let remove_attibute_name = [];
            if (newtab == 'purchasecreditstab') {
                elt('manage').innerHTML =
                    '<?=tl('managecredits_element_purchase') ?>';
                elt('credits-option').value = 'purchaseCredits';
                elt('start-button-parent').style.display = 'none';
                elt('manage-parent').style.display = 'block';
                elt('purchase-card-number').setAttribute('<?=
                    C\CreditConfig::getAttribute('card-number','name')?>',
                    '<?= C\CreditConfig::getAttribute('card-number','value')
                    ?>');
                elt('purchase-cvc').setAttribute('<?=
                    C\CreditConfig::getAttribute('cvc','name')?>',
                    '<?= C\CreditConfig::getAttribute('cvc','value')?>');
                elt('purchase-exp-month').setAttribute('<?=
                    C\CreditConfig::getAttribute('exp-month','name')?>',
                    '<?= C\CreditConfig::getAttribute('exp-month','value')?>');
                elt('purchase-exp-year').setAttribute('<?=
                    C\CreditConfig::getAttribute('exp-year','name')?>',
                    '<?= C\CreditConfig::getAttribute('exp-year','value')?>');
                remove_attibute_names = {
                    'redeem-card-number' : '<?=
                        C\CreditConfig::getAttribute('card-number','name') ?>',
                    'redeem-cvc' : '<?=
                        C\CreditConfig::getAttribute('cvc','name') ?>',
                    'redeem-exp-month' : '<?=
                        C\CreditConfig::getAttribute('exp-month','name')?>',
                    'redeem-exp-year' : '<?=
                        C\CreditConfig::getAttribute('exp-year','name')?>'
                    };
                removeElementsAttributes(remove_attibute_names);
            } else if (newtab == 'redeemcreditstab') {
                elt('manage').innerHTML =
                    '<?=tl('managecredits_element_redeem') ?>';
                elt('credits-option').value = 'redeemCredits';
                elt('start-button-parent').style.display = 'none';
                elt('manage-parent').style.display = '<?=
                    $data['REDEEM_ENABLED'] &&
                    $data['BALANCE'] >= C\CreditConfig::MIN_REDEEMABLE_CREDITS ?
                    'block' : 'none' ?>';
                elt('redeem-card-number').setAttribute('<?=
                    C\CreditConfig::getAttribute('card-number','name')?>',
                    '<?= C\CreditConfig::getAttribute('card-number','value')
                    ?>');
                elt('redeem-cvc').setAttribute('<?=
                    C\CreditConfig::getAttribute('cvc','value')?>',
                    '<?=C\CreditConfig::getAttribute('cvc','value')?>');
                elt('redeem-exp-month').setAttribute('<?=
                    C\CreditConfig::getAttribute('exp-month','name')?>',
                    '<?= C\CreditConfig::getAttribute('exp-month','value')?>');
                elt('redeem-exp-year').setAttribute('<?=
                    C\CreditConfig::getAttribute('exp-year','name')?>',
                    '<?=C\CreditConfig::getAttribute('exp-year','value')?>');
                remove_attibute_names = {
                    'purchase-card-number' : '<?=
                        C\CreditConfig::getAttribute('card-number','name')?>',
                    'purchase-cvc' : '<?=
                        C\CreditConfig::getAttribute('cvc','name')?>',
                    'purchase-exp-month' : '<?=
                        C\CreditConfig::getAttribute('exp-month','name')?>',
                    'purchase-exp-year' : '<?=
                        C\CreditConfig::getAttribute('exp-year','name')?>'
                };
                removeElementsAttributes(remove_attibute_names);
            } else {
                elt('start-button').innerHTML =
                    '<?=tl('managecredits_element_start') ?>';
                elt('credits-option').value = 'manageCreditsAccount';
                elt('start-button-parent').style.display = '<?=
                    $data['CREDITS_SERVICE_ACC_REQS'] == true ?
                    'block' : 'none' ?>';
                elt('manage-parent').style.display = 'none';
            }
        }
        if (typeof yioop_post_scripts !== 'object') {
            yioop_post_scripts = {};
        }
        yioop_post_scripts['page-load'] = function() {
            switchTab('purchasecreditstab', 'redeemcreditstab',
                'managedetailstab');
        }
        </script>
        <?php
    }
    /**
     * Draws the form used to create or edit a keyword
     * advertisement
     * @param array $data containing field values that have already been
     *  been filled in and the anti-CSRF attack token
     */
    public function renderCreditsForm($data)
    { ?>
        <form id="credit-form" method="post" enctype="multipart/form-data">
        <ul class='tab-menu-list'>
        <li><script>
            document.write('<a href="javascript:switchTab(' +
                "'purchasecreditstab', 'redeemcreditstab', 'managedetailstab'"
                + ');"' + "id='purchasecreditstabitem'>" +
                '<?= tl('managecredits_element_purchase_credits')?></a>');
            </script>
            <noscript>
            <a href="#purchasecreditstab"
                id='purchasecreditstabitem'><?=
                tl('managecredits_element_purchase_credits')?></a>
            </noscript>
        </li>
        <li><script>
            document.write('<a href="javascript:switchTab(' +
                "'redeemcreditstab', 'purchasecreditstab', 'managedetailstab'"
                + ');" ' +"id='redeemcreditstabitem'>" +
                '<?= tl('managecredits_element_redeem_credits')?></a>');
            </script>
            <noscript>
            <a href="#redeemcreditstab" id="redeemcreditstabitem" ><?=
                tl('managecredits_element_redeem_credits')?></a>
            </noscript>
        </li>
        <li><script>
            document.write('<a href="javascript:switchTab(' +
                "'managedetailstab', 'purchasecreditstab', 'redeemcreditstab'"
                + ');" ' +"id='managedetailstabitem'>" +
                '<?= tl('managecredits_element_manage_details')?></a>');
            </script>
            <noscript>
            <a href="#managedetailstab" id='managedetailstabitem' ><?=
                tl('managecredits_element_manage_details')?></a>
            </noscript>
        </li>
        </ul>
        <div class='tab-menu-content'>
        <input type="hidden" name="c" value="admin" >
        <input type="hidden" name="<?=C\p('CSRF_TOKEN') ?>" value="<?=
            $data[C\p('CSRF_TOKEN')] ?>" >
        <input type="hidden" name="a" value="manageCredits" >
        <input type="hidden" id="credits-option" name="arg" value="">
        <input type="hidden" id="card-token" name="CARD_TOKEN" value="" >
        <?php
        $this->renderPurchaseCreditsTab($data) ?>
        <noscript>
        <div class="center slight-pad">
        <button class="button-box" type="submit"><?=
        tl('managecredits_element_purchase')?></button>
        </div>
        </noscript>
        <?php
        $this->renderRedeemCreditsTab($data) ?>
        <noscript>
        <div class="center slight-pad">
        <button class="button-box" type="submit"><?=
        tl('managecredits_element_redeem')?></button>
        </div>
        </noscript>
        <?php
        $this->renderManageDetailsTab($data) ?>
        <noscript>
        <div class="center slight-pad">
        <button class="button-box" type="submit"><?=
        tl('managecredits_element_start')?></button>
        </div>
        </noscript>
        <div id='manage-parent' class="center slight-pad">
            <button class="button-box" id="manage" type="submit">
            </button>
        </div>
        <div id='start-button-parent' class="center slight-pad">
            <button class="button-box" id="start-button" type="submit">
            </button>
        </div>
        </div>
        </form>
        <?php
        if (C\CreditConfig::isActive()) {
            $ad_script_found = false;
            for ($i = C\DATABASE_VERSION; $i >= C\MIN_AD_VERSION;$i--) {
                $get_submit_purchase_script = "FN" . md5(
                    UrlParser::getBaseDomain(C\p('NAME_SERVER')) .
                    $i . "getSubmitPurchaseScript");
                if (method_exists( C\NS_CONFIGS . "CreditConfig",
                    $get_submit_purchase_script)) {
                    $ad_script_found = true;
                    break;
                }
            }
            if ($ad_script_found) {
                $data['SCRIPT'] .=
                    e(C\CreditConfig::$get_submit_purchase_script());
            } else {?>
                <br><span class='red'><?=
                    tl('managecredits_element_script_failure') ;
                ?></span><?php
            }
        }
    }
    /**
    * Draws the form fields required to purchase credits
    * @param array $data containing field values that have already been
    * been filled in and the anti-CSRF attack token
    */
    public function renderPurchaseCreditsTab($data)
    { ?>
        <div id="purchasecreditstab">
        <h2><?= tl('managecredits_element_purchase_credits') ?>
        <?= $this->view->helper("helpbutton")->render(
            "Purchase Credits", $data[C\p('CSRF_TOKEN')]) ?></h2>
        <table class='name-table'>
        <tr><th class="table-label"><label for="num-credits"><?=
            tl('managecredit_element_num_credits') ?>:
        </label></th>
        <td>
        <?php
        $this->view->helper('options')->render('num-credits',
            'NUM_DOLLARS', $data["AMOUNTS"], 0);
        ?>
        </td>
        </tr>
        <tr><th class="table-label"><label for="purchase-card-number"><?=
            tl('managecredit_element_card_number') ?>:
        </label></th>
        <td>
        <input class="narrow-field" id="purchase-card-number"
            type="text" size="20" <?=
                C\CreditConfig::getAttribute('card-number','name')
                ?>="<?=
                C\CreditConfig::getAttribute('card-number','value')
                ?>" >
        </td></tr>
        <tr><th class="table-label"><label for="purchase-cvc"><?=
            tl('managecredit_element_cvc') ?>:
        </label></th>
        <td>
        <input class="narrow-field" id="purchase-cvc"
            type="text" size="4" <?=
                C\CreditConfig::getAttribute('cvc','name')?>="<?=
                C\CreditConfig::getAttribute('cvc','value') ?>" >
        </td></tr>
        <tr><th class="table-label"><label for="purchase-exp-month"><?=
            tl('managecredit_element_expiration') ?>:
        </label></th>
        <td>
        <?php
        $this->view->helper('options')->render('purchase-exp-month', '',
            $data['MONTHS'], 0, false, [
                C\CreditConfig::getAttribute('exp-month','name') =>
                C\CreditConfig::getAttribute('exp-month','value')]);
        ?> / <?php
        $this->view->helper('options')->render('purchase-exp-year', '',
            $data['YEARS'], 0, false, [
                C\CreditConfig::getAttribute('exp-year','name') =>
                C\CreditConfig::getAttribute('exp-year','value')]);
        ?>
        </td></tr>
        <tr>
        <td></td>
        <td><div class="narrow-field green tiny-font"><?=
        tl('managecredits_element_charge_warning')
        ?> <a target="_blank" rel="noopener" href="<?=B\wikiUrl(
            'ad_program_terms') ?>"><?=
        tl('managecredits_element_program_terms')
        ?></a>.</div></td>
        </tr>
        </table>
        </div> <?php
    }
    /**
    * Draws the form fields required to redeem credits
    *
    * @param array $data containing field values that have already been
    * been filled in and the anti-CSRF attack token
    */
    public function renderRedeemCreditsTab($data)
    { ?>
        <div id="redeemcreditstab">
        <h2><?= tl('managecredits_element_redeem_credits') ?>
        <?= $this->view->helper("helpbutton")->render(
            "Redeem Credits", $data[C\p('CSRF_TOKEN')]) ?></h2><?php
        if (!isset($data['USER']['AD_CREDITS_SERVICE_ACCOUNT'])) { ?>
            <span class='red'><?=
                tl('managecredits_element_account_setup') ?></span><?php
        } else if (!$data['REDEEM_ENABLED']) { ?>
            <span class='red'><?=
                tl('managecredits_element_account_incomplete') ?></span><?php
        } else if ($data['BALANCE'] < 500) { ?>
            <span class='red'><?=
                tl('managecredits_element_insufficient_balance') ?></span><?php
        } else { ?>
            <input type="hidden"  value="usd"
            <?= C\CreditConfig::getAttribute('currency','name') ?>
            ="<?=C\CreditConfig::getAttribute('currency','value') ?>">
            <table class='name-table'>
            <tr>
            <th class='table-label'>
            <label for="credits-amount"><?=
                tl('managecredit_element_num_credits')?>:</label></th>
            <td><?php
            $this->view->helper('options')->render('num-credits',
                'NUM_CREDITS', $data['USD_AMOUNT'], 0); ?>
            </td>
            </tr>
            <tr><th class="table-label"><label for="redeem-card-number"><?=
                tl('managecredit_element_debit_card_number') ?>:
            </label></th>
            <td>
            <input class="narrow-field" id="redeem-card-number"
                type="text" size="20" <?=
                C\CreditConfig::getAttribute('redeem-card-number','name')
                ?>="<?=
                C\CreditConfig::getAttribute('card-number','value')
                ?>" >
            </td></tr>
            <tr><th class="table-label"><label for="redeem-cvc"><?=
                tl('managecredit_element_cvc') ?>:</label></th>
            <td>
            <input class="narrow-field" id="redeem-cvc"
                type="text" size="4" <?=
                    C\CreditConfig::getAttribute('redeem-cvc','name')?>="<?=
                    C\CreditConfig::getAttribute('cvc','value') ?>" >
            </td></tr>
            <tr><th class="table-label"><label for="redeem-exp-month"><?=
                tl('managecredit_element_expiration') ?>:</label></th>
            <td>
            <?php
            $this->view->helper('options')->render('redeem-exp-month', '',
                $data['MONTHS'], 0, false, [
                    C\CreditConfig::getAttribute('exp-month','name') =>
                    C\CreditConfig::getAttribute('exp-month','value')]);
            ?> / <?php
            $this->view->helper('options')->render('redeem-exp-year', '',
                $data['YEARS'], 0, false, [
                    C\CreditConfig::getAttribute('exp-year','name') =>
                    C\CreditConfig::getAttribute('exp-year','value')]);
            ?>
            </td></tr>
            <tr>
            <td></td>
            <td><div class="narrow-field green tiny-font"><?=
            tl('managecredits_element_redeem_warning')
            ?> <a target="_blank" rel="noopener" href="<?=B\wikiUrl(
                'ad_program_terms') ?>"><?=
            tl('managecredits_element_program_terms')
            ?></a>.</div></td>
            </tr>
            </table><?php
        } ?>
        </div><?php
    }
    /**
     * Draws the form fields showing the payment agency service account
     * requirements status
     *
     * @param array $data containing field values that have already been
     * been filled in and the anti-CSRF attack token
     */
    public function renderManageDetailsTab($data)
    { ?>
        <div id="managedetailstab">
        <h2><?= tl('managecredits_element_manage_details') ?>
        <?= $this->view->helper("helpbutton")->render(
            "Manage Details", $data[C\p('CSRF_TOKEN')]) ?></h2><?php
        if (!isset($data['USER']['AD_CREDITS_SERVICE_ACCOUNT'])) { ?>
            <div class="red"><?=
                tl('managecredits_element_credit_service_account')?></div><?php
        }
        else if (!$data['CREDITS_SERVICE_ACC_REQS']) { ?>
            <div class="green"><?=
                tl('managecredits_element_details_complete')?></div><?php
        } else { ?>
            <div class="red"><?=
                tl('managecredits_element_details_due')?></div><?php
        } ?>
        </div><?php
    }
    /**
     * Draws the search for credit transactions forms
     *
     * @param array $data consists of values of locale fields set
     *     so far as well as values of the drops downs on the form
     */
    public function renderSearchForm($data)
    {
        $controller = "admin";
        $activity = "manageCredits";
        $view = $this->view;
        $title = tl('managecredits_element_search');
        $fields = [
            tl('managecredits_element_type') => ["type",
                $data['EQUAL_COMPARISON_TYPES']],
            tl('managecredits_element_amount') => ["amount",
                $data['BETWEEN_COMPARISON_TYPES']],
            tl('managecredits_element_date') => ["timestamp",
                $data['BETWEEN_COMPARISON_TYPES']]
        ];
        $dropdowns = [
            'amount' => "range",
            'type' => ['advertisement_init_ledger' =>
                tl('advertisement_init_ledger'),
                'advertisement_buy_credits' => tl('advertisement_buy_credits'),
                'advertisement_buy_ad' => tl('advertisement_buy_ad'),
                'social_component_join_group_fee' =>
                    tl('social_component_join_group_fee')],
            'timestamp' => "date"];
        $view->helper("searchform")->render($data, $controller, $activity,
            $view, $title, $fields, $dropdowns);
    }
}
