<?php

//=============================================================================//
//  Last Modfd	: 11-1-2005                                         
//  Script Name	: admin_currency.php               			    
//=============================================================================//

# Add provision to support multiple currencies
# sets a currency as default currency
# generates a relation between currencies based on this default currency

require_once("db_connect.php"); // Make sure you include a proper mysqli connection

$id   = isset($_GET['id']) ? trim($_GET['id']) : '';
$mode = isset($_GET['mode']) ? trim($_GET['mode']) : '';

#-------------------------------------------------------------------------------
# getting default currency
#-------------------------------------------------------------------------------

$dftsql = "SELECT * FROM partners_currency WHERE currency_code = ?";
$dftstmt = $mysqli->prepare($dftsql);
$dftstmt->bind_param("s", $default_currency_code);
$dftstmt->execute();
$dftret = $dftstmt->get_result();

if ($dftret && $dftret->num_rows > 0) {
    $dftrow  = $dftret->fetch_object();
    $dftcurr = trim(stripslashes($dftrow->currency_caption));
    $dftsym  = trim(stripslashes($dftrow->currency_symbol));
    $dftid   = trim(stripslashes($dftrow->currency_id));
    $dftcode = trim(stripslashes($dftrow->currency_code));
}
$dftstmt->close();

#-------------------------------------------------------------------------------
#  setting values according to $mode
#-------------------------------------------------------------------------------

if ($mode == "Delete") {
    // Check if the currency is used by any merchant
    $chkSql = "SELECT merchant_id FROM partners_merchant WHERE merchant_currency = ?";
    $chkStmt = $mysqli->prepare($chkSql);
    $chkStmt->bind_param("s", $id);
    $chkStmt->execute();
    $chkRet = $chkStmt->get_result();

    if ($chkRet->num_rows > 0) {
        $msg = 6;
    } else {
        // Proceed to delete
        $deleteSql = "DELETE FROM partners_currency WHERE currency_id = ?";
        $deleteStmt = $mysqli->prepare($deleteSql);
        $deleteStmt->bind_param("s", $id);
        if (!$deleteStmt->execute()) {
            die("You have an error while processing sql query.");
        }
        $deleteStmt->close();
        $msg = 5;
    }

    $chkStmt->close();
}

if ($mode == "Edit") {
    $capt = "Set New Currency Relation";

    // Retrieve currency values
    $editSql = "SELECT * FROM partners_currency WHERE currency_id = ?";
    $editStmt = $mysqli->prepare($editSql);
    $editStmt->bind_param("s", $id);
    $editStmt->execute();
    $edtRet = $editStmt->get_result();

    if ($edtRet->num_rows > 0) {
        $editRow = $edtRet->fetch_object();
        $currency_caption  = trim(stripslashes($editRow->currency_caption));
        $currency_symbol   = trim(stripslashes($editRow->currency_symbol));
        $currency_relation = trim(stripslashes($editRow->currency_relation));
    }

    $editStmt->close();
} else {
    $capt = "Set New Currency Relation";
    $mode = "Add";
}

#-------------------------------------------------------------------------------
#  getting existing currencies.
#-------------------------------------------------------------------------------

$sql = "SELECT * FROM partners_currency WHERE currency_code != ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $default_currency_code);
$stmt->execute();
$ret = $stmt->get_result();
$ret1 = $ret; // Used later in the form

# display messages
switch ($msg) {
    case 1:
        $ErrMsg = "Please Don't Leave Any Fields!!";
        break;
    case 2:
        $ErrMsg = "Sorry, this entry already exists!!";
        break;
    case 3:
        $ErrMsg = "New Currency has been added successfully!!";
        break;
    case 4:
        $ErrMsg = "Currency has been edited successfully!!";
        break;
    case 5:
        $ErrMsgd = "Currency has been deleted successfully!!";
        break;
    case 6:
        $ErrMsgd = "Sorry, this Currency is being used by a merchant!!";
        break;
    case 7:
        $ErrMsgd = "Default Currency has been changed!!";
        break;
    case 8:
        $ErrMsg = "Please enter Numeric Values as relation field!!";
        break;
    case 12:
        $ErrMsg = "Invalid Entry.  Action Failed";
        break;
}
?>

