<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Require PHPMailer classes
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

// Enable full error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Read and decode raw JSON input
$rawInput = file_get_contents("php://input");
file_put_contents(__DIR__ . '/debug-raw.txt', $rawInput); // Log raw input

$data = json_decode($rawInput, true);

if (!$data) {
    file_put_contents(__DIR__ . '/debug-json-error.txt', json_last_error_msg());
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON payload']);
    exit;
}

// PHPMailer setup
$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = $data['smtp_host'];
    $mail->SMTPAuth = true;
    $mail->Username = $data['smtp_user'];
    $mail->Password = $data['smtp_pass'];
    $mail->SMTPSecure = $data['smtp_secure'] ?? 'ssl';
    $mail->Port = (int) $data['smtp_port'];

    // Handle from name/email
    if (!empty($data['from']) && preg_match('/^(.*?)\s*<(.+?)>$/', $data['from'], $matches)) {
        $mail->setFrom($matches[2], $matches[1]);
    } elseif (!empty($data['smtp_user'])) {
        $mail->setFrom($data['smtp_user']);
    } else {
        throw new Exception('Missing valid "from" address.');
    }

    // Add recipient
    if (!empty($data['to'])) {
        $mail->addAddress($data['to']);
    } else {
        throw new Exception('Missing "to" address.');
    }

    // Subject and body
    $mail->isHTML(true);
    $mail->Subject = $data['subject'] ?? 'No Subject';
    $mail->Body = nl2br($data['body'] ?? '');

    $mail->send();
    echo json_encode(['status' => 'success']);
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $mail->ErrorInfo ?: $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}
