<?php
session_start();
include_once 'session.php';

class text_display
{
    /*-------------------------------------------------------------------------------------------
    Function to Display the TextAd with the selected colors.  Used in get_trackingcode.php.
    -------------------------------------------------------------------------------------------*/
    function displayTextAd($id, $col_boder, $col_back, $col_title, $col_url, $col_head, $col_desc, $trackUrl, $newwindow, $width, $height, $track_site_url)
    {
        global $pdo;
        
        if($col_boder=="") {
            $col_boder = "#3399FF";
            $col_back = "#FFFFFF";
            $col_title = "#000000";
            $col_url = "#009900";
            $col_head = "#FFFFFF";
            $col_desc = "#7E7E7E";
        }
        if($width == '') $width = 500;
        if($height == '') $height = 75;

        if($newwindow == 1)  {
            $OpenWindow = "target='_blank'";
        } else {
            $OpenWindow = "";
        }

        $code = "";
        $sql = "SELECT * FROM partners_text WHERE text_id = ?";
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $row_text = $row['text_text'];
                $row_no = $row['text_rows'];
                $url = $row['text_url'];
                $desc = $row['text_description'];

                # if the 1st part of the URL not contain http:/
                $url_test = substr($url, 0, 7);
                if($url_test!="http://") {
                    $url = "http://".$url;
                }
                //getting only domain name from the url
                $url1 = explode("://",$url);
                $url2 = explode("/",$url1[1]);
                $disp_url = "http://".$url2[0];

                $image = $row['text_image'];
            }
        } catch (PDOException $e) {
            error_log("displayTextAd Error: " . $e->getMessage());
        }

        $tableWidth = $width-2;
        $tableHeight = $height-2;
        $imgHeight = $height - 25;

        if(!empty($image)) {
            $img_colspan = " colspan=2 ";
            $imgcode = "<img src='$track_site_url/thumbnail.php?image=$image&height=$imgHeight' alt='0' border='0' />";
        } else {
            $img_colspan = "";
            $imgcode = "";
        }

        $code  = "<div style=\"border:none; width:$width; height:$height; overflow:hidden\" >";
        $code .= "<table align=\"center\" width=\"$tableWidth\" height=\"$tableHeight\" border=\"1\" style=\"border-color:$col_boder; \" cellpadding=\"0\" cellspacing=\"0\">";
        $code .= "<tr style=\"border:none;\" valign=\"top\">";
        $code .= "<td style=\"border:none;\" valign=\"top\" width=\"$tableWidth\" height=\"$tableHeight\">";
        $code .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"$tableWidth\" height=\"$tableHeight\">";
        $code .= "<tr bgcolor=\"$col_boder\">";
        $code .= "<td align=\"left\" height=\"10\" valign=\"top\" colspan=\"2\" ><font style=\"color:$col_head; font-family:verdana; font-size:10px;\"><b>SPONSORED LISTINGS</b></font></td>";
        $code .= "</tr>";
        $code .= "<tr bgcolor=\"$col_back\">";
        $code .= "<td align=\"left\"><a href='$trackUrl' $OpenWindow ><font style=\"color:$col_title; font-family:verdana; font-size:10px;\"  ><b>$row_text</b></font></a></td>";
        $code .= "<td align=\"right\" rowspan=\"3\" > $imgcode </td>";
        $code .= "</tr>";
        $code .= "<tr bgcolor=\"$col_back\">";
        $code .= "<td align=\"left\"><font style=\"color:$col_desc; font-family:verdana; font-size:10px;\" >$desc</font></td>";
        $code .= "</tr>";
        $code .= "<tr bgcolor=\"$col_back\">";
        $code .= "<td align=\"left\"><font style=\"color:$col_url; font-family:verdana; font-size:10px;\" >$disp_url</font></td>";
        $code .= "</tr>";
        $code .= "</table>";
        $code .= "</td>";
        $code .= "</tr>";
        $code .= "</table>";
        $code .= "</div>";
        $code = str_replace("\"","'",$code);
        return $code;
    }
    
    /*-------------------------------------------------------------------------------------------
    Function to Display the TextAd with the selected colors in Rotator.  Used in get_trackingcode.php,
    and to display Text ad in Rotator(profile_view.php & profile_add.php)
    -------------------------------------------------------------------------------------------*/
    function showRotatorTextAd($id, $track_site_url, $width='500', $height='75', $col_boder='#3399FF', $col_back='#FFFFFF', $col_title='#000000', $col_url='#009900', $col_head='#FFFFFF', $col_desc='#7E7E7E')
    {
        global $pdo;
        
        $code = "";
        $sql = "SELECT * FROM partners_text WHERE text_id = ?";
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $row_text = $row['text_text'];
                $row_no = $row['text_rows'];
                $url = $row['text_url'];
                $desc = $row['text_description'];

                # if the 1st part of the URL not contain http:/
                $url_test = substr($url, 0, 7);
                if($url_test!="http://") {
                    $url = "http://".$url;
                }
                //getting only domain name from the url
                $url1 = explode("://",$url);
                $url2 = explode("/",$url1[1]);
                $disp_url = "http://".$url2[0];
                
                $image = $row['text_image'];
            }
        } catch (PDOException $e) {
            error_log("showRotatorTextAd Error: " . $e->getMessage());
        }
        
        $tableWidth = $width-2;
        $tableHeight = $height-2;
        $imgHeight = $height - 25;
        
        if(!empty($image)) {
            $img_colspan = " colspan=2 ";
            $imgcode = "<img src='$track_site_url/thumbnail.php?image=$image&height=$imgHeight' alt='0' border='0' />";
        } else {
            $img_colspan = "";
            $imgcode = "";
        }
        
        $code  = "<div style=\"width:$width; height:$height; overflow:hidden\" >";
        $code .= "<table align=\"center\" width=\"$tableWidth\" height=\"$tableHeight\" border=\"1\" style=\"border-color:$col_boder; \" cellpadding=\"0\" cellspacing=\"0\">";
        $code .= "<tr style=\"border:none;\" valign=\"top\">";
        $code .= "<td style=\"border:none;\" valign=\"top\" width=\"$tableWidth\" height=\"$tableHeight\">";
        $code .= "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"$tableWidth\" height=\"$tableHeight\">";
        $code .= "<tr bgcolor=\"$col_boder\">";
        $code .= "<td align=\"left\" height=\"10\" valign=\"top\" colspan=\"2\" ><font style=\"color:$col_head; font-family:verdana; font-size:10px;\"><b>SPONSORED LISTINGS</b></font></td>";
        $code .= "</tr>";
        $code .= "<tr bgcolor=\"$col_back\">";
        $code .= "<td align=\"left\"><a href='$url' target='_blank' ><font style=\"color:$col_title; font-family:verdana; font-size:10px;\"  >$row_text</font></a></td>";
        $code .= "<td align=\"right\" rowspan=\"3\" height=\"$imgHeight\" > $imgcode </td>";
        $code .= "</tr>";
        $code .= "<tr bgcolor=\"$col_back\">";
        $code .= "<td align=\"left\"><font style=\"color:$col_desc; font-family:verdana; font-size:10px;\" >$desc</font></td>";
        $code .= "</tr>";
        $code .= "<tr bgcolor=\"$col_back\">";
        $code .= "<td align=\"left\"><font style=\"color:$col_url; font-family:verdana; font-size:10px;\" >$disp_url</font></td>";
        $code .= "</tr>";
        $code .= "</table>";
        $code .= "</td>";
        $code .= "</tr>";
        $code .= "</table>";
        $code .= "</div>";
        $code = str_replace("\"","'",$code);
        return $code;
    }
}

