<?php
/***************************************************************************************************
PROGRAM DESCRIPTION :  PROGRAM TO VIEW DAILY REPORTS
****************************************************************************************************/

include_once '../includes/constants.php';
include_once '../includes/functions.php';
include_once '../includes/session.php';
include_once '../includes/allstripslashes.php';

// Database connection
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Fetch merchants and affiliates
$merchants = $mysqli->query("SELECT * FROM partners_merchant");
$affiliates = $mysqli->query("SELECT * FROM partners_affiliate");

// Session and POST logic
$_SESSION['MERCHANT'] = $_SESSION['MERCHANT'] ?? 'All';
$_SESSION['AFFILIATE'] = $_SESSION['AFFILIATE'] ?? 'All';

if (!empty($_POST['Mname'])) {
    $_SESSION['MERCHANT'] = $_POST['Mname'];
}
if (!empty($_POST['Aname'])) {
    $_SESSION['AFFILIATE'] = $_POST['Aname'];
}

// Date logic
if (empty($_GET['d'])) {
    $today = getdate();
    $d = $today['mday'];
    $m = date("m");
    $y = $today['year'];
} else {
    $d = intval($_GET['d']);
    $m = intval($_GET['m']);
    $y = intval($_GET['y']);
}

$Merchant = $_SESSION['MERCHANT'];
$Affiliate = $_SESSION['AFFILIATE'];
$dateoftrans = "$y-$m-$d";

// Query logic
if ($Merchant === 'All') {
    if ($Affiliate === 'All') {
        $sql = "SELECT * FROM partners_joinpgm";
        $impSql = "SELECT SUM(imp_count) AS impr_count FROM partners_impression_daily WHERE imp_date = ?";
        $rawClick = GetRawTrans('click', 0, 0, 0, 0, 0, 0, $dateoftrans);
        $rawImp = GetRawTrans('impression', 0, 0, 0, 0, 0, 0, $dateoftrans);
    } else {
        $sql = "SELECT * FROM partners_joinpgm WHERE joinpgm_affiliateid = '$Affiliate'";
        $impSql = "SELECT SUM(imp_count) AS impr_count FROM partners_impression_daily WHERE imp_affiliateid = '$Affiliate' AND imp_date = ?";
        $rawClick = GetRawTrans('click', 0, $Affiliate, 0, 0, 0, 0, $dateoftrans);
        $rawImp = GetRawTrans('impression', 0, $Affiliate, 0, 0, 0, 0, $dateoftrans);
    }
} else {
    if ($Affiliate === 'All') {
        $sql = "SELECT * FROM partners_joinpgm INNER JOIN partners_program ON joinpgm_programid = program_id WHERE program_merchantid = '$Merchant'";
        $impSql = "SELECT SUM(imp_count) AS impr_count FROM partners_impression_daily WHERE imp_merchantid = '$Merchant' AND imp_date = ?";
        $rawClick = GetRawTrans('click', $Merchant, 0, 0, 0, 0, 0, $dateoftrans);
        $rawImp = GetRawTrans('impression', $Merchant, 0, 0, 0, 0, 0, $dateoftrans);
    } else {
        $sql = "SELECT * FROM partners_joinpgm INNER JOIN partners_program ON joinpgm_programid = program_id WHERE program_merchantid = '$Merchant' AND joinpgm_affiliateid = '$Affiliate'";
        $impSql = "SELECT SUM(imp_count) AS impr_count FROM partners_impression_daily WHERE imp_merchantid = '$Merchant' AND imp_affiliateid = '$Affiliate' AND imp_date = ?";
        $rawClick = GetRawTrans('click', $Merchant, $Affiliate, 0, 0, 0, 0, $dateoftrans);
        $rawImp = GetRawTrans('impression', $Merchant, $Affiliate, 0, 0, 0, 0, $dateoftrans);
    }
}

$result1 = $mysqli->query($sql);

// Get impression count
$numRec = 0;
$stmt = $mysqli->prepare($impSql);
$stmt->bind_param("s", $dateoftrans);
$stmt->execute();
$stmt->bind_result($numRec);
$stmt->fetch();
$stmt->close();

$numRec = $numRec ?? 0;

// Initialize counters
$click = $lead = $sale = 0.00;
$nclick = $nlead = $nsale = 0;
$impression = 0.00;

