<?php
#-------------------------------------------------------------------------------
# Admin Panel Link Report
# Gets date range, merchant id and corresponding programs
# Finds Transactions happened for these programs through specific ad link
#-------------------------------------------------------------------------------

require_once 'db_connection.php'; // assumes you have a file for mysqli connection like $mysqli

// Sanitize inputs
$MERCHANTID = isset($_GET['merchants']) ? intval($_GET['merchants']) : 0;
$txtfrom    = isset($_GET['txtfrom']) ? trim($_GET['txtfrom']) : '';
$txtto      = isset($_GET['txtto']) ? trim($_GET['txtto']) : '';
$sub        = isset($_GET['sub']) ? trim($_GET['sub']) : '';
$msg        = isset($_GET['msg']) ? trim($_GET['msg']) : '';
$LINKS      = isset($_SESSION['LINKS']) ? trim($_SESSION['LINKS']) : '';
$i          = isset($_GET['i']) ? trim($_GET['i']) : '';
$programs   = isset($_GET['programs']) ? trim($_GET['programs']) : '';

$Link = explode("^", $LINKS);
$TOTALREC = count($Link) - 1;

// Create report heading
if (!empty($txtto) && !empty($txtfrom)) {
    $heading = "$txtfrom - $txtto";
}

// Fetch all merchants
$sqlMer = "SELECT * FROM partners_merchant";
$retMer = $mysqli->query($sqlMer);
$retMer1 = $mysqli->query($sqlMer);

// Get merchant count
$sqlMerc = "SELECT MAX(merchant_id) AS countMer FROM partners_merchant";
$retMerc = $mysqli->query($sqlMerc);
$rowMerc = $retMerc->fetch_object();
$countMer = $rowMerc->countMer;

// JavaScript REGION array for merchant-program mapping
echo "<script language='javascript' type='text/javascript'>";

$code = "var REGION = new Array ( ";
$code .= str_repeat(" new Array(),", $countMer + 1); // empty arrays for each merchant
$fbody = " AddPgms(0,'All Programs`~`AllPgms'); ";

while ($rowMer1 = $retMer1->fetch_object()) {
    $merchantId = (int)$rowMer1->merchant_id;

    // Fetch programs for each merchant
    $sqlfld = "SELECT * FROM partners_program WHERE program_merchantid = $merchantId";
    $resfld = $mysqli->query($sqlfld);

    $fbody .= "AddPgms($merchantId,'All Programs`~`All'); ";

    if ($resfld && $resfld->num_rows > 0) {
        while ($rowfld = $resfld->fetch_object()) {
            $fld = addslashes($rowfld->program_url) . "`~`" . $rowfld->program_id;
            $count = $rowfld->program_merchantid;
            $fbody .= " AddPgms($count,'$fld'); ";
        }
    }
}

// Finalize JavaScript output
$code = rtrim($code, ",");
$code .= " ); ";

$code .= "function LoadPrgms() { ";
$code .= $fbody;
$code .= " UpdateCombos($MERCHANTID); ";

if ($programs) {
    $escapedProgram = htmlspecialchars($programs, ENT_QUOTES);
    $code .= " document.trans.programs.value = '$escapedProgram';";
}

$code .= "}";

echo $code;
echo "</script>";
?>

<script type="text/javascript">
    function AddPgms(intRegion, strCity) {
        REGION[intRegion][REGION[intRegion].length++] = strCity;
    }

    function UpdateCombos(intREGION) {
        document.trans.programs.length = REGION[intREGION].length;

        for (let x = 0; x < REGION[intREGION].length; x++) {
            let test = REGION[intREGION][x].split("`~`");
            let showString;

            if (test[1] !== "All" && test[1] !== "AllPgms") {
                showString = "ID:" + test[1] + "..." + test[0];
            } else {
                showString = test[0];
            }

            document.trans.programs.options[x] = new Option(showString, test[1]);
        }
    }

    function from_date() {
        gfPop.fStartPop(document.trans.txtfrom, Date);
    }

    function to_date() {
        gfPop.fStartPop(document.trans.txtto, Date);
    }
</script>

