<?php

// beginning of class desi definition
class partners
{
    private $pdo;

    function connection($host, $user, $pass, $db)
    {
        global $pdo;
        
        // Use the global PDO connection if it exists
        if (isset($pdo) && $pdo instanceof PDO) {
            $this->pdo = $pdo;
            return true;
        }
        
        // Fallback: create new connection only if global doesn't exist
        try {
            $dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            
            $this->pdo = new PDO($dsn, $user, $pass, $options);
            return true;
            
        } catch (PDOException $e) {
            error_log("Database Connection Failed: " . $e->getMessage());
            throw new RuntimeException('Database connection failed. Please try again later.');
        }
    }

    //check for admin login
    function islogin()
    {
        if (!empty($_SESSION['ADMIN']) || !empty($_SESSION['ADMINUSERID']))
            return 1;
        else
            return 0;
    }

    //check for affiliate login
    function isAffiliatelogin()
    {
        if (!empty($_SESSION['AFFILIATEID']))
            return 1;
        else
            return 0;
    }

    //check for MERCHANT login
    function isMerchantlogin()
    {
        if (!empty($_SESSION['MERCHANTID']))
            return 1;
        else
            return 0;
    }

    //check for e-mail validation (Modernized with filter_var)
    function is_email($mail)
    {
        if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) return 0;
        else return 1;
    }

    //check for valid date
    function is_date($date){
        $tmp = explode('/',$date);
        if(count($tmp)!=3) {
            $tmp = explode('-',$date);
            if(count($tmp)!=3) return 0;
        }
        if(!is_numeric($tmp[1]) || !is_numeric($tmp[0]) || !is_numeric($tmp[2]))
            return 0;
        if(checkdate($tmp[1],$tmp[0],$tmp[2])) return 1;
        else return 0;
    }

    //check for valid date in mysql Format
    function is_date_Mysql($date){
        $tmp = explode('/',$date);
        if(count($tmp)!=3) {
            $tmp = explode('-',$date);
            if(count($tmp)!=3) return 0;
        }
        if(!is_numeric($tmp[1]) || !is_numeric($tmp[0]) || !is_numeric($tmp[2]))
            return 0;
        if(checkdate($tmp[1],$tmp[2],$tmp[0])) return 1;
        else return 0;
    }

    // formats the date (mm/dd/yy) to mysql format (yyyy-mm-dd)
    function date2mysql($date){
        $tmp = explode('/',$date);
        if(count($tmp)!=3) {
            $tmp = explode('-',$date);
            if(count($tmp)!=3) return "0000-00-00";
        }
        $date = "$tmp[2]-$tmp[1]-$tmp[0]";
        return $date;
    }

    function format_date($dob,$time=0)
    {
        $tmp = explode(" ",$dob);
        $date2 = explode("/",$tmp[0]);
        $dob = $date2[2]."/".$date2[0]."/".$date2[1];
        if($time)
            return $dob." ".$tmp[1];
        else
            return $dob;
    }

    function getpage(){
        if(!isset($_GET['page'])) $page=1;
        else $page=$_GET['page'];
        return $page;
    }

    function show_page_nos($sql,$url,$lines1,$page){
        $tmp = explode("LIMIT", $sql);
        if(count($tmp)<1) $tmp = explode("limit", $sql);
        $pgsql = $tmp[0];
        include 'admin_show_pagenos.php';
    }

    function RandomNumber( $noLength ) {
        $randNo = "";
        $randArray = array();
        $randArray1 = array(0,1,2,3,4,5,6,9,8,9);
        $randArray2 = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
        $randArray3 = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

        for ($index = 1; $index <= $noLength; $index++) {
            $rand = mt_rand(0,9);
            $randNo .= $randArray1[$rand];
            $rand = mt_rand(0,25);
            $randNo .= $randArray2[$rand];
            $rand = mt_rand(0,25);
            $randNo .= $randArray3[$rand];
        }
        return $randNo;
    }
}

function GetRawTrans($type, $mid, $aid, $pgmid, $linkid, $from, $to, $date)
{
    return GetRawTrans_daily($type, $mid, $aid, $pgmid, $linkid, $from, $to, $date);
}