//********* End Class Textdisplay *******************************

//********* Start Class Impression  *******************************
class impression
{
    ##Function to insert impression transaction into transaction table and trans_rates table
    ##Modified on 28-Feb-06
    function update_imp_transaction($joinid, $approvalstatus, $today, $impression_rate, $linkid, $admin_amount, $referer, $ip, $name, $subid, $impr_ids="", $unit="")
    {
        global $pdo;
        
        try {
            $sql = "INSERT into partners_transaction SET
            transaction_joinpgmid = ?,
            transaction_type = 'impression',
            transaction_status = ?,
            transaction_dateoftransaction = ?,
            transaction_amttobepaid = ?,
            transaction_linkid = ?,
            transaction_admin_amount = ?,
            transaction_referer = ?,
            transaction_ip = ?,
            transaction_country = ?,
            transaction_subid = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$joinid, $approvalstatus, $today, $impression_rate, $linkid, $admin_amount, $referer, $ip, $name, $subid]);
            
            if($stmt->rowCount() > 0) {
                #get the transaction id for the new impresion transaction
                $trans_id = $pdo->lastInsertId();

                #--insert into trans_rates table
                $sql = "INSERT into partners_trans_rates SET trans_id = ?, trans_rate = ?, trans_unit = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$trans_id, $impression_rate, $unit]);
                
                #--delete all impressions corresponding to the new transation fro the impression table
                $impr_ids = trim($impr_ids,",");

                # Update pending impression count into table partners_Impression_daily after recording a transaction
                $impr_arr = explode(",",$impr_ids);
                for($i=0; $i<count($impr_arr); $i++) {
                    $sum_pending = 0;
                    $sql_select = "SELECT imp_pending FROM partners_impression_daily WHERE imp_id = ?";
                    $stmt_select = $pdo->prepare($sql_select);
                    $stmt_select->execute([$impr_arr[$i]]);
                    
                    if($row_select = $stmt_select->fetch()) {
                        $sum_pending += $row_select['imp_pending'];

                        if($sum_pending <= $unit) {
                            $sql_update = "UPDATE partners_impression_daily SET imp_pending = '0' WHERE imp_id = ?";
                            $stmt_update = $pdo->prepare($sql_update);
                            $stmt_update->execute([$impr_arr[$i]]);
                        } else {
                            $balance_impr = $sum_pending - $unit;
                            $sql_update = "UPDATE partners_impression_daily SET imp_pending = ? WHERE imp_id = ?";
                            $stmt_update = $pdo->prepare($sql_update);
                            $stmt_update->execute([$balance_impr, $impr_arr[$i]]);
                        }
                    }
                }
            }
        } catch (PDOException $e) {
            error_log("update_imp_transaction Error: " . $e->getMessage());
            return false;
        }
        return true;
    }
}

//********* End Class Impression  *******************************    

//********* Start Class Common  *******************************
class common
{
    /*----------------------------------------------------------------
    Description   :- function to validate mandatory fields in a form
    -------------------------------------------------------------------*/
    function nullvalidation($validationstring)
    {
        //separate the fields from the string which contains all the fields separated by '~*'
        $fieldarray = explode("~*",trim($validationstring));
        
        //validate each field for null values
        for($i=0;$i<count($fieldarray);$i++) {
            //return true if any field is empty
            if(empty($fieldarray[$i]) and ($fieldarray[$i]!="0")) return true;
        }
        //return false if no null field
        return false;
    }
}

//********* End Class Common  *******************************

