<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include PHPMailer classes
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Require the PHPMailer files directly
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

// Load SMTP configuration
$smtp_config =[
    'host' => 'pacesetter.co.ke',      // Your SMTP server address
    'username' => 'no-reply@pacesetter.co.ke',     // Your SMTP username
    'password' => 'xvygT41F5(#CEiIV',     // Your SMTP password
    'port' => 587,                         // Usually 587 for TLS or 465 for SSL
    'from_email' => 'no-reply@pacesetter.co.ke',
    'from_name' => 'PaceSetter',
];

// Handle preflight CORS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    header('Access-Control-Max-Age: 1728000');
    header('Content-Length: 0');
    header('Content-Type: text/plain');
    die();
}

// Handle actual request
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Log all request headers for debugging
$headers = getallheaders();
error_log("All Request Headers: " . print_r($headers, true));

// Log request method and content type
error_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
error_log("Content Type Header: " . ($_SERVER['HTTP_CONTENT_TYPE'] ?? $_SERVER['CONTENT_TYPE'] ?? 'not set'));

// Get and log raw input
$raw_input = file_get_contents("php://input");
error_log("Raw input received: " . $raw_input);

// Log POST data
error_log("POST data: " . print_r($_POST, true));

// Decode JSON
$data = json_decode($raw_input, true);

// Debug JSON decode
error_log("JSON decode result: ");
error_log(print_r($data, true));

// Output for API response
// echo json_encode([
//     'raw_input' => $raw_input,
//     'decoded_data' => $data,
//     'request_method' => $_SERVER['REQUEST_METHOD'],
//     'content_type' => $_SERVER['CONTENT_TYPE'] ?? 'not set'
// ]);
// exit();

if (!isset($data['to']) || !isset($data['subject']) || !isset($data['html'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Missing required fields: to, subject, and html are required'
    ]);
    exit();
}

$to = $data['to'];
$subject = $data['subject'];
$htmlContent = $data['html'];

try {
    // Create a new PHPMailer instance
    $mail = new PHPMailer(true);

    // Server settings
    $mail->SMTPDebug = SMTP::DEBUG_OFF;
    $mail->isSMTP();
    $mail->Host = $smtp_config['host'];
    $mail->SMTPAuth = true;
    $mail->Username = $smtp_config['username'];
    $mail->Password = $smtp_config['password'];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = $smtp_config['port'];

    // Recipients
    $mail->setFrom($smtp_config['from_email'], $smtp_config['from_name']);
    $mail->addCC('kioko.mw@gmail.com');
    $mail->addCC('josephkitonga@gmail.com');
    $mail->addAddress($to);

    // Content
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $htmlContent;

    // Send email
    $mail->send();

    echo json_encode([
        'status' => 'success',
        'message' => 'Email sent successfully'
    ]);
} catch (Exception $e) {
    error_log("Mailer Error: " . $e->getMessage());
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