function GetRawTrans_daily($type, $mid, $aid, $pgmid, $linkid, $from, $to, $date)
{
    global $pdo;
    $totalRecord = 0;

    if($type=='impression')
        $tranSql = "SELECT sum(transdaily_impression) AS TOTAL FROM partners_rawtrans_daily WHERE 1";
    else
        $tranSql = "SELECT sum(transdaily_click) AS TOTAL FROM partners_rawtrans_daily WHERE 1";

    if($mid) $tranSql .= " AND transdaily_merchantid = ? ";
    if($aid) $tranSql .= " AND transdaily_affiliateid = ? ";
    if($pgmid) $tranSql .= " AND transdaily_programid = ? ";
    if($linkid) $tranSql .= " AND transdaily_linkid = ? ";
    if($date) $tranSql .= " AND transdaily_date like ? ";
    if(($to) and ($from)) $tranSql .= " AND transdaily_date between ? AND ? ";

    try {
        $stmt = $pdo->prepare($tranSql);
        $paramIndex = 1;
        if($mid) $stmt->bindValue($paramIndex++, $mid, PDO::PARAM_INT);
        if($aid) $stmt->bindValue($paramIndex++, $aid, PDO::PARAM_INT);
        if($pgmid) $stmt->bindValue($paramIndex++, $pgmid, PDO::PARAM_INT);
        if($linkid) $stmt->bindValue($paramIndex++, $linkid, PDO::PARAM_INT);
        if($date) $stmt->bindValue($paramIndex++, $date, PDO::PARAM_STR);
        if(($to) and ($from)) {
            $stmt->bindValue($paramIndex++, $from, PDO::PARAM_STR);
            $stmt->bindValue($paramIndex++, $to, PDO::PARAM_STR);
        }

        $stmt->execute();
        $tranRow = $stmt->fetch();
        $totalRecord = $tranRow['TOTAL'] ?? 0;
        
    } catch (PDOException $e) {
        error_log("GetRawTrans_daily Error: " . $e->getMessage());
    }

    return $totalRecord;
}

function viewRawTrans($click, $imp){
    if(!$click) $click = '0';
    if(!$imp) $imp = '0';
    ?>
    <table width="50%" class="tablewbdr" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
        <td height="7" colspan="2"></td>
    </tr>
    <tr>
        <td height="20"><b><font color='#923D4E'>Raw Clicks</font></b></td>
        <td height="20"><b>: <?php echo htmlspecialchars($click); ?></b></td>
    </tr>
    <tr>
        <td height="20"><b><font color='#923D4E'>Raw Impressions</font></b></td>
        <td height="20"><b>: <?php echo htmlspecialchars($imp); ?></b></td>
    </tr>
    </table>
    <?php
}

function getCurrencyValue($date, $currencyName, $amount){
    global $pdo;
    $currValue = 0;

    $sql = "SELECT * FROM partners_currency, partners_currency_relation WHERE currency_caption = ? ".
           " AND currency_code = relation_currency_code AND relation_date <= ? ORDER BY relation_date DESC";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$currencyName, $date]);
        $row = $stmt->fetch();

        if ($row) {
            $currRelation = $row['relation_value'];
            $currValue = round(($amount * $currRelation), 2);
        }
    } catch (PDOException $e) {
        error_log("getCurrencyValue Error: " . $e->getMessage());
    }

    return $currValue;
}

function getDefaultCurrencyValue($date, $currencyName, $amount){
    global $pdo;
    $currValue = 0;

    $sql = "SELECT * FROM partners_currency, partners_currency_relation WHERE currency_caption = ? ".
           " AND currency_code = relation_currency_code AND relation_date <= ? ORDER BY relation_date DESC";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$currencyName, $date]);
        $row = $stmt->fetch();

        if ($row) {
            $currRelation = $row['relation_value'];
            $currValue = ($amount / $currRelation);
        }
    } catch (PDOException $e) {
        error_log("getDefaultCurrencyValue Error: " . $e->getMessage());
    }

    return $currValue;
}

function getDollarValue($date, $currencyName, $amount){
    global $pdo;
    $currValue = 0;

    $sql = "SELECT currency_relation FROM partners_currency WHERE currency_date <= ? AND ".
           " currency_caption like ? ORDER BY currency_date DESC";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$date, $currencyName]);
        $row = $stmt->fetch();

        if ($row) {
            $currRelation = $row['currency_relation'];
            $currValue = ($amount / $currRelation);
        }
    } catch (PDOException $e) {
        error_log("getDollarValue Error: " . $e->getMessage());
    }

    return $currValue;
}