//********* Start Class recur  *******************************
class recur
{
    /*-------------------------------------------------------------------------------------------
    Function to get all the recurring commissions for the mechant with selected status
    -------------------------------------------------------------------------------------------*/
    function getRecurringCommissions($display, $mid)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_affiliate A, partners_transaction T, partners_recur R, partners_recurpayments P, partners_joinpgm J 
                WHERE T.transaction_recur ='1' AND T.transaction_joinpgmid = J.joinpgm_id AND 
                J.joinpgm_affiliateid = A.affiliate_id AND R.recur_transactionid = T.transaction_id AND 
                P.recurpayments_recurid = R.recur_id  AND P.recurpayments_status = ? AND R.recur_status='Active' 
                AND J.joinpgm_merchantid = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$display, $mid]);
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->payment_id[] = $row['recurpayments_id'];
                    $this->aff_name[] = $row['affiliate_firstname']." ".$row['affiliate_lastname'];
                    $this->aff_id[] = $row['affiliate_id'];
                    $this->recur_date[] = $row['recurpayments_date'];
                    $this->recur_status[] = $row['recurpayments_status'];
                    $this->recur_amount[] = $row['recurpayments_amount'];
                    $this->trans_orderid[] = $row['transaction_orderid'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("getRecurringCommissions Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the recurring Payment details of the selected record
    -------------------------------------------------------------------------------------------*/
    function getRecurDetails($id, $mid)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_affiliate A, partners_transaction T, partners_recur R, partners_recurpayments P, 
                partners_joinpgm J, partners_track_revenue V 
                WHERE P.recurpayments_id = ? AND P.recurpayments_recurid = R.recur_id AND 
                R.recur_transactionid = T.transaction_id AND T.transaction_joinpgmid = J.joinpgm_id AND 
                V.revenue_transaction_id = T.transaction_id AND J.joinpgm_affiliateid = A.affiliate_id AND 
                T.transaction_recur ='1' AND J.joinpgm_merchantid = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id, $mid]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $this->payment_id = $row['recurpayments_id'];
                $this->aff_name = $row['affiliate_firstname']." ".$row['affiliate_lastname'];
                $this->aff_id = $row['affiliate_id'];
                $this->aff_company = $row['affiliate_company'];
                $this->aff_url = $row['affiliate_url'];
                $this->recur_date = $row['recurpayments_date'];
                $this->recur_status = $row['recurpayments_status'];
                $this->recur_amount = $row['recurpayments_amount'];
                $this->trans_orderid = $row['transaction_orderid'];
                $this->sale_amount = $row['revenue_amount'];
                $this->total_comm = $row['recur_totalcommission'];
                $this->recur_period = $row['recur_period'];
                $this->recur_subsale = $row['recurpayments_subsaleamount'];
                $this->total_subsale = $row['recur_total_subsalecommission'];
                
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("getRecurDetails Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get all the Recuuring Transactions for the Merchant
    -------------------------------------------------------------------------------------------*/
    function getRecurringTransactions($mid)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_affiliate A, partners_transaction T, partners_joinpgm J, partners_recur R 
                WHERE T.transaction_recur ='1' AND T.transaction_joinpgmid = J.joinpgm_id AND R.recur_transactionid = T.transaction_id AND 
                J.joinpgm_affiliateid = A.affiliate_id AND J.joinpgm_merchantid = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$mid]);
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->trans_id[] = $row['transaction_id'];
                    $this->aff_name[] = $row['affiliate_firstname']." ".$row['affiliate_lastname'];
                    $this->aff_id[] = $row['affiliate_id'];
                    $this->trans_date[] = $row['transaction_dateoftransaction'];
                    $this->trans_status[] = $row['transaction_status'];
                    $this->trans_amount[] = $row['transaction_amttobepaid'];
                    $this->trans_orderid[] = $row['transaction_orderid'];
                    $this->recur_status[] = $row['recur_status'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("getRecurringTransactions Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the details of the selected recurring transaction
    -------------------------------------------------------------------------------------------*/
    function getRecurTransDetails($id, $mid)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_affiliate A, partners_transaction T, partners_recur R, 
                partners_joinpgm J, partners_track_revenue V 
                WHERE T.transaction_id = ? AND 
                R.recur_transactionid = T.transaction_id AND T.transaction_joinpgmid = J.joinpgm_id AND 
                V.revenue_transaction_id = T.transaction_id AND J.joinpgm_affiliateid = A.affiliate_id AND 
                T.transaction_recur ='1' AND J.joinpgm_merchantid = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id, $mid]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $this->payment_id = $row['transaction_id'];
                $this->aff_name = $row['affiliate_firstname']." ".$row['affiliate_lastname'];
                $this->aff_id = $row['affiliate_id'];
                $this->aff_company = $row['affiliate_company'];
                $this->aff_url = $row['affiliate_url'];
                $this->lastpaid_date = $row['recur_lastpaid'];
                $this->recur_period = $row['recur_period'];
                
                $sql_date = "SELECT date_format(DATE_ADD(?, INTERVAL ? MONTH),'%Y-%m-%d') as d";
                $stmt_date = $pdo->prepare($sql_date);
                $stmt_date->execute([$row['recur_lastpaid'], $row['recur_period']]);
                $row_date = $stmt_date->fetch();
                
                $this->recur_nextpay = $row_date['d'];
                $this->recur_status = $row['recur_status'];
                $this->recur_balance = $row['recur_balanceamt'];
                $this->trans_orderid = $row['transaction_orderid'];
                $this->sale_amount = $row['revenue_amount'];
                $this->total_comm = $row['recur_totalcommission'];
                $this->recur_period = $row['recur_period'];
                $this->trans_date = $row['transaction_dateoftransaction'];
                $this->recur_id = $row['recur_id'];
                $this->join_id = $row['joinpgm_id'];
                $this->recur_subsale = $row['recur_total_subsalecommission'];
                $this->recur_bal_subsale = $row['recur_balance_subsaleamt'];
                
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("getRecurTransDetails Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Pay the Recurring commission to the Affiliate and to the admin if the payment is 
    first installment of the recurring commission.  Called on the click of Approve this Commision link
    -------------------------------------------------------------------------------------------*/
    function RecurCommissionPayment($recur_pay_id, $mid, $cut_off)
    {
        global $pdo;
        
        try {
            $sql = "SELECT * FROM partners_affiliate A, partners_transaction T, partners_recur R, partners_recurpayments P, 
                    partners_joinpgm J 
                    WHERE P.recurpayments_id = ? AND P.recurpayments_recurid = R.recur_id AND 
                    R.recur_transactionid = T.transaction_id AND T.transaction_joinpgmid = J.joinpgm_id AND 
                    J.joinpgm_affiliateid = A.affiliate_id AND T.transaction_recur ='1' AND J.joinpgm_merchantid = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$recur_pay_id, $mid]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $transId = $row['transaction_id'];
                $amount = $row['recurpayments_amount'];
                $aid = $row['affiliate_id'];
                $flag = $row['transaction_flag'];
                $parentid = $row['transaction_parentid'];
                $subsale = $row['recurpayments_subsaleamount'];
                $admin_sale_comm = $row['transaction_admin_amount'];
                $admin_paydate = $row['transaction_adminpaydate'];
                $today = date('Y-m-d');
                
                if($admin_paydate != "0000-00-00") {
                    $admin_sale_comm = 0;
                } else {
                    $admin_pay_sql = "UPDATE partners_transaction SET transaction_adminpaydate = ? WHERE transaction_id = ?";
                    $stmt_admin = $pdo->prepare($admin_pay_sql);
                    $stmt_admin->execute([$today, $transId]);
                }
            }
            
            $sql_mer = "SELECT * FROM merchant_pay WHERE pay_merchantid = ?";
            $stmt_mer = $pdo->prepare($sql_mer);
            $stmt_mer->execute([$mid]);
            
            if($row_mer = $stmt_mer->fetch()) {
                $merchant_balance = $row_mer['pay_amount'];
                
                if(($merchant_balance - $amount - $admin_sale_comm) <= $cut_off) {
                    return false;
                } else {
                    // Add money to affiliate account
                    $merchant_balance = $merchant_balance - $amount - $admin_sale_comm;
                    
                    $sql_aff = "SELECT * FROM affiliate_pay WHERE pay_affiliateid = ?";
                    $stmt_aff = $pdo->prepare($sql_aff);
                    $stmt_aff->execute([$aid]);
                    
                    if($stmt_aff->rowCount() > 0) {
                        $row_aff = $stmt_aff->fetch();
                        $curamount = $row_aff['pay_amount'] + $amount;
                        
                        $sql2 = "UPDATE affiliate_pay SET pay_amount = ? WHERE pay_affiliateid = ?";
                        $stmt2 = $pdo->prepare($sql2);
                        $stmt2->execute([$curamount, $aid]);
                    } else {
                        $sql2 = "INSERT INTO affiliate_pay (pay_affiliateid, pay_amount) VALUES (?, ?)";
                        $stmt2 = $pdo->prepare($sql2);
                        $stmt2->execute([$aid, $amount]);
                    }
                    
                    // Subtract money from merchant account
                    $sql_mpay = "UPDATE merchant_pay SET pay_amount = ? WHERE pay_merchantid = ?";
                    $stmt_mpay = $pdo->prepare($sql_mpay);
                    $stmt_mpay->execute([$merchant_balance, $mid]);
                    $_SESSION['MERCHANTBALANCE'] = $merchant_balance;
                    
                    // Handle admin and subsale amounts
                    $sql1 = "SELECT * FROM admin_pay";
                    $stmt1 = $pdo->prepare($sql1);
                    $stmt1->execute();
                    
                    if($row1 = $stmt1->fetch()) {
                        $admin_curamount = $row1['pay_amount'];
                        $admin_curamount = ($admin_curamount + $admin_sale_comm) - $subsale;
                        
                        $sql_admin = "UPDATE admin_pay SET pay_amount = ?";
                        $stmt_admin = $pdo->prepare($sql_admin);
                        $stmt_admin->execute([$admin_curamount]);
                        
                        if($flag == 1) {
                            $sql_parent = "SELECT * FROM affiliate_pay WHERE pay_affiliateid = ?";
                            $stmt_parent = $pdo->prepare($sql_parent);
                            $stmt_parent->execute([$parentid]);
                            
                            if($stmt_parent->rowCount() > 0) {
                                $row_parent = $stmt_parent->fetch();
                                $parent_amount = $row_parent['pay_amount'] + $subsale;
                                
                                $sql_parent_update = "UPDATE affiliate_pay SET pay_amount = ? WHERE pay_affiliateid = ?";
                                $stmt_parent_update = $pdo->prepare($sql_parent_update);
                                $stmt_parent_update->execute([$parent_amount, $parentid]);
                            }
                        }
                    }
                    
                    // Record successful payment
                    $today = date("Y-m-d");
                    if($amount > 0) {
                        $sql3 = "INSERT INTO partners_adjustment (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) 
                                VALUES (?, 'programFee', 'm', ?, ?, ?)";
                        $stmt3 = $pdo->prepare($sql3);
                        $stmt3->execute([$mid, $amount, $today, $row['joinpgm_programid']]);
                    }
                    
                    $sql4 = "INSERT INTO partners_fee (adjust_memberid, adjust_action, adjust_flag, adjust_amount, adjust_date, adjust_no) 
                            VALUES (?, 'programFee', 'closed', ?, ?, ?)";
                    $stmt4 = $pdo->prepare($sql4);
                    $stmt4->execute([$mid, $amount, $today, $row['joinpgm_programid']]);
                }
            }
            return true;
        } catch (PDOException $e) {
            error_log("RecurCommissionPayment Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Update the recurring period of a particular Recurring transaction
    -------------------------------------------------------------------------------------------*/
    function UpdateRecurPeriod($transid, $period)
    {
        global $pdo;
        
        try {
            $sql_trans = "SELECT * FROM partners_transaction T, partners_recur R 
                         WHERE T.transaction_id = ? AND R.recur_transactionid = T.transaction_id AND T.transaction_recur='1'";
            $stmt_trans = $pdo->prepare($sql_trans);
            $stmt_trans->execute([$transid]);
            
            if($stmt_trans->rowCount() > 0) {
                $row_trans = $stmt_trans->fetch();
                $recur_id = $row_trans['recur_id'];
                
                $sql_update = "UPDATE partners_recur SET recur_period = ? WHERE recur_id = ?";
                $stmt_update = $pdo->prepare($sql_update);
                $stmt_update->execute([$period, $recur_id]);
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("UpdateRecurPeriod Error: " . $e->getMessage());
            return false;
        }
    }

    function rejectRecurTransaction($recurId)
    {
        global $pdo;
        
        try {
            $sql_status = "UPDATE partners_recur SET recur_status='Rejected' WHERE recur_id = ?";
            $stmt_status = $pdo->prepare($sql_status);
            $stmt_status->execute([$recurId]);
            return true;
        } catch (PDOException $e) {
            error_log("rejectRecurTransaction Error: " . $e->getMessage());
            return false;
        }
    }
}

//********* End Class recur  *******************************

//********* Start of Class Graphs  *******************************
//********* Start of Class Graphs  *******************************
class graphs
{
    // Declare ALL properties here to avoid dynamic property deprecation warnings
    public $merId = array();
    public $merCompany = array();
    public $affId = array();
    public $affCompany = array();
    public $affClick = array();
    public $affSale = array();
    public $affCommn = array();
    public $pgmId = array();
    public $pgmName = array();
    
    // Properties for FindReturnDays function
    public $total_sameday = 0;
    public $total_15Day = 0;
    public $total_1Month = 0;
    public $total_2Month = 0;
    public $total_After = 0;
    public $total = 0;
    public $rowcount = 0;
    
    // Properties for FindPerformanceAffiliateGroup
    public $groupCount = array();
    
    // Properties for FindAffiliateClickPercentage
    public $total_sale = 0;
    
    // Properties for GetBubbleReport
    public $maxcomm = 0;

    /*-------------------------------------------------------------------------------------------
    Function to get the names of all affiliates joined for the Merchant
    -------------------------------------------------------------------------------------------*/
    function GetAffiliates($mid)
    {
        global $pdo;
        
        // Initialize properties
        $this->aff_id = array();
        $this->aff_comp = array();
        
        $sql = "SELECT DISTINCT affiliate_id, affiliate_company FROM partners_affiliate, partners_joinpgm 
                WHERE affiliate_id=joinpgm_affiliateid AND joinpgm_merchantid=? AND joinpgm_status='approved'";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$mid]);
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->aff_id[] = $row['affiliate_id'];
                    $this->aff_comp[] = $row['affiliate_company'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("GetAffiliates Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the return day values for the respective period for the selected Affiliate
    -------------------------------------------------------------------------------------------*/
    function FindReturnDays($aid="All", $mid)
    {
        global $pdo;
        
        // Initialize properties
        $this->total_sameday = 0;
        $this->total_15Day = 0;
        $this->total_1Month = 0;
        $this->total_2Month = 0;
        $this->total_After = 0;
        $this->total = 0;
        
        $total_sameday = $total_15Day = $total_1Month = $total_2Month = $total_After = 0;
        
        if($aid == "All") {
            $affiliate_sql = "";
        } else {
            $affiliate_sql = " AND joinpgm_affiliateid=? ";
        }
        
        $sql = "SELECT DISTINCT transaction_linkid, transaction_joinpgmid FROM partners_transaction, partners_joinpgm 
                WHERE joinpgm_merchantid=? AND joinpgm_id=transaction_joinpgmid AND transaction_type='click'";
        
        if($aid != "All") {
            $sql .= $affiliate_sql;
        }
        
        try {
            $stmt = $pdo->prepare($sql);
            if($aid != "All") {
                $stmt->execute([$mid, $aid]);
            } else {
                $stmt->execute([$mid]);
            }
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $clickdate = $saledate = "";
                    $linkId = $row['transaction_linkid'];
                    $joinId = $row['transaction_joinpgmid'];
                    
                    // Find first click date
                    $sql_click = "SELECT DISTINCT transaction_dateoftransaction FROM partners_transaction, partners_joinpgm 
                                 WHERE joinpgm_merchantid=? AND joinpgm_id=? AND joinpgm_id=transaction_joinpgmid AND 
                                 transaction_linkid=? AND transaction_type='click'";
                    if($aid != "All") {
                        $sql_click .= " AND joinpgm_affiliateid=?";
                    }
                    $sql_click .= " ORDER BY transaction_dateoftransaction ASC";
                    
                    $stmt_click = $pdo->prepare($sql_click);
                    if($aid != "All") {
                        $stmt_click->execute([$mid, $joinId, $linkId, $aid]);
                    } else {
                        $stmt_click->execute([$mid, $joinId, $linkId]);
                    }
                    
                    if($row_click = $stmt_click->fetch()) {
                        $clickdate = $row_click['transaction_dateoftransaction'];
                    }
                    
                    // Find first sale date
                    $sql_sale = "SELECT DISTINCT transaction_dateoftransaction FROM partners_transaction, partners_joinpgm 
                                WHERE joinpgm_merchantid=? AND joinpgm_id=? AND joinpgm_id=transaction_joinpgmid AND 
                                transaction_linkid=? AND transaction_type='sale'";
                    if($aid != "All") {
                        $sql_sale .= " AND joinpgm_affiliateid=?";
                    }
                    $sql_sale .= " ORDER BY transaction_dateoftransaction ASC";
                    
                    $stmt_sale = $pdo->prepare($sql_sale);
                    if($aid != "All") {
                        $stmt_sale->execute([$mid, $joinId, $linkId, $aid]);
                    } else {
                        $stmt_sale->execute([$mid, $joinId, $linkId]);
                    }
                    
                    if($row_sale = $stmt_sale->fetch()) {
                        $saledate = $row_sale['transaction_dateoftransaction'];
                    }
                    
                    // Calculate time difference
                    if($clickdate && $saledate) {
                        if($clickdate == $saledate) {
                            $total_sameday += 1;
                        } else {
                            $click_datetime = new DateTime($clickdate);
                            $sale_datetime = new DateTime($saledate);
                            $interval = $click_datetime->diff($sale_datetime);
                            $days = $interval->days;
                            
                            if($days <= 15) {
                                $total_15Day += 1;
                            } elseif($days <= 30) {
                                $total_1Month += 1;
                            } elseif($days <= 60) {
                                $total_2Month += 1;
                            } else {
                                $total_After += 1;
                            }
                        }
                    }
                }
            }
            
            $total = $total_sameday + $total_15Day + $total_1Month + $total_2Month + $total_After;
            if($total > 0) {
                $this->total_sameday = ($total_sameday / $total) * 100;
                $this->total_15Day = ($total_15Day / $total) * 100;
                $this->total_1Month = ($total_1Month / $total) * 100;
                $this->total_2Month = ($total_2Month / $total) * 100;
                $this->total_After = ($total_After / $total) * 100;
            } else {
                $this->total_sameday = $this->total_15Day = $this->total_1Month = $this->total_2Month = $this->total_After = 0;
            }
            $this->total = $total;
            
        } catch (PDOException $e) {
            error_log("FindReturnDays Error: " . $e->getMessage());
        }
    }

     /*-------------------------------------------------------------------------------------------
    Function to get all the Programs of the Merchant
    -------------------------------------------------------------------------------------------*/
    function GetAllPrograms($mid)
    {
        global $pdo;
        
        // Initialize properties
        $this->pgmId = array();
        $this->pgmName = array();
        
        $sql = "SELECT DISTINCT program_id, program_url FROM partners_program WHERE program_merchantid=?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$mid]);
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->pgmId[] = $row['program_id'];
                    $this->pgmName[] = $row['program_url'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("GetAllPrograms Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Find the number of clicks and sales made by the Affiliates of a Merchant for a 
    selected Program or for all the programs
    -------------------------------------------------------------------------------------------*/
    function FindAffiliateClickPercentage($mid, $pgmid, $from, $to)
    {
        global $pdo;
        
        // Initialize properties
        $this->affId = array();
        $this->affCompany = array();
        $this->affClick = array();
        $this->affSale = array();
        $this->rowcount = 0;
        $this->total = 0;
        $this->total_sale = 0;
        
        $count = 0;
        $total = $total_sale = "0,";
        
        $sql = "SELECT DISTINCT affiliate_id, affiliate_company FROM partners_joinpgm, partners_affiliate 
                WHERE joinpgm_merchantid=? AND joinpgm_affiliateid=affiliate_id";
        
        if($pgmid != "All") {
            $sql .= " AND joinpgm_programid=?";
        }
        
        try {
            $stmt = $pdo->prepare($sql);
            if($pgmid != "All") {
                $stmt->execute([$mid, $pgmid]);
            } else {
                $stmt->execute([$mid]);
            }
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $count += 1;
                    $aff_id = $row['affiliate_id'];
                    $aff_name = $row['affiliate_company'];
                    
                    $sql_common = " FROM partners_transaction, partners_joinpgm WHERE 
                                  transaction_joinpgmid=joinpgm_id AND 
                                  joinpgm_merchantid=? AND joinpgm_affiliateid=?";
                    if($pgmid != "All") {
                        $sql_common .= " AND joinpgm_programid=?";
                    }
                    if($from != "" && $to != "") {
                        $sql_common .= " AND transaction_dateoftransaction BETWEEN ? AND ?";
                    }

                    // Get clicks
                    $sql_affiliate = "SELECT COUNT(transaction_id) as clicks " . $sql_common . " AND transaction_type='click'";
                    $stmt_affiliate = $pdo->prepare($sql_affiliate);
                    
                    $params = [$mid, $aff_id];
                    if($pgmid != "All") $params[] = $pgmid;
                    if($from != "" && $to != "") {
                        $params[] = $from;
                        $params[] = $to;
                    }
                    
                    $stmt_affiliate->execute($params);
                    if($row_affiliate = $stmt_affiliate->fetch()) {
                        $this->affClick[] = $row_affiliate['clicks'];
                        $total .= $row_affiliate['clicks'] . ",";
                    }

                    // Get sales
                    $sql_sale = "SELECT COUNT(transaction_id) as sales " . $sql_common . " AND transaction_type='sale'";
                    $stmt_sale = $pdo->prepare($sql_sale);
                    $stmt_sale->execute($params);
                    
                    if($row_sale = $stmt_sale->fetch()) {
                        $this->affSale[] = $row_sale['sales'];
                        $total_sale .= $row_sale['sales'] . ",";
                    }
                    
                    $this->affId[] = $aff_id;
                    $this->affCompany[] = $aff_name;
                }
                
                $total = trim($total, ",");
                if($total != "") {
                    $numbers = explode(",", $total);
                    $this->total = max($numbers);
                }
                
                $total_sale = trim($total_sale, ",");
                if($total_sale != "") {
                    $numbers = explode(",", $total_sale);
                    $this->total_sale = max($numbers);
                }
                
                $this->rowcount = $count;
            }
        } catch (PDOException $e) {
            error_log("FindAffiliateClickPercentage Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Find the performance of the Affiliate Groups (top 10, 11-20, 21-50, 51-75 and above) 
    for clicks sales and commmission
    -------------------------------------------------------------------------------------------*/
    function FindPerformanceAffiliateGroup($mid, $type)
    {
        global $pdo;
        
        // Initialize properties
        $this->groupCount = array();
        $this->total = 0;
        
        $sql_common = "SELECT DISTINCT affiliate_id, affiliate_company FROM partners_joinpgm, partners_affiliate 
                      WHERE joinpgm_merchantid=? AND joinpgm_affiliateid=affiliate_id";
        
        try {
            $stmt_common = $pdo->prepare($sql_common);
            $stmt_common->execute([$mid]);
            $totalcount = $stmt_common->rowCount();
            
            $limitArr = array(10, 20, 50, 75, $totalcount);
            $start = $end = $total = 0;
            
            for($i = 0; $i < count($limitArr); $i++) {
                $value = 0;
                $end = $limitArr[$i];
                $sql = $sql_common . " LIMIT " . $start . ", " . $end;
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$mid]);
                
                if($stmt->rowCount() > 0) {
                    while($row = $stmt->fetch()) {
                        $aff_id = $row['affiliate_id'];
                        
                        if($type != 'commission') {
                            $sql_affiliate = "SELECT COUNT(transaction_id) as CNT ";
                        } else {
                            $sql_affiliate = "SELECT SUM(transaction_amttobepaid) as CNT ";
                        }
                        
                        $sql_affiliate .= "FROM partners_transaction, partners_joinpgm 
                                          WHERE transaction_joinpgmid=joinpgm_id AND 
                                          joinpgm_merchantid=? AND joinpgm_affiliateid=?";
                        
                        if($type != 'commission') {
                            $sql_affiliate .= " AND transaction_type=?";
                        }
                        
                        $stmt_affiliate = $pdo->prepare($sql_affiliate);
                        
                        if($type != 'commission') {
                            $stmt_affiliate->execute([$mid, $aff_id, $type]);
                        } else {
                            $stmt_affiliate->execute([$mid, $aff_id]);
                        }
                        
                        if($row_affiliate = $stmt_affiliate->fetch()) {
                            $value += $row_affiliate['CNT'];
                        }
                    }
                }
                
                $start = $end;
                $total += $value;
                $this->groupCount[] = $value;
                
                if($start > $totalcount) break;
            }
            
            $this->total = $total;
        } catch (PDOException $e) {
            error_log("FindPerformanceAffiliateGroup Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Find the clicks or sales made by the Affiliates of the merchnat and also to get the
    commission earned by them
    -------------------------------------------------------------------------------------------*/
    function GetBubbleReport($mid, $pgmid, $from, $to, $type)
    {
        global $pdo;
        
        $count = 0;
        $total = $max_comm = "0,";
        
        $sql = "SELECT DISTINCT affiliate_id, affiliate_company FROM partners_joinpgm, partners_affiliate 
                WHERE joinpgm_merchantid=? AND joinpgm_affiliateid=affiliate_id";
        
        if($pgmid != "All") {
            $sql .= " AND joinpgm_programid=?";
        }
        
        try {
            $stmt = $pdo->prepare($sql);
            if($pgmid != "All") {
                $stmt->execute([$mid, $pgmid]);
            } else {
                $stmt->execute([$mid]);
            }
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $count += 1;
                    $aff_id = $row['affiliate_id'];
                    $aff_name = $row['affiliate_company'];
                    
                    $sql_common = "FROM partners_transaction, partners_joinpgm 
                                  WHERE transaction_joinpgmid=joinpgm_id AND 
                                  joinpgm_merchantid=? AND joinpgm_affiliateid=?";
                    if($pgmid != "All") {
                        $sql_common .= " AND joinpgm_programid=?";
                    }
                    if($from != "" && $to != "") {
                        $sql_common .= " AND transaction_dateoftransaction BETWEEN ? AND ?";
                    }

                    $sql_affiliate = "SELECT COUNT(transaction_id) as clicks, SUM(transaction_amttobepaid) as amount 
                                     " . $sql_common . " AND transaction_type=?";
                    
                    $stmt_affiliate = $pdo->prepare($sql_affiliate);
                    
                    $params = [$mid, $aff_id];
                    if($pgmid != "All") $params[] = $pgmid;
                    if($from != "" && $to != "") {
                        $params[] = $from;
                        $params[] = $to;
                    }
                    $params[] = $type;
                    
                    $stmt_affiliate->execute($params);
                    
                    if($row_affiliate = $stmt_affiliate->fetch()) {
                        $this->affClick[] = $row_affiliate['clicks'];
                        $this->affCommn[] = $row_affiliate['amount'];
                        $total .= $row_affiliate['clicks'] . ",";
                        
                        if($row_affiliate['amount'] > 0) {
                            $max_comm .= $row_affiliate['amount'] . ",";
                        } else {
                            $max_comm .= "0,";
                        }
                    }
                    
                    $this->affId[] = $aff_id;
                    $this->affCompany[] = $aff_name;
                }
                
                $total = trim($total, ",");
                if($total != "") {
                    $numbers = explode(",", $total);
                    $this->total = max($numbers);
                }
                
                $max_comm = trim($max_comm, ",");
                if($max_comm != "") {
                    $numbers = explode(",", $max_comm);
                    $this->maxcomm = max($numbers);
                }
                
                $this->rowcount = $count;
            }
        } catch (PDOException $e) {
            error_log("GetBubbleReport Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get all the Merchants
    -------------------------------------------------------------------------------------------*/
    function GetAllMerchants()
    {
        global $pdo;
        
        // Initialize properties
        $this->merId = array();
        $this->merCompany = array();
        
        $sql = "SELECT * FROM partners_merchant";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->merId[] = $row['merchant_id'];
                    $this->merCompany[] = $row['merchant_company'];
                }
                return true;
            }
            return false;
        } catch (PDOException $e) {
            error_log("GetAllMerchants Error: " . $e->getMessage());
            return false;
        }
    }
}

//********* End Class Graphs  *******************************

//********* Start Class AdminUser  *******************************
class adminuser
{
    /*-------------------------------------------------------------------------------------------
    Function to get all the Admin users except Super Admin
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function getAllAdminUsers()
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_adminusers WHERE adminusers_id != '1'";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->userid[] = $row['adminusers_id'];
                    $this->username[] = $row['adminusers_login'];
                    $this->email[] = $row['adminusers_email'];
                    $this->password[] = $row['adminusers_password'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("getAllAdminUsers Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get all the Admin users except Super Admin
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function AddAdminUser($username, $email, $password)
    {
        global $pdo;
        
        try {
            $sql = "INSERT INTO partners_adminusers SET 
                   adminusers_login = ?,
                   adminusers_email = ?,
                   adminusers_password = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$username, $email, $password]);
            return true;
        } catch (PDOException $e) {
            error_log("AddAdminUser Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to check if the email id already exists
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function IsEmailexists($email, $id='')
    {
        global $pdo;
        
        try {
            if($id == '') {
                $sql = "SELECT * FROM partners_adminusers WHERE adminusers_email = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$email]);
            } else {
                $sql = "SELECT * FROM partners_adminusers WHERE adminusers_email = ? AND adminusers_id != ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$email, $id]);
            }
            
            return $stmt->rowCount() == 0;
        } catch (PDOException $e) {
            error_log("IsEmailexists Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to check if the user name already exists
    Created By    :     SMA
    Created On     :     11-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function IsUserNameExists($user, $id='')
    {
        global $pdo;
        
        try {
            if($id == '') {
                $sql = "SELECT * FROM partners_adminusers WHERE adminusers_login = ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$user]);
            } else {
                $sql = "SELECT * FROM partners_adminusers WHERE adminusers_login = ? AND adminusers_id != ?";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$user, $id]);
            }
            
            return $stmt->rowCount() == 0;
        } catch (PDOException $e) {
            error_log("IsUserNameExists Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to update Admin user details
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function UpdateAdminUser($id, $username, $email, $password)
    {
        global $pdo;
        
        try {
            $sql = "UPDATE partners_adminusers SET 
                   adminusers_email = ?,
                   adminusers_password = ?,
                   adminusers_login = ?
                   WHERE adminusers_id = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$email, $password, $username, $id]);
            return true;
        } catch (PDOException $e) {
            error_log("UpdateAdminUser Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Delete Admin user details
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function DeleteAdminUser($id)
    {
        global $pdo;
        
        try {
            $sql = "DELETE FROM partners_adminusers WHERE adminusers_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            return true;
        } catch (PDOException $e) {
            error_log("DeleteAdminUser Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Mailing get details of Super Admin
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function GetSuperAdmin()
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_admin";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $this->admin_email = $row['admin_email'];
                $this->admin_header = $row['admin_mailheader'];
                $this->admin_footer = $row['admin_mailfooter'];
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("GetSuperAdmin Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the details of the selecte ADMIN User
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function GetAdimUserDetails($id)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_adminusers WHERE adminusers_id = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $this->username = $row['adminusers_login'];
                $this->email = $row['adminusers_email'];
                $this->password = $row['adminusers_password'];
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("GetAdimUserDetails Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the links available for Admin and the previleges for the diffrerent ADMIN Users
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function GetAdminLiks($parent)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_adminlinks WHERE adminlinks_parentid = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$parent]);
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->linkid[] = $row['adminlinks_id'];
                    $this->linktitle[] = $row['adminlinks_title'];
                    $this->linkparent[] = $row['adminlinks_parentid'];
                    $this->linkusers[] = $row['adminlinks_userid'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("GetAdminLiks Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the all the details of all the links for Admin Section
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function GetAllAdminLinks()
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_adminlinks";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->linkid[] = $row['adminlinks_id'];
                    $this->linktitle[] = $row['adminlinks_title'];
                    $this->linkparent[] = $row['adminlinks_parentid'];
                    $this->linkusers[] = $row['adminlinks_userid'];
                }
            }
        } catch (PDOException $e) {
            error_log("GetAllAdminLinks Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Update the User Privilege for a selected Link
    Created By    :     SMA
    Created On     :     11-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function UpdateAdminUserLinks($linkid, $users)
    {
        global $pdo;
        
        try {
            $sql = "UPDATE partners_adminlinks SET adminlinks_userid = ? WHERE adminlinks_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$users, $linkid]);
        } catch (PDOException $e) {
            error_log("UpdateAdminUserLinks Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to send mail to the Admin User on adding and updating details
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function SendMailtoAdminUser($to, $subject, $from, $adminheader, $username, $password, $adminfooter)
    {
        $headers = "Content-Type: text/html; charset=iso-8859-1\n";
        $headers .= "From: $from\n";
        
        $body = "<table border='0' cellpadding='0' cellspacing='0' width='90%'>
                <tr><td width='100%' align='center' valign='top'><br/>
                <table border='0' cellpadding='0' cellspacing='0' width='80%'>
                <tr><td width='100%' align='center'>$adminheader</td></tr>
                <tr><td width='100%' align='left'>&nbsp;</td></tr>
                <tr><td width='100%' align='left'>Your Admin User name is = $username</td></tr>
                <tr><td width='100%' align='left'>Your Password Is = $password</td></tr>
                <tr><td width='100%' align='left'>&nbsp;</td></tr>
                <tr><td width='100%' align='center'>$adminfooter</td></tr>
                </table></td></tr></table>";

        mail($to, $subject, $body, $headers);
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the user details of the selected link
    Created By    :     SMA
    Created On     :     10-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function GetAdminUserLink($linkName, $adminUserId, $parent)
    {
        global $pdo;
        
        if($adminUserId != '1') {
            $sql = "SELECT * FROM partners_adminlinks WHERE adminlinks_title = ? AND adminlinks_parentid = ?";
            
            try {
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$linkName, $parent]);
                
                if($row = $stmt->fetch()) {
                    $linkusers = $row['adminlinks_userid'];
                    $users = explode(",", $linkusers);
                    return in_array($adminUserId, $users);
                }
                return false;
            } catch (PDOException $e) {
                error_log("GetAdminUserLink Error: " . $e->getMessage());
                return false;
            }
        } else {
            return true;
        }
    }
}

//********* End Class AdminUser  *******************************

//********* Start Class Report  *******************************
class report
{
    function FindMerchantName($id)
    {
        global $pdo;
        $merchantName = "";
        
        try {
            $sql = "SELECT merchant_company FROM partners_merchant WHERE merchant_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($row = $stmt->fetch()) {
                $merchantName = $row['merchant_company'];
            }
        } catch (PDOException $e) {
            error_log("FindMerchantName Error: " . $e->getMessage());
        }
        return $merchantName;
    }
    
    function FindAffiliateName($id)
    {
        global $pdo;
        $affiliateName = "";
        
        try {
            $sql = "SELECT affiliate_company FROM partners_affiliate WHERE affiliate_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($row = $stmt->fetch()) {
                $affiliateName = $row['affiliate_company'];
            }
        } catch (PDOException $e) {
            error_log("FindAffiliateName Error: " . $e->getMessage());
        }
        return $affiliateName;
    }
    
    function FindProgramName($id)
    {
        global $pdo;
        $program = "";
        
        try {
            $sql = "SELECT program_url FROM partners_program WHERE program_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($row = $stmt->fetch()) {
                $program = $row['program_url'];
            }
        } catch (PDOException $e) {
            error_log("FindProgramName Error: " . $e->getMessage());
        }
        return $program;
    }
}

//********* End Class Report  *******************************

//********* Start Class MerchantLink *******************************
class merchantLink
{
    /*-------------------------------------------------------------------------------------------
    Function to get the header and footer details of the merchant
    Created By    :     SMA
    Created On     :     25-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function merchantSignUpLink($id)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_merchant WHERE merchant_id = ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch();
                $this->mer_header = $row['merchant_headercode'];
                $this->mer_footer = $row['merchant_footercode'];
            }
        } catch (PDOException $e) {
            error_log("merchantSignUpLink Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to update the header and footer details of the merchant
    Created By    :     SMA
    Created On     :     25-JULY-2006
    -------------------------------------------------------------------------------------------*/
    function UpdateLinks($id, $header, $footer)
    {
        global $pdo;
        
        try {
            $sql = "UPDATE partners_merchant SET 
                   merchant_headercode = ?,
                   merchant_footercode = ?
                   WHERE merchant_id = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$header, $footer, $id]);
            return true;
        } catch (PDOException $e) {
            error_log("UpdateLinks Error: " . $e->getMessage());
            return false;
        }
    }
}

//********* End Class MerchantLink  *******************************

//********* Start Class Currency  *******************************
class currency
{
    /*-------------------------------------------------------------------------------------------
    Function to find if the Currency details already exists
    Created By    :     SMA
    Created On     :     4-AUG-2006
    -------------------------------------------------------------------------------------------*/
    function ifCurrencyDetailsExists($type, $value)
    {
        global $pdo;
        
        try {
            $sql = "SELECT * FROM partners_currency WHERE currency_$type = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$value]);
            
            return $stmt->rowCount() == 0;
        } catch (PDOException $e) {
            error_log("ifCurrencyDetailsExists Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Add New Currency details
    Created By    :     SMA
    Created On     :     4-AUG-2006
    -------------------------------------------------------------------------------------------*/
    function insertCurrency($caption, $code, $symbol, $relation)
    {
        global $pdo;
        
        try {
            $sql = "INSERT INTO partners_currency SET 
                   currency_caption = ?,
                   currency_code = ?,
                   currency_symbol = ?";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$caption, $code, $symbol]);
            
            if($stmt->rowCount() > 0) {
                $today = date('Y-m-d');
                $sql_rel = "INSERT INTO partners_currency_relation SET 
                           relation_currency_code = ?,
                           relation_value = ?,
                           relation_date = ?";
                
                $stmt_rel = $pdo->prepare($sql_rel);
                $stmt_rel->execute([$code, $relation, $today]);
                return $stmt_rel->rowCount() > 0;
            }
            return false;
        } catch (PDOException $e) {
            error_log("insertCurrency Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to Change the values of Amounts in the tables on the chage of the Base Currency
    Created By    :     SMA
    Created On     :     7-AUG-2006
    -------------------------------------------------------------------------------------------*/
    function ConvertToNewBaseCurrency($newCode)
    {
        global $pdo;
        
        try {
            $sql = "SELECT * FROM partners_currency, partners_currency_relation 
                    WHERE currency_code = ? AND currency_code = relation_currency_code 
                    ORDER BY relation_date DESC";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$newCode]);
            
            if($row = $stmt->fetch()) {
                $currRelation = $row['relation_value'];
                
                // Update all tables with currency conversion
                $tables = [
                    "admin_pay" => "pay_amount = pay_amount * $currRelation",
                    "affiliate_pay" => "pay_amount = pay_amount * $currRelation",
                    "merchant_pay" => "pay_amount = pay_amount * $currRelation",
                    "partners_addmoney" => "addmoney_amount = addmoney_amount * $currRelation",
                    "partners_adjustment" => "adjust_amount = adjust_amount * $currRelation",
                    "partners_fee" => "adjust_amount = adjust_amount * $currRelation",
                    "partners_program" => "program_impressionrate = program_impressionrate * $currRelation, 
                                          program_clickrate = program_clickrate * $currRelation",
                    "partners_pgm_commission" => "commission_leadrate = commission_leadrate * $currRelation",
                    "partners_group" => "group_clickrate = group_clickrate * $currRelation, 
                                       group_leadrate = group_leadrate * $currRelation",
                    "partners_invoice" => "invoice_amount = invoice_amount * $currRelation",
                    "partners_ipblocking" => "ipblocking_click = ipblocking_click * $currRelation, 
                                            ipblocking_lead = ipblocking_lead * $currRelation",
                    "partners_payment" => "pay_amount = pay_amount * $currRelation",
                    "partners_recur" => "recur_totalcommission = recur_totalcommission * $currRelation, 
                                       recur_balanceamt = recur_balanceamt * $currRelation,
                                       recur_total_subsalecommission = recur_total_subsalecommission * $currRelation,
                                       recur_balance_subsaleamt = recur_balance_subsaleamt * $currRelation",
                    "partners_recurpayments" => "recurpayments_amount = recurpayments_amount * $currRelation,
                                               recurpayments_subsaleamount = recurpayments_subsaleamount * $currRelation",
                    "partners_request" => "request_amount = request_amount * $currRelation",
                    "partners_track_revenue" => "revenue_amount = revenue_amount * $currRelation",
                    "partners_transaction" => "transaction_amttobepaid = transaction_amttobepaid * $currRelation,
                                             transaction_amountpaid = transaction_amountpaid * $currRelation,
                                             transaction_subsale = transaction_subsale * $currRelation,
                                             transaction_reverseamount = transaction_reverseamount * $currRelation,
                                             transaction_adminpaid = transaction_adminpaid * $currRelation,
                                             transaction_subsalepaid = transaction_subsalepaid * $currRelation"
                ];
                
                foreach ($tables as $table => $update) {
                    $update_sql = "UPDATE $table SET $update";
                    $pdo->exec($update_sql);
                }
                
                // Update percentage-based commissions separately
                $pdo->exec("UPDATE partners_pgm_commission SET commission_salerate = commission_salerate * $currRelation 
                           WHERE commission_saletype != '%'");
                $pdo->exec("UPDATE partners_ipblocking SET ipblocking_sale = ipblocking_sale * $currRelation 
                           WHERE ipblocking_saletype != '%'");
            }
        } catch (PDOException $e) {
            error_log("ConvertToNewBaseCurrency Error: " . $e->getMessage());
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to find the currency details of currrencies other than present Base Currency
    Created By    :     SMA
    Created On     :     8-AUG-2006
    -------------------------------------------------------------------------------------------*/
    function GetAllCurrencies($base)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_currency WHERE currency_code != ?";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$base]);
            
            if($stmt->rowCount() > 0) {
                while($row = $stmt->fetch()) {
                    $this->curCode[] = $row['currency_code'];
                    $this->curCaption[] = $row['currency_caption'];
                }
                return true;
            } else {
                return false;
            }
        } catch (PDOException $e) {
            error_log("GetAllCurrencies Error: " . $e->getMessage());
            return false;
        }
    }

    /*-------------------------------------------------------------------------------------------
    Function to get the present rate of a currency with respect to the Base currency
    -------------------------------------------------------------------------------------------*/
    function FindCurrentRate($currency)
    {
        global $pdo;
        
        $sql = "SELECT * FROM partners_currency_relation 
                WHERE relation_currency_code = ? ORDER BY relation_date DESC";
        
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$currency]);
            
            if($row = $stmt->fetch()) {
                $this->rate = $row['relation_value'];
            } else {
                $this->rate = 0;
            }
        } catch (PDOException $e) {
            error_log("FindCurrentRate Error: " . $e->getMessage());
            $this->rate = 0;
        }
    }
}

*-------------------------------------------------------------------------------------------
    Function to detect frauds
    --------------------------------------------------------------------------------------*/

class FraudDetector {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function flag($affiliateId, $transactionId, $type, $reason, $severity = 'medium') {
        $sql = "INSERT INTO partners_fraud_flags 
                (affiliate_id, transaction_id, flag_type, flag_reason, severity)
                VALUES (?, ?, ?, ?, ?)";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$affiliateId, $transactionId, $type, $reason, $severity]);
    }

    public function getFlags($resolved = false) {
        $sql = "SELECT * FROM partners_fraud_flags WHERE resolved = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$resolved ? 1 : 0]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function resolveFlag($id, $adminId) {
        $sql = "UPDATE partners_fraud_flags 
                SET resolved = 1, resolved_by = ?, resolved_at = NOW()
                WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$adminId, $id]);
    }
}

*-------------------------------------------------------------------------------------------
    Function for smartlinks
    --------------------------------------------------------------------------------------*/

class SmartLinkResolver {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function resolve($code, $geo, $device) {
        $sql = "SELECT * FROM partners_smartlinks WHERE smartlink_code = ? AND status = 'active'";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$code]);
        $rules = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($rules as $rule) {
            if ($this->matchGeo($geo, $rule['geo_target']) && $this->matchDevice($device, $rule['device_target'])) {
                return $this->getOfferUrl($rule['offer_id']);
            }
        }

        return $rules[0]['fallback_url'] ?? null;
    }

    private function matchGeo($geo, $target) {
        return in_array($geo, explode(',', $target));
    }

    private function matchDevice($device, $target) {
        return strtolower($device) === strtolower($target);
    }

    private function getOfferUrl($offerId) {
        $sql = "SELECT offer_url FROM partners_offers WHERE offer_id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$offerId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row['offer_url'] ?? null;
    }
}

*-------------------------------------------------------------------------------------------
    Function for import offers from other networks
    --------------------------------------------------------------------------------------*/

class OfferImporter {
    private $pdo;
    private $networkUrl;
    private $networkName;

    public function __construct($pdo, $networkUrl, $networkName) {
        $this->pdo = $pdo;
        $this->networkUrl = $networkUrl;
        $this->networkName = $networkName;
    }

    public function fetchOffers() {
        $json = @file_get_contents($this->networkUrl);
        if (!$json) {
            error_log("OfferImporter: Failed to fetch from $this->networkUrl");
            return [];
        }

        $offers = json_decode($json, true);
        return $offers['data'] ?? [];
    }

    public function import() {
        $offers = $this->fetchOffers();
        foreach ($offers as $offer) {
            $this->saveOffer($offer);
        }
    }

    private function saveOffer($offer) {
        $sql = "INSERT INTO partners_offers 
                (offer_title, offer_url, offer_payout, offer_currency, offer_geo, offer_device, offer_status, offer_source)
                VALUES (?, ?, ?, ?, ?, ?, 'active', ?)
                ON DUPLICATE KEY UPDATE 
                    offer_title = VALUES(offer_title),
                    offer_url = VALUES(offer_url),
                    offer_payout = VALUES(offer_payout),
                    offer_currency = VALUES(offer_currency),
                    offer_geo = VALUES(offer_geo),
                    offer_device = VALUES(offer_device)";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            $offer['title'] ?? 'Untitled',
            $offer['url'] ?? '',
            $offer['payout'] ?? 0.00,
            $offer['currency'] ?? 'USD',
            $offer['geo'] ?? '',
            $offer['device'] ?? '',
            $this->networkName
        ]);
    }
}

//********* End Class Currency  *******************************
?>