<?php
header("Content-Type: application/json");
session_start();

if(!isset($_SESSION["user_role"]) || $_SESSION["user_role"] !== "admin") {
    exit(json_encode(["success" => false, "message" => "Forbidden"]));
}

require_once dirname(dirname(dirname(__FILE__))) . "/config/config.php";
require_once dirname(dirname(dirname(__FILE__))) . "/classes/Database.php";

$db = Database::getInstance();
$testEmail = filter_var($_POST["test_email"] ?? "", FILTER_VALIDATE_EMAIL);

if(!$testEmail) {
    exit(json_encode(["success" => false, "message" => "Invalid email"]));
}

$settings = [];
$keys = ["mail_host", "mail_username", "mail_from_email", "mail_from_name", "mail_port", "mail_encryption"];

foreach($keys as $key) {
    $result = $db->fetch("SELECT setting_value FROM admin_settings WHERE setting_key = ?", [$key]);
    if($result) {
        $settings[$key] = $result["setting_value"];
    }
}

$pwdResult = $db->fetch("SELECT setting_value FROM admin_settings WHERE setting_key = ?", ["mail_password_encrypted"]);
$password = $pwdResult ? base64_decode($pwdResult["setting_value"]) : "";

if(!$settings["mail_host"] || !$settings["mail_username"] || !$password) {
    exit(json_encode(["success" => false, "message" => "Email settings not configured"]));
}

$subject = "Test Email - Advanced Mobile Info";
$body = "This is a test email from Admin Panel at " . date("Y-m-d H:i:s");
$headers = "From: " . $settings["mail_from_name"] . " <" . $settings["mail_from_email"] . ">\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

if(mail($testEmail, $subject, $body, $headers)) {
    exit(json_encode(["success" => true, "message" => "Email sent successfully to " . $testEmail]));
} else {
    exit(json_encode(["success" => false, "message" => "Failed to send email"]));
}
?>
