<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Content-Type: application/json");

// ==========================
// CONFIGURATION
// ==========================
define('API_USER', 'admin');
define('API_PASS', 'hgf5951&^0)!');

define('SMTP_HOST', 'mail.gs1sy.org');
define('SMTP_USER', 'info@gs1sy.org');
define('SMTP_PASS', 'cVq1hck2DTS!');
define('SMTP_PORT', 587);
define('SMTP_DOMAIN', 'gs1sy.org');

// ==========================
// BASIC AUTH CHECK
// ==========================
$auth_header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';

if (!$auth_header) {
    header('WWW-Authenticate: Basic realm="Email API"');
    header('HTTP/1.0 401 Unauthorized');
    echo json_encode(["error" => "Authentication required"]);
    exit;
}

if (preg_match('/Basic\s+(.*)$/i', $auth_header, $matches)) {
    $decoded = base64_decode($matches[1]);
    $credentials = explode(':', $decoded, 2);

    if (count($credentials) !== 2) {
        http_response_code(401);
        echo json_encode(["error" => "Invalid authentication format"]);
        exit;
    }

    $user = $credentials[0];
    $pass = $credentials[1];

    if ($user !== API_USER || $pass !== API_PASS) {
        http_response_code(401);
        echo json_encode(["error" => "Invalid credentials"]);
        exit;
    }
} else {
    http_response_code(401);
    echo json_encode(["error" => "Basic authentication required"]);
    exit;
}

// ==========================
// REQUIRE POST
// ==========================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "POST method required"]);
    exit;
}

// ==========================
// GET JSON INPUT
// ==========================
$raw_input = file_get_contents("php://input");
$data = json_decode($raw_input, true);

if (!$data) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON"]);
    exit;
}

$from = $data['from'] ?? '';
$to = $data['to'] ?? '';
$subject = $data['subject'] ?? '';
$body = $data['body'] ?? '';

if (!$from || !$to || !$subject || !$body) {
    http_response_code(400);
    echo json_encode(["error" => "Missing fields"]);
    exit;
}

// ==========================
// HELPER FUNCTION: Split long lines for SMTP
// ==========================
function wrapLongLines($text, $maxLength = 998) {
    $lines = preg_split("/(\r\n|\n|\r)/", $text);
    $result = [];

    foreach ($lines as $line) {
        while (strlen($line) > $maxLength) {
            $result[] = substr($line, 0, $maxLength);
            $line = substr($line, $maxLength);
        }
        $result[] = $line;
    }

    return implode("\r\n", $result);
}

// ==========================
// PURE PHP SMTP FUNCTION
// ==========================
function sendEmailViaSMTP($host, $port, $username, $password, $from, $to, $subject, $body) {
    $errno = 0;
    $errstr = '';

    // Connect to SMTP server
    $socket = fsockopen($host, $port, $errno, $errstr, 30);
    if (!$socket) {
        return ["success" => false, "error" => "Connection failed: $errstr"];
    }

    $getResponse = function($socket) {
        $response = '';
        while ($line = fgets($socket, 515)) {
            $response .= $line;
            if (substr($line, 3, 1) == ' ') break;
        }
        return $response;
    };

    $sendCommand = function($socket, $command, $expectedCode) use ($getResponse) {
        fputs($socket, $command . "\r\n");
        $response = $getResponse($socket);
        $code = substr($response, 0, 3);
        return [$code == $expectedCode, $response];
    };

    // Read welcome message
    $response = $getResponse($socket);

    // Say EHLO
    list($success, $response) = $sendCommand($socket, "EHLO " . SMTP_DOMAIN, 250);
    if (!$success) return ["success" => false, "error" => "EHLO failed: $response"];

    // Start TLS if port 587
    if ($port == 587) {
        list($success, $response) = $sendCommand($socket, "STARTTLS", 220);
        if ($success) {
            stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
            list($success, $response) = $sendCommand($socket, "EHLO " . SMTP_DOMAIN, 250);
            if (!$success) return ["success" => false, "error" => "EHLO after TLS failed: $response"];
        }
    }

    // Authenticate
    list($success, $response) = $sendCommand($socket, "AUTH LOGIN", 334);
    if (!$success) return ["success" => false, "error" => "AUTH failed: $response"];

    fputs($socket, base64_encode($username) . "\r\n");
    $response = $getResponse($socket);
    if (substr($response, 0, 3) != '334') {
        return ["success" => false, "error" => "Username rejected: $response"];
    }

    fputs($socket, base64_encode($password) . "\r\n");
    $response = $getResponse($socket);
    if (substr($response, 0, 3) != '235') {
        return ["success" => false, "error" => "Password rejected: $response"];
    }

    // MAIL FROM
    list($success, $response) = $sendCommand($socket, "MAIL FROM:<$from>", 250);
    if (!$success) return ["success" => false, "error" => "MAIL FROM failed: $response"];

    // RCPT TO
    list($success, $response) = $sendCommand($socket, "RCPT TO:<$to>", 250);
    if (!$success) return ["success" => false, "error" => "RCPT TO failed: $response"];

    // DATA
    list($success, $response) = $sendCommand($socket, "DATA", 354);
    if (!$success) return ["success" => false, "error" => "DATA failed: $response"];

    // Wrap long lines
    $body = wrapLongLines($body);

    // Email headers and body
    $headers = [
        "From: $from",
        "To: $to",
        "Subject: $subject",
        "MIME-Version: 1.0",
        "Content-Type: text/html; charset=UTF-8"
    ];

    $email = implode("\r\n", $headers) . "\r\n\r\n" . $body . "\r\n.";
    fputs($socket, $email . "\r\n");
    $response = $getResponse($socket);
    if (substr($response, 0, 3) != '250') {
        return ["success" => false, "error" => "Message sending failed: $response"];
    }

    // QUIT
    fputs($socket, "QUIT\r\n");
    fclose($socket);

    return ["success" => true, "message" => "Email sent successfully"];
}

// ==========================
// SEND EMAIL
// ==========================
$result = sendEmailViaSMTP(
    SMTP_HOST,
    SMTP_PORT,
    SMTP_USER,
    SMTP_PASS,
    $from,
    $to,
    $subject,
    $body
);

if ($result['success']) {
    echo json_encode([
        "success" => true,
        "message" => "Email sent successfully via pure PHP SMTP",
        "to" => $to
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "error" => "SMTP Error",
        "details" => $result['error']
    ]);
}
?>