<br/>
<form name="currency" method="post" action="currency_validate.php?mode=<?=htmlspecialchars($mode)?>&amp;id=<?=htmlspecialchars($id)?>" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" border='0' class="tablebdr" width="90%">
    <tr>
        <td width="100%" class="tdhead" align="center" colspan="2"><b>Supported Currencies</b></td>
    </tr>
    <tr>
        <td width="100%" align="center" colspan="2">&nbsp;</td>
    </tr>
    <tr>
        <td width="50%" valign="top">
            <table width="98%" cellpadding="5" cellspacing="0" border='0' class="tablebdr" align="center">
                <tr><td class="tdhead" colspan="7" align="center"><b>Existing Currencies</b></td></tr>
                <tr><td class="textred" colspan="7" align="center"><?=$ErrMsgd?></td></tr>
                <tr><td class="textred" colspan="7" align="left"><b>Base Currency</b>: <b><?=htmlspecialchars($dftcurr)?> (<?=htmlspecialchars($dftsym)?>)&nbsp;<?=htmlspecialchars($dftcode)?></b></td></tr>

                <?php
                # display all currencies
                if ($ret && $ret->num_rows > 0) {
                    $i = 0;
                    while ($row = $ret->fetch_object()) {
                        $i++;

                        // Get relation for this currency
                        $newSql = "SELECT * FROM partners_currency_relation WHERE relation_currency_code = ? ORDER BY relation_date DESC LIMIT 1";
                        $newStmt = $mysqli->prepare($newSql);
                        $newStmt->bind_param("s", $row->currency_code);
                        $newStmt->execute();
                        $newRet = $newStmt->get_result();

                        $currency_relation = '';
                        $currency_symbol = $row->currency_symbol;
                        $can_not_delete = 0;

                        if ($newRet && $newRet->num_rows > 0) {
                            $newRow = $newRet->fetch_object();
                            $currency_relation = $newRow->relation_value;
                        }

                        // Check if this currency is used by any merchant
                        $sqlchk = "SELECT merchant_id FROM partners_merchant WHERE merchant_currency = ?";
                        $chkStmt = $mysqli->prepare($sqlchk);
                        $chkStmt->bind_param("s", $row->currency_caption);
                        $chkStmt->execute();
                        $reschk = $chkStmt->get_result();

                        if ($reschk && $reschk->num_rows > 0) {
                            $can_not_delete = 1;
                        }

                        $chkStmt->close();
                        $newStmt->close();
                        ?>
                        <tr>
                            <td width="50%" align="left"><b><?=$i?></b>.&nbsp;<?=htmlspecialchars(stripslashes($row->currency_caption))?></td>
                            <td width="37%" align="left"><b>1&nbsp;<?=htmlspecialchars($dftsym)?> = <?=htmlspecialchars($currency_relation)?> <?=htmlspecialchars($currency_symbol)?></b></td>
                            <td width="13%" align="left"><a href="#" onclick="javascript:delete_currency(<?=$can_not_delete?>,'<?=htmlspecialchars(stripslashes($row->currency_caption))?>')">Delete</a></td>
                        </tr>
								   <?php
        } // end of currency display loop
    } else {
?>
    <tr><td class="textred" colspan="7" align="center">Sorry, No Currency(s) Found</td></tr>
<?php
    }
?>
    <tr><td colspan="7" align="center">&nbsp;</td></tr>
    </table>
</td>