function payProgramFee($id, $totamount, $pgmid){
    global $pdo;
    
    try {
        $merchant_sql = "SELECT * FROM merchant_pay WHERE pay_merchantid = ?";
        $stmt = $pdo->prepare($merchant_sql);
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        
        $merchant_pay_amount = $row['pay_amount'] ?? 0;

        if($merchant_pay_amount - $totamount >= 0){
            $admin_sql = "SELECT * FROM admin_pay";
            $stmt = $pdo->prepare($admin_sql);
            $stmt->execute();
            $admin_row = $stmt->fetch();
            
            $admin_pay_amount = $admin_row['pay_amount'] ?? 0;

            $merchant_pay_amount -= $totamount;
            $admin_pay_amount += $totamount;

            $sql1 = "UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?";
            $stmt = $pdo->prepare($sql1);
            $stmt->execute([$merchant_pay_amount, $id]);

            $sql2 = "UPDATE admin_pay SET pay_amount = ?";
            $stmt = $pdo->prepare($sql2);
            $stmt->execute([$admin_pay_amount]);

            $_SESSION['MERCHANTBALANCE'] = $merchant_pay_amount;

            $today = date("Y-m-d");
            if($totamount){
                $sql3 = "INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) ".
                       "VALUES (?, 'programFee', 'm', ?, ?, ?)";
                $stmt = $pdo->prepare($sql3);
                $stmt->execute([$id, $totamount, $today, $pgmid]);
            }
            
            $sql4 = "INSERT INTO partners_fee (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) ".
                   "VALUES (?, 'programFee', 'closed', ?, ?, ?)";
            $stmt = $pdo->prepare($sql4);
            $stmt->execute([$id, $totamount, $today, $pgmid]);
            
        } else {
            $today = date("Y-m-d");
            $sql3 = "INSERT INTO partners_fee (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) ".
                   "VALUES (?, 'programFee', 'pending', ?, ?, ?)";
            $stmt = $pdo->prepare($sql3);
            $stmt->execute([$id, $totamount, $today, $pgmid]);
        }
        
    } catch (PDOException $e) {
        error_log("payProgramFee Error: " . $e->getMessage());
    }
}

function closeFee($tid, $id, $pgmid, $totamount){
    global $pdo;
    
    try {
        $merchant_sql = "SELECT * FROM merchant_pay WHERE pay_merchantid = ?";
        $stmt = $pdo->prepare($merchant_sql);
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        
        $merchant_pay_amount = $row['pay_amount'] ?? 0;

        if($merchant_pay_amount - $totamount >= 0){
            $admin_sql = "SELECT * FROM admin_pay";
            $stmt = $pdo->prepare($admin_sql);
            $stmt->execute();
            $admin_row = $stmt->fetch();
            
            $admin_pay_amount = $admin_row['pay_amount'] ?? 0;

            $merchant_pay_amount -= $totamount;
            $admin_pay_amount += $totamount;

            $sql1 = "UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?";
            $stmt = $pdo->prepare($sql1);
            $stmt->execute([$merchant_pay_amount, $id]);

            $sql2 = "UPDATE admin_pay SET pay_amount = ?";
            $stmt = $pdo->prepare($sql2);
            $stmt->execute([$admin_pay_amount]);

            $sql3 = "UPDATE partners_fee SET adjust_flag = 'closed' WHERE adjust_id = ?";
            $stmt = $pdo->prepare($sql3);
            $stmt->execute([$tid]);

            $today = date("Y-m-d");
            if($totamount){
                $sql4 = "INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) ".
                       "VALUES (?, 'programFee', 'm', ?, ?, ?)";
                $stmt = $pdo->prepare($sql4);
                $stmt->execute([$id, $totamount, $today, $pgmid]);
            }
        }
        
    } catch (PDOException $e) {
        error_log("closeFee Error: " . $e->getMessage());
    }
}