while ($row = $result1->fetch_object()) {
    $joinid = $row->joinpgm_id;

    // Click transactions
    $result = $mysqli->query("SELECT * FROM partners_transaction WHERE transaction_dateoftransaction = '$dateoftrans' AND transaction_type = 'click' AND transaction_joinpgmid = '$joinid'");
    $nclick += $result->num_rows;
    while ($tr = $result->fetch_object()) {
        $click += $tr->transaction_amttobepaid + $tr->transaction_admin_amount;
    }

    // Lead transactions
    $result = $mysqli->query("SELECT * FROM partners_transaction WHERE transaction_dateoftransaction = '$dateoftrans' AND transaction_type = 'lead' AND transaction_joinpgmid = '$joinid'");
    $nlead += $result->num_rows;
    while ($tr = $result->fetch_object()) {
        $lead += $tr->transaction_amttobepaid + $tr->transaction_admin_amount;
    }

    // Sale transactions
    $result = $mysqli->query("SELECT * FROM partners_transaction WHERE transaction_dateoftransaction = '$dateoftrans' AND transaction_type = 'sale' AND transaction_joinpgmid = '$joinid'");
    $nsale += $result->num_rows;
    while ($tr = $result->fetch_object()) {
        $transactionId = $tr->transaction_id;
        $recur = $tr->transaction_recur;

        if ($recur == '1') {
            $res_Recur = $mysqli->query("SELECT * FROM partners_recur WHERE recur_transactionid = '$transactionId'");
            if ($res_Recur->num_rows > 0) {
                $row_recur = $res_Recur->fetch_object();
                $recurId = $row_recur->recur_id;
                $res_recurpay = $mysqli->query("SELECT * FROM partners_recurpayments WHERE recurpayments_recurid = '$recurId'");
                if ($res_recurpay->num_rows > 0) {
                    $row_recurpay = $res_recurpay->fetch_object();
                    $sale += $row_recurpay->recurpayments_amount;
                }
            }
        } else {
            $sale += $tr->transaction_amttobepaid;
        }
        $sale += $tr->transaction_admin_amount;
    }

    // Impression transactions
    $result = $mysqli->query("SELECT * FROM partners_transaction WHERE transaction_dateoftransaction = '$dateoftrans' AND transaction_type = 'impression' AND transaction_joinpgmid = '$joinid'");
    while ($tr = $result->fetch_object()) {
        $impression += $tr->transaction_amttobepaid + $tr->transaction_admin_amount;
    }
}

$selDate = "$d.$m.$y";
$values = "$numRec~$impression~$nclick~$click~$nlead~$lead~$nsale~$sale";
?>

<p align="right">
    <a href="#" onclick="window.open('../print_daily.php?mid=<?= $Merchant ?>&mode=admin&date=<?= $selDate ?>&values=<?= $values ?>&aid=<?= $Affiliate ?>','new','400,400,scrollbars=1,resizable=1');"><b>Print Report</b></a>&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="../csv_daily.php?mid=<?= $Merchant ?>&mode=admin&date=<?= $selDate ?>&values=<?= $values ?>&aid=<?= $Affiliate ?>"><b>Export as CSV</b></a>
</p>

<form name="showreport" method="post" action="">
    <table width="90%" align="center" border="0">
        <tr>
            <td align="right">
                <table class="tablebdr" width="100%" cellpadding="0" cellspacing="0">
                    <tr><td class="tdhead" align="center"><b>Statistics on <?= $selDate ?></b></td></tr>
                    <tr><td>
                        <table class="tablewbdr" width="95%" align="center">
                            <tr>
                                <td width="25%">Merchants</td>
                                <td width="50%">
                                    <select name="Mname">
                                        <option value="All">All Merchants</option>
                                        <?php while ($row = $merchants->fetch_object()): ?>
                                            <option value="<?= $row->merchant_id ?>" <?= ($_SESSION['MERCHANT'] == $row->merchant_id) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars(stripslashes($row->merchant_company)) ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td width="25%">Affiliates</td>
                                <td width="50%">
                                    <select name="Aname">
                                        <option value="All">All Affiliates</option>
                                        <?php while ($row = $affiliates->fetch_object()): ?>
                                            <option value="<?= $row->affiliate_id ?>" <?= ($_SESSION['AFFILIATE'] == $row->affiliate_id) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars(stripslashes($row->affiliate_company)) ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <input type="submit" name="merchant" value="View" />
                                </td>
                            </tr>
                        </table>
                    </td></tr>
                </table>
            </td>
        </tr>
    </table>
</form>
