<?php
/************************************************************************/
/*     PROGRAMMER     :  SMA                                            */
/*     SCRIPT NAME    :  AffiliateGroup.php                             */
/*     CREATED ON     :  27/JULY/2009                                   */
/************************************************************************/

require_once("db_connection.php"); // Assumes a central DB connection script
$mysqli = db_connect(); // Get the mysqli connection

$mode     = $_REQUEST['mode'] ?? '';
$groupId  = $_REQUEST['groupId'] ?? '';
$msg      = $_REQUEST['msg'] ?? '';

if ($msg === "saved") {
    $msg = "Group Details Saved successfully!";
} elseif ($msg === "invalidId") {
    $msg = "Affiliate Group Id does not exist";
} elseif ($msg === "deleted") {
    $msg = "Affiliate Group deleted successfully!";
} elseif ($msg === "commissionSaved") {
    $msg = "Commission details saved successfully";
}
?>
<table cellpadding="0" cellspacing="0" border="0" align="center" width="95%" class="tablebdr">
    <tr><td height="30" valign="middle"><b>&nbsp;&raquo;&raquo;&nbsp;&nbsp;Affiliate Group Management</b></td></tr>
    <tr><td>

<?php
switch ($mode) {

    case "submit":
        $grouptitle = trim(strip_tags($_REQUEST['grouptitle'] ?? ''));
        $level      = (int) ($_REQUEST['level'] ?? 0);

        if (empty($grouptitle)) {
            $msg = "Please enter the title";
            include "AffiliateGroupForm.php";
            include "AffiliateGroupList.php";
        } elseif (ifGroupExists($grouptitle, $groupId, $mysqli)) {
            $msg = "Group Title already exists";
            include "AffiliateGroupForm.php";
            include "AffiliateGroupList.php";
        } elseif (saveAffiliateGroup($grouptitle, $level, $groupId, $mysqli)) {
            $msg = "saved";
            header("Location: index.php?Act=AffiliateGroup&msg=$msg");
            exit;
        } else {
            $msg = "Unknown Error. Operation Failed!!";
            include "AffiliateGroupForm.php";
            include "AffiliateGroupList.php";
        }
        break;

    case "edit":
        if ($groupId) {
            $groupDetails = getGroupDetails($groupId, $mysqli);
            if ($groupDetails) {
                $grouptitle = $groupDetails['grouptitle'];
                $level = $groupDetails['level'];
            } else {
                $msg = "invalidId";
                header("Location: index.php?Act=AffiliateGroup&msg=$msg");
                exit;
            }
        }
        include "AffiliateGroupForm.php";
        include "AffiliateGroupList.php";
        break;

    case "delete":
        if ($groupId) {
            if (groupAlreadyUsed($groupId, $mysqli)) {
                $msg = "The group is already assigned to Affiliates. Deletion not possible!!";
                include "AffiliateGroupForm.php";
                include "AffiliateGroupList.php";
            } elseif (deleteGroup($groupId, $mysqli)) {
                $msg = "deleted";
                header("Location: index.php?Act=AffiliateGroup&msg=$msg");
                exit;
            } else {
                $msg = "Unknown Error. Operation Failed!!";
                include "AffiliateGroupForm.php";
                include "AffiliateGroupList.php";
            }
        } else {
            include "AffiliateGroupForm.php";
            include "AffiliateGroupList.php";
        }
        break;

    case "setCommission":
        $groupDetails = getGroupDetails($groupId, $mysqli);
        $commisionDetails = GetGroupCommission($groupId, $mysqli);
        include "AffiliateGroupCommission.php";
        break;

    case "submitCommission":
        $groupDetails = getGroupDetails($groupId, $mysqli);
        $error = 0;
        $commisionDetails = [];

        for ($i = 1; $i <= $groupDetails['level']; $i++) {
            $commission = $_REQUEST["txt_commission_$i"] ?? '';
            $type = $_REQUEST["radio_type_$i"] ?? '';

            if (!is_numeric($commission)) {
                $error = 1;
            } elseif ($type === "percentage" && $commission > 100) {
                $error = 2;
            }

            $commisionDetails[$i] = [
                'commission' => (float)$commission,
                'type' => $type
            ];
        }

        if ($error !== 0) {
            $msg = "Please enter a valid amount for commission";
            include "AffiliateGroupCommission.php";
        } elseif (SaveGroupCommission($groupId, $commisionDetails, $mysqli)) {
            $msg = "commissionSaved";
            header("Location: index.php?Act=AffiliateGroup&msg=$msg");
            exit;
        } else {
            include "AffiliateGroupCommission.php";
        }
        break;

    default:
        include "AffiliateGroupForm.php";
        include "AffiliateGroupList.php";
        break;
}
?>

    </td></tr>
    <tr><td height="30"></td></tr>