function payMembershipFee($id, $totamount){
    global $pdo;
    
    try {
        $merchant_sql = "SELECT * FROM merchant_pay WHERE pay_merchantid = ?";
        $stmt = $pdo->prepare($merchant_sql);
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        
        $merchant_pay_amount = $row['pay_amount'] ?? 0;

        if($merchant_pay_amount - $totamount >= 0){
            $admin_sql = "SELECT * FROM admin_pay";
            $stmt = $pdo->prepare($admin_sql);
            $stmt->execute();
            $admin_row = $stmt->fetch();
            
            $admin_pay_amount = $admin_row['pay_amount'] ?? 0;

            $merchant_pay_amount -= $totamount;
            $admin_pay_amount += $totamount;

            $sql1 = "UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?";
            $stmt = $pdo->prepare($sql1);
            $stmt->execute([$merchant_pay_amount, $id]);

            $sql2 = "UPDATE admin_pay SET pay_amount = ?";
            $stmt = $pdo->prepare($sql2);
            $stmt->execute([$admin_pay_amount]);

            $_SESSION['MERCHANTBALANCE'] = $merchant_pay_amount;

            $today = date("Y-m-d");
            if($totamount){
                $sql22 = "INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) ".
                        "VALUES (?, 'deposit', 'm', ?, ?, 0)";
                $stmt = $pdo->prepare($sql22);
                $stmt->execute([$id, $totamount, $today]);
            }
            
            $sql3 = "INSERT INTO partners_fee (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date) ".
                   "VALUES (?, 'register', 'closed', ?, ?)";
            $stmt = $pdo->prepare($sql3);
            $stmt->execute([$id, $totamount, $today]);
            
        } else {
            $today = date("Y-m-d");
            $sql3 = "INSERT INTO partners_fee (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date) ".
                   "VALUES (?, 'register', 'pending', ?, ?)";
            $stmt = $pdo->prepare($sql3);
            $stmt->execute([$id, $totamount, $today]);
        }
        
    } catch (PDOException $e) {
        error_log("payMembershipFee Error: " . $e->getMessage());
    }
}

function closeMemFee($tid, $id, $totamount){
    global $pdo;
    
    try {
        $merchant_sql = "SELECT * FROM merchant_pay WHERE pay_merchantid = ?";
        $stmt = $pdo->prepare($merchant_sql);
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        
        $merchant_pay_amount = $row['pay_amount'] ?? 0;

        if($merchant_pay_amount - $totamount >= 0){
            $admin_sql = "SELECT * FROM admin_pay";
            $stmt = $pdo->prepare($admin_sql);
            $stmt->execute();
            $admin_row = $stmt->fetch();
            
            $admin_pay_amount = $admin_row['pay_amount'] ?? 0;

            $merchant_pay_amount -= $totamount;
            $admin_pay_amount += $totamount;

            $sql1 = "UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?";
            $stmt = $pdo->prepare($sql1);
            $stmt->execute([$merchant_pay_amount, $id]);

            $sql2 = "UPDATE admin_pay SET pay_amount = ?";
            $stmt = $pdo->prepare($sql2);
            $stmt->execute([$admin_pay_amount]);

            $sql3 = "UPDATE partners_fee SET adjust_flag = 'closed' WHERE adjust_id = ?";
            $stmt = $pdo->prepare($sql3);
            $stmt->execute([$tid]);

            $today = date("Y-m-d");
            if($totamount){
                $sql4 = "INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) ".
                       "VALUES (?, 'register', 'm', ?, ?, 0)";
                $stmt = $pdo->prepare($sql4);
                $stmt->execute([$id, $totamount, $today]);
            }
        }
        
    } catch (PDOException $e) {
        error_log("closeMemFee Error: " . $e->getMessage());
    }
}

function getStealthRedirect($code) {
    global $pdo;

    $sql = "SELECT destination_url FROM partners_stealth_links WHERE cloaked_code = ? AND status = 'active'";
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$code]);
        $row = $stmt->fetch();
        return $row ? $row['destination_url'] : false;
    } catch (PDOException $e) {
        error_log("getStealthRedirect Error: " . $e->getMessage());
        return false;
    }
}

function log_admin_action($pdo, $actionType, $actionDetail, $ipOverride = null) {
    if (!isset($_SESSION['admin_id'])) return;

    $adminId = $_SESSION['admin_id'];
    $ip = $ipOverride ?? $_SERVER['REMOTE_ADDR'];

    $stmt = $pdo->prepare("INSERT INTO admin_action_logs 
        (admin_id, action_type, action_detail, ip_address) 
        VALUES (?, ?, ?, ?)");
    $stmt->execute([$adminId, $actionType, $actionDetail, $ip]);
}

?>