<?php
ob_start();
session_start();

require_once '../includes/constants.php';
require_once '../includes/functions.php';
require_once '../includes/allstripslashes.php';

// DB connection
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die("Database connection failed: " . $mysqli->connect_error);
}

$merid = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
$loginflag = $_REQUEST['loginflag'] ?? '';
$tick = "checked";
$ok = "";
$mailok = "";
$pwd = "";
$conpass = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['B1'])) {
    $mailid = $_POST['mailid'] ?? '';
    $pwd = $_POST['t1'] ?? '';
    $conpass = $_POST['t2'] ?? '';
    $tick = isset($_POST['C1']) ? "checked" : "";

    if (empty($pwd) || empty($conpass)) {
        $ok = "Please don't leave any field blank.";
    } elseif ($pwd !== $conpass) {
        $ok = "Password and Confirm Password should be the same.";
    } else {
        // Hash the password securely
        $hashed_password = password_hash($pwd, PASSWORD_DEFAULT);

        // Update password
        $stmt = $mysqli->prepare("UPDATE partners_login SET login_password = ? WHERE login_id = ? AND login_flag = ?");
        $stmt->bind_param("sis", $hashed_password, $merid, $loginflag);
        $stmt->execute();
        $stmt->close();

        $ok = "Your password has been changed!";
        $mailok = "Didn't send any mail.";

        if ($tick === "checked") {
            // Get admin email settings
            $adminRes = $mysqli->query("SELECT * FROM partners_admin LIMIT 1");
            $admin = $adminRes->fetch_object();
            $admin_email = stripslashes($admin->admin_email);
            $adminheader = stripslashes($admin->admin_mailheader);
            $adminfooter = stripslashes($admin->admin_mailfooter);

            if ($loginflag === 'a') {
                $userRes = $mysqli->query("SELECT * FROM partners_affiliate WHERE affiliate_id = $merid");
                $user = $userRes->fetch_object();

                $loginRes = $mysqli->query("SELECT * FROM partners_login WHERE login_id = $merid AND login_flag = 'a'");
                $login = $loginRes->fetch_object();

                $sql_mail = "SELECT * FROM partners_adminmail WHERE adminmail_eventname='Change Affiliate Password'";
            } else {
                $userRes = $mysqli->query("SELECT * FROM partners_merchant WHERE merchant_id = $merid");
                $user = $userRes->fetch_object();

                $loginRes = $mysqli->query("SELECT * FROM partners_login WHERE login_id = $merid AND login_flag = 'm'");
                $login = $loginRes->fetch_object();

                $sql_mail = "SELECT * FROM partners_adminmail WHERE adminmail_eventname='Change Merchant Password'";
            }

            $mailRes = $mysqli->query($sql_mail);
            if ($mailRes->num_rows > 0) {
                $mailrow = $mailRes->fetch_object();
                $subject = stripslashes($mailrow->adminmail_subject);
                $message = stripslashes($mailrow->adminmail_message);
                $head = stripslashes($mailrow->adminmail_header);
                $footer = stripslashes($mailrow->adminmail_footer);
                $from = str_replace("[from]", $admin_email, stripslashes($mailrow->adminmail_from));

                $today = date("Y-m-d");

                // Build email body
                $body = "<table border='0' cellpadding='0' cellspacing='0' width='90%'>";
                $body .= "<tr><td align='center'><br/><table border='0' cellpadding='0' cellspacing='0' width='80%'>";
                $body .= "<tr><td align='center' bgcolor='#000000'>&nbsp;</td></tr>";
                $body .= "<tr><td align='center'>$adminheader</td></tr>";
                $body .= "<tr><td align='left'>$head</td></tr>";
                $body .= "<tr><td align='left'>&nbsp;</td></tr>";
                $body .= "<tr><td align='left'>$message</td></tr>";
                $body .= "<tr><td align='left'>Your New Password is: $pwd</td></tr>";
                $body .= "<tr><td align='left'>$footer</td></tr>";
                $body .= "<tr><td align='center'>$adminfooter</td></tr>";
                $body .= "<tr><td bgcolor='#000000'>&nbsp;</td></tr></table></td></tr></table>";

                // Replace placeholders
                $replacements = [
                    "[aff_firstname]" => stripslashes($user->affiliate_firstname ?? ''),
                    "[aff_lastname]" => stripslashes($user->affiliate_lastname ?? ''),
                    "[aff_company]" => stripslashes($user->affiliate_company ?? ''),
                    "[aff_email]" => stripslashes($login->login_email ?? ''),
                    "[aff_loginlink]" => stripslashes($user->affiliate_url ?? ''),
                    "[aff_password]" => $pwd,
                    "[mer_firstname]" => stripslashes($user->merchant_firstname ?? ''),
                    "[mer_lastname]" => stripslashes($user->merchant_lastname ?? ''),
                    "[mer_company]" => stripslashes($user->merchant_company ?? ''),
                    "[mer_email]" => stripslashes($login->login_email ?? ''),
                    "[mer_loginlink]" => stripslashes($user->merchant_url ?? ''),
                    "[mer_password]" => $pwd,
                    "[today]" => $today,
                    "[from]" => $admin_email
                ];
                $body = strtr($body, $replacements);

                // Email headers
                $headers = "Content-Type: text/html; charset=iso-8859-1\r\n";
                $headers .= "From: $from\r\n";

                // Send mail
                mail($mailid, $subject, $body, $headers);

                $mailok = "Password change notification mail has been sent to: $mailid<br/>From: $from";
            }
        }
    }
}

