<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/Exception.php';
require 'PHPMailer/SMTP.php';

$connection = mysqli_connect('localhost', 'webstagi_optoutu', 'Chang3M3', 'webstagi_optout');

if (!$connection) {
    die("DB Error: " . mysqli_connect_error());
}

$user_phone = mysqli_real_escape_string($connection, $_POST['phone'] ?? '');
$user_senderid = mysqli_real_escape_string($connection, $_POST['senderid'] ?? '');

date_default_timezone_set('Asia/Dubai');
$udate = date('Y-m-d H:i:s');

$sql = "INSERT INTO unsubscribe_optout (mobile, senderid, udate)
        VALUES ('$user_phone', '$user_senderid', '$udate')";

if (mysqli_query($connection, $sql)) {

$mail = new PHPMailer(true);

$mail->SMTPDebug = 2;
$mail->Debugoutput = 'error_log';

try {
    $mail->isSMTP();
    $mail->Host       = 'mail.web-staging.in';
    $mail->SMTPAuth   = true;
    $mail->Username   = '_mainaccount@web-staging.in';
    $mail->Password   = 'GFkhbHRg9t2VtglX';

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    $mail->SMTPOptions = [
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ]
    ];

    // MOST IMPORTANT
    $mail->setFrom('support@vectramind.com', 'Vectramind Optout');
    $mail->addReplyTo('support@vectramind.com');
    $mail->Sender = 'support@vectramind.com';

    // Recipients
    $mail->addAddress('hemasree.atmakuri@vectramind.com');

    $mail->isHTML(true);
    $mail->Subject = "UnSubscribe Notice";

    $mail->Body = "
        <h1 style='color:#f40;'>UnSubscribe!</h1>
        <p style='font-size:18px;'>Phone: $user_phone</p>
        <p style='font-size:18px;'>Sender ID: $user_senderid</p>
    ";

    $mail->send();
    echo "<p class='success'>Unsubscribed Successfully</p>";
} catch (Exception $e) {
    echo "Mailer Error: {$mail->ErrorInfo}";
}


} else {
    echo "<p class='error'>Database insert failed: " . mysqli_error($connection) . "</p>";
    error_log("SQL Error: " . mysqli_error($connection));
}
