<?php
include_once '../includes/constants.php';
include_once '../includes/functions.php';

$partners = new partners;
$conn = $partners->connection($host, $user, $pass, $db);

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['b1']) && $_POST['b1'] === 'Update') {
    foreach ($_POST as $key => $val) {
        if ($key === 'b1') continue;

        // Reconstruct the event name if it had underscores
        $eventName = str_replace('_', ' ', $key);
        $flag = $conn->real_escape_string($val);
        $eventNameEscaped = $conn->real_escape_string($eventName);

        $sql1 = "UPDATE partners_event SET event_flag = '$flag' WHERE event_name = '$eventNameEscaped'";
        $conn->query($sql1);
    }

    $msg = "Records Updated.";
}

// Fetch all active merchant events
$sql = "SELECT * FROM partners_event WHERE event_status = 'yes' AND event_type = '0'";
$res = $conn->query($sql);
?>
<form name="f1" method="post" action="">
    <table border="0" width="62%" align="center" class="tablebdr" cellpadding="2" cellspacing="2">
        <tr>
            <td colspan="5" class="tdhead" align="center"><b>Enable Mail Settings To Merchants</b></td>
        </tr>
        <tr>
            <td colspan="5" class="textred" align="center">
                <?php echo htmlspecialchars($msg); ?>
            </td>
        </tr>

        <?php while ($row = $res->fetch_object()): ?>
            <?php
                $eventname = trim($row->event_name);
                $flag = trim($row->event_flag);
                $inputName = str_replace(' ', '_', $eventname); // Safe input name
            ?>
            <tr>
                <td class="grid1"><p>&nbsp;</p></td>
                <td class="grid1"><p align="left"><?php echo htmlspecialchars($eventname); ?></p></td>
                <td class="grid1" align="center">
                    <input type="radio" name="<?php echo $inputName; ?>" value="a" <?php echo ($flag === "a" ? "checked='checked'" : ""); ?> /> Enable
                </td>
                <td class="grid1" align="center">
                    <input type="radio" name="<?php echo $inputName; ?>" value="m" <?php echo ($flag === "m" ? "checked='checked'" : ""); ?> /> Disable
                </td>
            </tr>
        <?php endwhile; ?>

        <tr>
            <td colspan="5" align="center">
                <input type="submit" value="Update" name="b1" />
            </td>
        </tr>
    </table>
</form>
<br />