</table>

<?php
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTIONS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function ifGroupExists($grouptitle, $groupId = '', $mysqli)
{
    $stmt = $mysqli->prepare("SELECT 1 FROM partners_affiliategroup WHERE affiliategroup_title = ? " . ($groupId ? "AND affiliategroup_id != ?" : ""));
    if ($groupId) {
        $stmt->bind_param("si", $grouptitle, $groupId);
    } else {
        $stmt->bind_param("s", $grouptitle);
    }
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}

function saveAffiliateGroup($grouptitle, $level, $groupId = '', $mysqli)
{
    if ($groupId) {
        $stmt = $mysqli->prepare("UPDATE partners_affiliategroup SET affiliategroup_title = ?, affiliategroup_levels = ? WHERE affiliategroup_id = ?");
        $stmt->bind_param("sii", $grouptitle, $level, $groupId);
    } else {
        $stmt = $mysqli->prepare("INSERT INTO partners_affiliategroup (affiliategroup_title, affiliategroup_levels) VALUES (?, ?)");
        $stmt->bind_param("si", $grouptitle, $level);
    }
    return $stmt->execute();
}

function getGroupDetails($groupId, $mysqli)
{
    $stmt = $mysqli->prepare("SELECT affiliategroup_title, affiliategroup_levels FROM partners_affiliategroup WHERE affiliategroup_id = ?");
    $stmt->bind_param("i", $groupId);
    $stmt->execute();
    $stmt->bind_result($title, $levels);
    if ($stmt->fetch()) {
        return ['grouptitle' => $title, 'level' => $levels];
    }
    return false;
}

function deleteGroup($groupId, $mysqli)
{
    $stmt = $mysqli->prepare("DELETE FROM partners_affiliategroup WHERE affiliategroup_id = ?");
    $stmt->bind_param("i", $groupId);
    return $stmt->execute();
}

function SaveGroupCommission($groupId, $commisionDetails, $mysqli)
{
    for ($i = 1; $i <= count($commisionDetails); $i++) {
        $stmt = $mysqli->prepare("SELECT 1 FROM partners_affiliategroup_commission WHERE commission_groupid = ? AND commission_level = ?");
        $stmt->bind_param("ii", $groupId, $i);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $stmt = $mysqli->prepare("UPDATE partners_affiliategroup_commission SET commission_amount = ?, commission_type = ? WHERE commission_groupid = ? AND commission_level = ?");
            $stmt->bind_param("dsii", $commisionDetails[$i]['commission'], $commisionDetails[$i]['type'], $groupId, $i);
        } else {
            $stmt = $mysqli->prepare("INSERT INTO partners_affiliategroup_commission (commission_amount, commission_type, commission_groupid, commission_level) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("dsii", $commisionDetails[$i]['commission'], $commisionDetails[$i]['type'], $groupId, $i);
        }
        $stmt->execute();
    }
    return true;
}

function GetGroupCommission($groupId, $mysqli)
{
    $stmt = $mysqli->prepare("SELECT commission_amount, commission_type, commission_level FROM partners_affiliategroup_commission WHERE commission_groupid = ?");
    $stmt->bind_param("i", $groupId);
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = [];

    while ($row = $result->fetch_assoc()) {
        $level = $row['commission_level'];
        $rows[$level] = [
            'commission' => $row['commission_amount'],
            'type' => $row['commission_type']
        ];
    }
    return $rows;
}

function groupAlreadyUsed($groupId, $mysqli)
{
    $stmt = $mysqli->prepare("SELECT 1 FROM partners_affiliate WHERE affiliate_group = ?");
    $stmt->bind_param("i", $groupId);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows > 0;
}
?>