<td width="50%" valign="top">
    <table width="98%" cellpadding="5" cellspacing="0" border='0' class="tablebdr" align="center">
        <tr>
            <td width="100%" class="tdhead" align="center" colspan="3"><b><?=htmlspecialchars($capt)?></b></td>
        </tr>

        <?php
        $crnysql = "SELECT * FROM partners_currency WHERE currency_code != ?";
        $crnystmt = $mysqli->prepare($crnysql);
        $crnystmt->bind_param("s", $default_currency_code);
        $crnystmt->execute();
        $crnyret = $crnystmt->get_result();
        ?>

        <tr>
            <td width="100%" class="textred" align="left" colspan="3">All the * fields are mandatory</td>
        </tr>

        <tr>
            <td width="100%" class="textred" align="center" colspan="3"><?=htmlspecialchars($ErrMsg)?></td>
        </tr>

        <tr>
            <td width="40%" align="center">
                Currency&nbsp;<font color="#FF0000" size="1"><b>*</b></font>
            </td>
            <td width="35%" align="left">
                <select size="1" name="currency_caption">
                    <?php
                    if ($crnyret && $crnyret->num_rows > 0) {
                        while ($crnyrow = $crnyret->fetch_object()) {
                            $selected = ($crnyrow->currency_caption == $currency) ? "selected='selected'" : "";
                            ?>
                            <option value="<?=htmlspecialchars($crnyrow->currency_code)?>" <?=$selected?>><?=htmlspecialchars(trim(stripslashes($crnyrow->currency_caption)))?></option>
                            <?php
                        }
                    }
                    ?>
                </select>
            </td>
        </tr>

        <tr>
            <td width="40%" align="center">
                Set Relation&nbsp;<font color="#FF0000" size="1"><b>*</b></font>
                ( <b>1 (<?=htmlspecialchars($dftsym)?>)</b> )
            </td>
            <td width="35%" align="left">
                <input name="currency_relation" type="text" value="" />
            </td>
        </tr>

        <tr>
            <td colspan="3" align="center">
                <input type="submit" value="Submit" />
                <input type="reset" value="Reset" />
            </td>
        </tr>
    </table>
</td>
</tr>
<tr><td colspan="3" align="center" height="10"></td></tr>
</table>
</form>
	
<?php
$crnysql = "SELECT * FROM partners_currency WHERE currency_code != ?";
$crnystmt = $mysqli->prepare($crnysql);
$crnystmt->bind_param("s", $default_currency_code);
$crnystmt->execute();
$crnyret = $crnystmt->get_result();

$note           = $_REQUEST['note'] ?? '';
$note1          = $_REQUEST['note1'] ?? '';
$txt_caption    = trim(stripslashes($_REQUEST['txt_caption'] ?? ''));
$txt_code       = trim(stripslashes($_REQUEST['txt_code'] ?? ''));
$txt_symbol     = trim(stripslashes($_REQUEST['txt_symbol'] ?? ''));
$txt_relation   = trim(stripslashes($_REQUEST['txt_relation'] ?? ''));

$var_cur = ($const_getCurrencyRatesFromXe == "1") ? "checked='checked'" : "";
?>  

<form name="frm_base" method="post">
    <table align="center" cellpadding="0" cellspacing="0" width="60%">
        <tr>
            <td height="50">
                <b><font size="2" color="#0000FF">Get Currency Rates From XE.com</font></b>&nbsp;&nbsp;&nbsp;&nbsp;
                <input type="checkbox" name="chk_currency" <?=$var_cur?> onClick="ChangeRateSystem('rate')" />
            </td>
        </tr>
    </table>

    <table cellpadding="0" cellspacing="0" border='0' class="tablebdr" width="60%">
        <tr>
            <td width="100%" class="tdhead" align="center" colspan="2"><b>Base Currency</b></td>
        </tr>

        <?php if ($note1) { ?>
        <tr>
            <td colspan="2" align="center">
                <font color="#FF0000" size="1"><b><?=htmlspecialchars($note1)?></b></font>
            </td>
        </tr>
        <?php } ?>

        <tr>
            <td width="100%" align="center" colspan="2">&nbsp;</td>
        </tr>

        <tr>
            <td align="right" width="50%">Select Base Currency&nbsp;&nbsp;&nbsp;&nbsp;</td>
            <td align="left" width="50%" height="30">
                <select name="basecurrency">
                    <?php
                    if ($crnyret && $crnyret->num_rows > 0) {
                        while ($crnyrow = $crnyret->fetch_object()) {
                            $selected = ($crnyrow->currency_caption == $currency) ? "selected='selected'" : "";
                            ?>
                            <option value="<?=htmlspecialchars($crnyrow->currency_code)?>" <?=$selected?>>
                                <?=htmlspecialchars(trim(stripslashes($crnyrow->currency_caption)))?>
                            </option>
                            <?php
                        }
                    }
                    ?>
                </select>
            </td>
        </tr>

        <tr>
            <td align="center" colspan="2" height="30" valign="bottom">
                <input type="button" name="base" value="Change" onClick="Currency_Process('change');" />
            </td>
        </tr>

        <tr>
            <td height="30" width="100%" align="center" colspan="2">&nbsp;</td>
        </tr>
    </table>

    <br />

    <table width="60%" cellpadding="0" cellspacing="0" class="tablebdr">
        <tr>
            <td width="100%" class="tdhead" align="center" colspan="3"><b>Add New Currency</b></td>
        </tr>

		<?php if ($note) { ?>
    <tr>
        <td colspan="3" align="center">
            <font color="#FF0000" size="1"><b><?=htmlspecialchars($note)?></b></font>
        </td>
    </tr>
<?php } ?>

