<?php
ob_start();

//=============================================================================//
// Script Name: return_world.php (Modernized)
// Last Modified: 2025-08-20
//=============================================================================//

// Session and system includes
require_once '../includes/session.php';
require_once '../includes/constants.php';
require_once '../includes/functions.php';
require_once '../includes/allstripslashes.php';

// Create database connection
$mysqli = new mysqli($host, $user, $pass, $db);

// Check connection
if ($mysqli->connect_errno) {
    die("Failed to connect to MySQL: " . $mysqli->connect_error);
}

$mode = $_GET['mode'] ?? '';
$returnUrl = $_SERVER['HTTP_REFERER'] ?? 'index.php';

// Only allow valid modes
$validModes = [
    'approvePgm',
    'rejectPgm',
    'approveMerchants',
    'approveAffiliates',
    'rejectMerchants',
    'rejectAffiliates'
];

if (!in_array($mode, $validModes)) {
    header("Location: $returnUrl");
    exit;
}

switch ($mode) {
    case "approvePgm":
        $mysqli->query("UPDATE partners_program SET program_status='active' WHERE program_status='inactive'");
        break;

    case "rejectPgm":
        $mysqli->query("UPDATE partners_program SET program_status='inactive' WHERE program_status='active'");
        break;

    case "approveMerchants":
        $mysqli->query("UPDATE partners_merchant SET merchant_status='approved' WHERE merchant_status='waiting'");
        break;

    case "approveAffiliates":
        $mysqli->query("UPDATE partners_affiliate SET affiliate_status='approved' WHERE affiliate_status='waiting'");
        break;

    case "rejectMerchants":
        $result = $mysqli->query("SELECT merchant_id FROM partners_merchant WHERE merchant_status='waiting'");
        if ($result && $result->num_rows > 0) {
            $stmt = $mysqli->prepare("DELETE FROM partners_login WHERE login_id=? AND login_flag='m'");
            while ($row = $result->fetch_assoc()) {
                $stmt->bind_param('i', $row['merchant_id']);
                $stmt->execute();
            }
            $stmt->close();
        }
        $mysqli->query("DELETE FROM partners_merchant WHERE merchant_status='waiting'");
        break;

    case "rejectAffiliates":
        $result = $mysqli->query("SELECT affiliate_id FROM partners_affiliate WHERE affiliate_status='waiting'");
        if ($result && $result->num_rows > 0) {
            $stmt = $mysqli->prepare("DELETE FROM partners_login WHERE login_id=? AND login_flag='a'");
            while ($row = $result->fetch_assoc()) {
                $stmt->bind_param('i', $row['affiliate_id']);
                $stmt->execute();
            }
            $stmt->close();
        }
        $mysqli->query("DELETE FROM partners_affiliate WHERE affiliate_status='waiting'");
        break;
}

// Redirect back to previous page
header("Location: $returnUrl");
exit;
?>