<iframe width="168" height="175" name="gToday:normal:agenda.js" id="gToday:normal:agenda.js"
    src="../cal/ipopeng.htm" scrolling="no" frameborder="0"
    style="border:2px ridge; visibility:visible; z-index:999; position:absolute; left:-500px; top:0px;">
</iframe>

<br/>

<form name="trans" method="post" action="link_process.php">
    <table border="0" cellpadding="0" cellspacing="0" class="tablebdr" width="50%" align="center">
        <tr>
            <td height="19" class="tdhead" colspan="2" align="center">
                <b>Statistics For Custom Period</b>
            </td>
        </tr>
        <tr>
            <td height="19" colspan="2" align="center" class="textred">
                <?= htmlspecialchars($msg ?? '', ENT_QUOTES) ?>
            </td>
        </tr>
        <tr>
            <td height="19" colspan="2" align="center">
                <b>For Period</b>
            </td>
        </tr>
        <tr>
            <td width="40%" height="24" align="center">&nbsp; From</td>
            <td width="60%" height="24" align="left">
                <input type="text" name="txtfrom" size="18" value="<?= htmlspecialchars($txtfrom ?? '', ENT_QUOTES) ?>"
                    onfocus="from_date(); return false;" />
            </td>
        </tr>
        <tr>
            <td height="7" colspan="2"></td>
        </tr>
        <tr>
            <td width="40%" height="24" align="center">&nbsp;&nbsp;&nbsp; To</td>
            <td width="60%" height="24" align="left">
                <input type="text" name="txtto" size="18" value="<?= htmlspecialchars($txtto ?? '', ENT_QUOTES) ?>"
                    onfocus="to_date(); return false;" />
            </td>
        </tr>
        <tr>
            <td width="35%" height="23">&nbsp;</td>
        </tr>
        <tr>
            <td height="20" class="tdhead" colspan="2" align="center">
                <b>Search Merchants</b>
            </td>
        </tr>
        <tr>
            <td width="35%" height="13">&nbsp;</td>
        </tr>
        <tr>
            <td height="25" colspan="2" align="center">
                Merchant:
                <select name="merchants" onchange="UpdateCombos(this.value);">
                    <option value="0">Select Merchants</option>
                    <?php
                    // Already fetched in Part 1 with mysqli
                    if (isset($retMer) && $retMer instanceof mysqli_result) {
                        while ($rowMer = $retMer->fetch_object()) {
                            $selected = ($MERCHANTID == $rowMer->merchant_id) ? "selected='selected'" : "";
                            $first = htmlspecialchars(stripslashes($rowMer->merchant_firstname));
                            $last = htmlspecialchars(stripslashes($rowMer->merchant_lastname));
                            $id = (int)$rowMer->merchant_id;
                            echo "<option value=\"$id\" $selected>$first&nbsp;$last</option>";
                        }
                    }
                    ?>
                </select>
            </td>
        </tr>
        <tr>
            <td height="25" colspan="2" align="center">
                Program:
                <select name="programs">
                    <!-- Options populated dynamically by JavaScript -->
                </select>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center" height="26">
                <input type="submit" name="sub" value="View" />
            </td>
        </tr>
    </table>
</form>