<tr>
    <td width="100%" align="center" colspan="3">&nbsp;</td>
</tr>

<tr>
    <td align="right" width="45%" height="30">
        Currency Caption&nbsp;<font color="#FF0000" size="1"><b>*</b></font>
    </td>
    <td width="10%" height="30"></td>
    <td width="45%" height="30">
        <input type="text" name="txt_caption" value="<?=htmlspecialchars($txt_caption)?>" />
    </td>
</tr>

<tr>
    <td align="right" width="45%" height="30">
        Currency Code&nbsp;<font color="#FF0000" size="1"><b>*</b></font>
    </td>
    <td width="10%" height="30"></td>
    <td width="45%" height="30">
        <input type="text" name="txt_code" value="<?=htmlspecialchars($txt_code)?>" />
    </td>
</tr>

<tr>
    <td align="right" width="45%" height="30">
        Currency Symbol&nbsp;<font color="#FF0000" size="1"><b>*</b></font>
    </td>
    <td width="10%" height="30"></td>
    <td width="45%" height="30">
        <input type="text" name="txt_symbol" value="<?=htmlspecialchars($txt_symbol)?>" />
    </td>
</tr>

<tr>
    <td align="right" width="45%" height="30">
        Currency Relation&nbsp;<font color="#FF0000" size="1"><b>*</b></font>
    </td>
    <td width="10%" height="30"></td>
    <td width="45%" height="30">
        <input type="text" name="txt_relation" value="<?=htmlspecialchars($txt_relation)?>" />
    </td>
</tr>

<tr>
    <td align="center" colspan="3" height="30">
        <input type="button" name="Add" value="Add Currency" onClick="Currency_Process('add');" />
        &nbsp;&nbsp;&nbsp;
        <input type="reset" name="cancel" value="Cancel" />
    </td>
</tr>
</table>
</form>
<br />

<script language="javascript" type="text/javascript">
    function ChangeRateSystem(mode) {
        if (!confirm('Are you sure to toggle the status of the integration with XE.com')) {
            document.frm_base.chk_currency.checked = !document.frm_base.chk_currency.checked;
            return false;
        }
        document.frm_base.action = 'currency_process.php?mode=' + mode;
        document.frm_base.submit();
    }

    function delete_currency(delete_currency, caption) {
        if (delete_currency) {
            alert("You can't delete this currency since there are some merchants using it");
        } else {
            window.location = "currency_validate.php?caption=" + encodeURIComponent(caption) + "&mode=delete";
        }
    }

    function Currency_Process(mode) {
        if (mode === 'add') {
            if (document.frm_base.txt_caption.value.trim() === '') {
                alert('Please enter the Currency Caption');
                document.frm_base.txt_caption.focus();
                return false;
            }
            if (document.frm_base.txt_code.value.trim() === '') {
                alert('Please enter the Currency Code');
                document.frm_base.txt_code.focus();
                return false;
            }
            if (document.frm_base.txt_symbol.value.trim() === '') {
                alert('Please enter the Currency Symbol');
                document.frm_base.txt_symbol.focus();
                return false;
            }
            if (document.frm_base.txt_relation.value.trim() === '') {
                alert('Please enter the Currency Relation with Base Currency');
                document.frm_base.txt_relation.focus();
                return false;
            }
        }

        if (mode === 'change') {
            if (!confirm('On changing the base currency the values of all the transactions will be replaced with the value of the Base Currency. Do you wish to continue?')) {
                return false;
            }
        }

        document.frm_base.action = 'currency_process.php?mode=' + mode;
        document.frm_base.submit();
    }
</script>