// Pre-fill email
$stmt = $mysqli->prepare("SELECT login_email FROM partners_login WHERE login_id = ? AND login_flag = ?");
$stmt->bind_param("is", $merid, $loginflag);
$stmt->execute();
$stmt->bind_result($lid);
$stmt->fetch();
$stmt->close();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Affiliate Network Pro - Admin Panel</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="admin.css" />
</head>
<body style="background-color:#FFFFFF;">
    <table width="400" align="center" cellpadding="0" cellspacing="0">
        <tr>
            <td height="69">
                <script>
                    function button1_onclick() {
                        window.close();
                    }
                </script>
                <form method="post" action="change_pass.php?id=<?= $merid ?>&loginflag=<?= $loginflag ?>" id="f1">
                    <table border="0" cellpadding="0" cellspacing="0" width="385" class="tablebdr">
                        <tr><td colspan="3" class="tdhead" align="center">Change Password</td></tr>
                        <tr><td colspan="3" align="center" class="textred"><?= $ok ?></td></tr>
                        <tr>
                            <td></td><td>Email ID</td><td><input type="text" name="mailid" value="<?= htmlspecialchars($lid) ?>" readonly></td>
                        </tr>
                        <tr>
                            <td></td><td>Password</td><td><input type="password" name="t1" value="<?= htmlspecialchars($pwd) ?>" /></td>
                        </tr>
                        <tr>
                            <td></td><td>Confirm Password</td><td><input type="password" name="t2" value="<?= htmlspecialchars($conpass) ?>" /></td>
                        </tr>
                        <tr>
                            <td colspan="3" align="center">
                                <input type="checkbox" name="C1" value="ON" <?= $tick === "checked" ? 'checked' : '' ?> />
                                Send a Notification Mail with new Password
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" class="tdhead" align="center">
                                <input type="submit" value="Change" name="B1" />
                            </td>
                            <td class="tdhead" align="center">
                                <input type="button" value="Close" onclick="button1_onclick()" />
                            </td>
                        </tr>
                        <?php if (!empty($mailok)) { ?>
                        <tr>
                            <td colspan="3" align="center" class="textgreen"><?= nl2br($mailok) ?></td>
                        </tr>
                        <?php } ?>
                    </table>
                </form>
            </td>
        </tr>
    </table>
</body>
</html>