<?php
if (!empty($sub)) {
    $total = explode("~", $Link[$i]);
    if (!empty($_SESSION['LINKS'])) {
        $To   = $partners->date2mysql($txtto);
        $From = $partners->date2mysql($txtfrom);

        // Secure mysqli version of impressions query
        $stmt = $conn->prepare("SELECT SUM(imp_count) AS impr_count FROM partners_impression_daily WHERE imp_linkid = ? AND imp_date BETWEEN ? AND ?");
        $stmt->bind_param("sss", $total[6], $From, $To);
        $stmt->execute();
        $impRet = $stmt->get_result();
        $row_impr = $impRet->fetch_object();
        $numRec = $row_impr->impr_count ?? 0;

        $rawClick = GetRawTrans('click', 0, 0, 0, $total[6], $From, $To, 0);
        $rawImp   = GetRawTrans('impression', 0, 0, 0, $total[6], $From, $To, 0);

        $selDate = $heading;
        ?>
        <p align="right">
            <a href="#" onclick="window.open('../print_link.php?mid=<?= htmlspecialchars($merchants) ?>&mode=admin&date=<?= urlencode($selDate) ?>&from=<?= urlencode($From) ?>&to=<?= urlencode($To) ?>&program=<?= urlencode($programs) ?>&currValue=<?= urlencode($currValue) ?>&currsymbol=<?= urlencode($currSymbol) ?>','new','400,400,scrollbars=1,resizable=1');"><b>Print Report</b></a>&nbsp;&nbsp;&nbsp;&nbsp;
            <a href="../csv_link.php?mid=<?= htmlspecialchars($merchants) ?>&mode=admin&date=<?= urlencode($selDate) ?>&from=<?= urlencode($From) ?>&to=<?= urlencode($To) ?>&program=<?= urlencode($programs) ?>&currValue=<?= urlencode($currValue) ?>&currsymbol=<?= urlencode($currSymbol) ?>"><b>Export as CSV</b></a>
        </p>
        <table border='0' cellpadding="0" cellspacing="0" width="75%" class="tablebdr" align="center">
            <tr>
                <td height="25" align="center" class="tdhead" colspan="4">Report<br /><?= htmlspecialchars($heading) ?></td>
            </tr>
            <tr>
                <td height="20" align="center" colspan="4"></td>
            </tr>
            <tr>
                <td height="51" align="center" colspan="4">
                    <?php
                    if (substr($total[6], 0, 1) == 'H') {
                        $id = substr($total[6], 1);
                        ?>
                        <a href='../merchants/temp.php?rowid=<?= urlencode($id) ?>' target="new">Click Here to View Html</a>
                        <?php
                    }

                    if (substr($total[6], 0, 1) == 'T') {
                        $id = substr($total[6], 1);
                        ?>
                        <a href='text.php?id=<?= urlencode($id) ?>' target="new">Click Here to View Text</a>
                        <?php
                    }

                    if (substr($total[6], 0, 1) == 'N') {
                        $id = substr($total[6], 1);
                        ?>
                        <a href='../merchants/temptext.php?rowid=<?= urlencode($id) ?>' target="new">Click Here to View Template Text</a>

                     <?php
                    }

                    if (substr($total[6], 0, 1) == 'P') {
                        $id = substr($total[6], 1);
                        $stmt = $conn->prepare("SELECT * FROM partners_popup WHERE popup_id = ?");
                        $stmt->bind_param("s", $id);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        $row = $result->fetch_object();
                        ?>
                        <a href="#" onclick="window.open('<?= htmlspecialchars(stripslashes($row->popup_url)) ?>',<?= (int)$row->popup_width ?>,<?= (int)$row->popup_height ?>)">Click Here to View Pop-Up</a>
                        <?php
                    }

                    if (substr($total[6], 0, 1) == 'B') {
                        $id = substr($total[6], 1);
                        $stmt = $conn->prepare("SELECT * FROM partners_banner WHERE banner_id = ?");
                        $stmt->bind_param("s", $id);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        $row = $result->fetch_object();
                        ?>
                        <img border='0' src="<?= htmlspecialchars(stripslashes($row->banner_name)) ?>" width="300" height="70" alt="" />
                        <?php
                    }

                    if (substr($total[6], 0, 1) == 'F') {
                        $id = substr($total[6], 1);
                        $stmt = $conn->prepare("SELECT * FROM partners_flash WHERE flash_id = ?");
                        $stmt->bind_param("s", $id);
                        $stmt->execute();
                        $result = $stmt->get_result();
                        $row = $result->fetch_object();
                        ?>
                        <object type="application/x-shockwave-flash" data="<?= htmlspecialchars(stripslashes($row->flash_url)) ?>" width="300" height="70">
                            <param name="movie" value="<?= htmlspecialchars(stripslashes($row->flash_url)) ?>" />
                        </object>
                        <?php
                    }
                    ?>
                </td>
            </tr>
            <tr>
                <td colspan="4">
                    <br/>
                    <?php viewRawTrans($rawClick, $rawImp); ?>
                    <table width="85%" align="center" class="tablebdr">
                        <tr>
                            <td width="40%" class="tdhead">Transactions</td>
                            <td width="30%" class="tdhead">Number</td>
                            <td width="30%" class="tdhead">Commission</td>
                        </tr>
                        <tr>
                            <td class="grid1" height="28">Impressions&nbsp;<img alt="" border='0' height="10" src="../images/impression.gif" width="10" /></td>
                            <td class="grid1" height="28"><?= (int)$numRec ?></td>
                            <td class="grid1" height="28"><?= htmlspecialchars($currSymbol) . round($total[11], 2) ?></td>
                        </tr>
                        <tr>
                            <td class="grid1" height="28">Click&nbsp;<img alt="" border='0' height="10" src="../images/click.gif" width="10" /></td>
                            <td class="grid1" height="28"><?= (int)$total[1] ?></td>
                            <td class="grid1" height="28"><?= htmlspecialchars($currSymbol) . round($total[0], 2) ?></td>
                        </tr>
                        <tr>
                            <td class="grid1" height="28">Lead&nbsp;<img alt="" border='0' height="10" src="../images/lead.gif" width="10" /></td>
                            <td class="grid1" height="28"><?= (int)$total[3] ?></td>
                            <td class="grid1" height="28"><?= htmlspecialchars($currSymbol) . round($total[2], 2) ?></td>
                        </tr>
                        <tr>
                            <td class="grid1" height="28">Sale&nbsp;<img alt="" border='0' height="10" src="../images/sale.gif" width="10" /></td>
                            <td class="grid1" height="28"><?= (int)$total[5] ?></td>
                            <td class="grid1" height="28"><?= htmlspecialchars($currSymbol) . round($total[4], 2) ?></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td colspan="4">
                    <br/>
                    <table width="100%" class="tablewbdr" align="center">
                        <tr>
                            <td class="tdhead" align="center">Pending</td>
                            <td class="tdhead" align="center">Reversed</td>
                            <td class="tdhead" align="center">Impressions</td>
                        </tr>
                        <tr>
                            <td height="28" align="center"><?= htmlspecialchars($currSymbol) . round($total[8], 2) ?></td>
                            <td height="28" align="center"><?= htmlspecialchars($currSymbol) . round($total[10], 2) ?></td>
                            <td height="28" align="center"><?= (int)$numRec ?></td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td height="25" width="32%" class="tdhead" align="center">
                    <?php if ($i != 1) { ?>
                        <a href="index.php?Act=link_report&amp;i=<?= ($i - 1) ?>&amp;sub=<?= urlencode($sub) ?>&amp;txtto=<?= urlencode($txtto) ?>&amp;txtfrom=<?= urlencode($txtfrom) ?>&amp;programs=<?= urlencode($programs) ?>&amp;merchants=<?= urlencode($MERCHANTID) ?>"><font color="#FFFFFF">Previous</font></a>
                    <?php } else {
                        echo "<font color='#FFFFFF'>Previous</font>";
                    } ?>
                </td>
                <td height="25" align="center" class="tdhead" colspan="2">Total Record Found - <?= (int)$TOTALREC ?></td>
                <td height="25" width="33%" align="center" class="tdhead">
                    <?php if ($i != (count($Link) - 1)) { ?>
                        <a href="index.php?Act=link_report&amp;i=<?= ($i + 1) ?>&amp;sub=<?= urlencode($sub) ?>&amp;txtto=<?= urlencode($txtto) ?>&amp;txtfrom=<?= urlencode($txtfrom) ?>&amp;programs=<?= urlencode($programs) ?>&amp;merchants=<?= urlencode($MERCHANTID) ?>"><font color="#FFFFFF">Next</font></a>
                    <?php } else {
                        echo "Next";
                    } ?>
                </td>
            </tr>
        </table>
    <?php
    } else {
    ?>
        <table width="100%" align="center">
            <tr>
                <td align="center" class="textred"><?= htmlspecialchars($norec) ?> </td>
            </tr>
        </table>
    <?php
    }
}
?>
<br />