<?php
// API to place an order
// POST /api_place_order.php
// Expects JSON: user_id, user_email, user_name, shipping_address, payment_method, cart (array of items)

// Ensure session is available so we can clear cart server-side after successful order
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
// Don't output raw HTML errors (we'll return JSON instead)
ini_set('display_errors', 0);

// Capture any accidental output and ensure we always return JSON
ob_start();
// Clear any output that may have been generated before ob_start
@ob_end_clean();
ob_start();
$JSON_EMITTED = false;
function json_output($arr) {
    global $JSON_EMITTED;
    $JSON_EMITTED = true;
    // Aggressively clear all buffered output before sending JSON
    while (ob_get_level()) {
        @ob_end_clean();
    }
    header('Content-Type: application/json; charset=utf-8');
    $json = json_encode($arr);
    // attempt to log the response to a file for debugging
    try {
        $logDir = __DIR__ . '/logs';
        if (!is_dir($logDir)) @mkdir($logDir, 0755, true);
        @file_put_contents($logDir . '/api_place_order.log', date('c') . " RESPONSE: " . $json . "\n", FILE_APPEND);
        if (!empty($buffer)) {
            @file_put_contents($logDir . '/api_place_order.log', date('c') . " BUFFER: " . preg_replace('/\s+/', ' ', trim($buffer)) . "\n", FILE_APPEND);
        }
    } catch (Exception $e) {
        // ignore logging failures
    }
    echo $json;
    exit;
}

register_shutdown_function(function () {
    global $JSON_EMITTED;
    $err = error_get_last();
    $buffer = '';
    // capture any buffered output
    if (ob_get_length() !== false) {
        $buffer = ob_get_clean();
    }
    if ($JSON_EMITTED) {
        // normal path, nothing to do
        return;
    }

    // If there was a PHP error, prefer that message; otherwise include any buffered output
    $msg = '';
    if ($err) {
        $msg = 'Server error: ' . ($err['message'] ?? 'unknown');
    } elseif (!empty($buffer)) {
        // strip tags and trim long output for safety
        $s = strip_tags($buffer);
        $s = preg_replace('/\s+/', ' ', $s);
        $msg = 'Unexpected server output: ' . substr($s, 0, 1000);
        error_log('api_place_order unexpected output: ' . $s);
    } else {
        $msg = 'Unknown server shutdown (no output)';
    }

    // send JSON error
    @header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => $msg]);
});

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_output(['success' => false, 'message' => 'Invalid request method']);
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    json_output(['success' => false, 'message' => 'Invalid JSON input']);
}

$userId = isset($input['user_id']) ? (int)$input['user_id'] : 0;
$userEmail = isset($input['user_email']) ? trim($input['user_email']) : '';
$userName = isset($input['user_name']) ? trim($input['user_name']) : '';
$shippingAddress = isset($input['shipping_address']) ? trim($input['shipping_address']) : '';
$paymentMethod = isset($input['payment_method']) ? trim($input['payment_method']) : '';
$cartItems = isset($input['cart']) ? $input['cart'] : [];

// Validate required fields
if ($userId <= 0 || empty($userEmail) || empty($userName) || empty($shippingAddress) || empty($cartItems)) {
    json_output(['success' => false, 'message' => 'Missing required fields']);
}

// Clear any output before including DB config
while (ob_get_level() > 1) @ob_end_clean();
ob_start();
require __DIR__ . '/db_config.php';
// Discard any output from db_config
while (ob_get_level() > 1) @ob_end_clean();
ob_start();

// Calculate total price
$totalPrice = 0;
foreach ($cartItems as $item) {
    $qty = isset($item['quantity']) ? (int)$item['quantity'] : (isset($item['qty']) ? (int)$item['qty'] : 0);
    $totalPrice += (float)$item['price'] * $qty;
}

// Start transaction
$conn->begin_transaction();

try {
    // Insert order
    $orderStmt = $conn->prepare("
        INSERT INTO orders (user_id, user_email, user_name, total_price, shipping_address, payment_method, status)
        VALUES (?, ?, ?, ?, ?, ?, 'pending')
    ");
    $orderStmt->bind_param('issdss', $userId, $userEmail, $userName, $totalPrice, $shippingAddress, $paymentMethod);
    $orderStmt->execute();
    $orderId = $conn->insert_id;
    $orderStmt->close();

    // Insert order items
    $itemStmt = $conn->prepare("
        INSERT INTO order_items (order_id, product_id, product_title, product_price, quantity, subtotal)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    foreach ($cartItems as $item) {
        $itemId = isset($item['id']) ? (int)$item['id'] : 0;
        $itemTitle = isset($item['title']) ? $item['title'] : (isset($item['name']) ? $item['name'] : 'Product');
        $itemPrice = isset($item['price']) ? (float)$item['price'] : 0.0;
        $itemQty = isset($item['quantity']) ? (int)$item['quantity'] : (isset($item['qty']) ? (int)$item['qty'] : 1);
        $itemSubtotal = $itemPrice * $itemQty;

        // types: order_id (i), product_id (i), product_title (s), product_price (d), quantity (i), subtotal (d)
        $itemStmt->bind_param('iisdid', $orderId, $itemId, $itemTitle, $itemPrice, $itemQty, $itemSubtotal);
        $itemStmt->execute();
    }
    $itemStmt->close();

    $conn->commit();

    // Clear server-side cart so the user no longer sees items after success
    if (session_status() !== PHP_SESSION_ACTIVE) session_start();
    if (isset($_SESSION['cart'])) {
        $_SESSION['cart'] = [];
        @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " CART: cleared for order $orderId\n", FILE_APPEND);
    }

    // Now send emails to admin and customer (do not block cart clearing)
    sendOrderEmailToAdmin($orderId, $userName, $userEmail, $totalPrice, $cartItems, $shippingAddress);
    sendOrderEmailToCustomer($orderId, $userName, $userEmail, $totalPrice, $cartItems, $shippingAddress);

    json_output([
        'success' => true,
        'message' => 'Order placed successfully',
        'order_id' => $orderId
    ]);

} catch (Exception $e) {
    $conn->rollback();
    json_output(['success' => false, 'message' => 'Order failed: ' . $e->getMessage()]);
}

$conn->close();

// Send email notification to admin
function sendOrderEmailToAdmin($orderId, $customerName, $customerEmail, $totalPrice, $items, $shippingAddress) {
    // Load SMTP config
    $cfg = [];
    if (file_exists(__DIR__ . '/mph_v3/mail_config.php')) {
        $cfg = include __DIR__ . '/mph_v3/mail_config.php';
    } elseif (file_exists(__DIR__ . '/mail_config.php')) {
        $cfg = include __DIR__ . '/mail_config.php';
    }

    $adminEmail = 'maham11abc@gmail.com';
    $subject = "New Order #$orderId - $customerName";
    
    $itemsList = '';
    foreach ($items as $item) {
        $title = isset($item['title']) ? $item['title'] : (isset($item['name']) ? $item['name'] : 'Product');
        $qty = isset($item['quantity']) ? (int)$item['quantity'] : (isset($item['qty']) ? (int)$item['qty'] : 1);
        $price = isset($item['price']) ? number_format((float)$item['price'], 2) : '0.00';
        $lineTotal = number_format(((float)($item['price'] ?? 0) * $qty), 2);
        $itemsList .= "  - {$title} x {$qty} @ \${$price} = \${$lineTotal}\r\n";
    }

    $body = "A new order has been placed!\r\n\r\n";
    $body .= "Order ID: #$orderId\r\n";
    $body .= "Customer: $customerName\r\n";
    $body .= "Email: $customerEmail\r\n";
    $body .= "Shipping Address: $shippingAddress\r\n";
    $body .= "Total: \$$totalPrice\r\n\r\n";
    $body .= "Items:\r\n$itemsList\r\n";
    $body .= "Status: Pending\r\n\r\n";
    $body .= "Log in to the admin panel to view and manage this order.\r\n";
    $body .= "Regards,\r\nOrder System";

    $emailDebug = ['method' => null, 'ok' => false, 'error' => null];
    // Try to send via PHPMailer if available
    if (!empty($cfg) && !empty($cfg['host']) && !empty($cfg['username'])) {
        if (file_exists(__DIR__ . '/mph_v3/vendor/autoload.php') || file_exists(__DIR__ . '/vendor/autoload.php')) {
            try {
                if (file_exists(__DIR__ . '/mph_v3/vendor/autoload.php')) {
                    require_once __DIR__ . '/mph_v3/vendor/autoload.php';
                } else {
                    require_once __DIR__ . '/vendor/autoload.php';
                }
                $mail = new PHPMailer\PHPMailer\PHPMailer(true);
                $mail->isSMTP();
                $mail->Host = $cfg['host'];
                $mail->SMTPAuth = true;
                $mail->Username = $cfg['username'];
                $mail->Password = $cfg['password'] ?? '';
                if (!empty($cfg['encryption'])) $mail->SMTPSecure = $cfg['encryption'];
                $mail->Port = $cfg['port'] ?? 587;
                $mail->setFrom($cfg['from_email'] ?? $cfg['username'], $cfg['from_name'] ?? 'Order System');
                $mail->addAddress($adminEmail);
                $mail->Subject = $subject;
                $mail->Body = $body;
                $mail->AltBody = strip_tags($body);
                $mail->send();
                $emailDebug['method'] = 'phpmailer';
                $emailDebug['ok'] = true;
                // log and return
                @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: phpmailer OK for order $orderId\n", FILE_APPEND);
                return true;
            } catch (Exception $e) {
                $emailDebug['method'] = 'phpmailer';
                $emailDebug['error'] = $e->getMessage();
                error_log("PHPMailer error: " . $e->getMessage());
                @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: phpmailer failed: " . $e->getMessage() . "\n", FILE_APPEND);
                // fall through to mail() fallback
            }
        }

        // Fallback: try PHP mail() using headers from config
        try {
            $from = ($cfg['from_email'] ?? $cfg['username'] ?? $adminEmail);
            $fromName = $cfg['from_name'] ?? 'Order System';
            $headers = "From: {$fromName} <{$from}>\r\n" .
                       "Reply-To: {$from}\r\n" .
                       "MIME-Version: 1.0\r\n" .
                       "Content-Type: text/plain; charset=UTF-8\r\n";
            $sent = @mail($adminEmail, $subject, $body, $headers);
            if ($sent) {
                $emailDebug['method'] = 'mail';
                $emailDebug['ok'] = true;
                @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: mail() OK for order $orderId\n", FILE_APPEND);
                return true;
            }
            $emailDebug['method'] = 'mail';
            $emailDebug['error'] = 'mail() returned false';
            error_log('mail() fallback failed to send order email');
            @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: mail() failed for order $orderId\n", FILE_APPEND);
        } catch (Exception $e) {
            $emailDebug['method'] = 'mail';
            $emailDebug['error'] = $e->getMessage();
            error_log('mail() exception: ' . $e->getMessage());
            @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: mail() exception: " . $e->getMessage() . "\n", FILE_APPEND);
        }
    }

        // If PHPMailer/mail() did not send, try a direct SMTP socket send using config
        try {
            if (!empty($cfg['host']) && !empty($cfg['username']) && !empty($cfg['password'])) {
                // Try the lightweight fsockopen-based sender used by the password-reset flow (faster/fail-fast)
                if (function_exists('smtp_send_local') === false) {
                    // define a local helper similar to api_forgot_password.php
                    function smtp_send_local($host, $port, $username, $password, $from, $to, $subject, $body, $encryption = '') {
                        $timeout = 10; $errno = 0; $errstr = '';
                        $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
                        if (!$fp) return ['ok' => false, 'error' => "Connection failed: $errstr ($errno)"];
                        $read = function() use ($fp) { $s = ''; while ($line = fgets($fp, 515)) { $s .= $line; if (substr($line,3,1) == ' ') break; } return $s; };
                        $send = function($cmd) use ($fp) { fputs($fp, $cmd . "\r\n"); };
                        $read();
                        $send("EHLO localhost"); $ehlo = $read();
                        if (stripos($ehlo, 'STARTTLS') !== false && strtolower($encryption) === 'tls') {
                            $send("STARTTLS"); $read();
                            stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                            $send("EHLO localhost"); $read();
                        }
                        $send('AUTH LOGIN'); $read();
                        $send(base64_encode($username)); $read();
                        $send(base64_encode($password)); $authRes = $read();
                        if (stripos($authRes, '235') === false) { fclose($fp); return ['ok'=>false,'error'=>'SMTP auth failed: '.trim($authRes)]; }
                        $send('MAIL FROM: <' . $from . '>'); $read();
                        $send('RCPT TO: <' . $to . '>'); $rcpt = $read();
                        if (stripos($rcpt,'250')===false && stripos($rcpt,'251')===false) { fclose($fp); return ['ok'=>false,'error'=>'RCPT TO failed: '.trim($rcpt)]; }
                        $send('DATA'); $read();
                        $headers = "From: " . $from . "\r\n" .
                                   "To: " . $to . "\r\n" .
                                   "Subject: " . $subject . "\r\n" .
                                   "MIME-Version: 1.0\r\n" .
                                   "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
                        $send($headers . $body . "\r\n.");
                        $dataRes = $read();
                        $send('QUIT'); $read(); fclose($fp);
                        if (stripos($dataRes,'250')===false) return ['ok'=>false,'error'=>'DATA failed: '.trim($dataRes)];
                        return ['ok'=>true];
                    }
                }

                // try fast fsockopen method first (short timeout)
                $fast = smtp_send_local($cfg['host'], $cfg['port'] ?? 587, $cfg['username'], $cfg['password'] ?? '', $from ?? ($cfg['from_email'] ?? $cfg['username']), $adminEmail, $subject, $body, $cfg['encryption'] ?? '');
                if (!empty($fast['ok'])) {
                    @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: smtp_send_local OK for order $orderId\n", FILE_APPEND);
                    return true;
                }

                // fallback to stream_socket_client method
                $sent = smtp_send($cfg, $adminEmail, $subject, $body, $from ?? ($cfg['from_email'] ?? $cfg['username']));
                if ($sent) {
                    @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: smtp_send OK for order $orderId\n", FILE_APPEND);
                    return true;
                }
            }
        } catch (Exception $e) {
            error_log('SMTP socket send failed: ' . $e->getMessage());
            @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: smtp exception: " . $e->getMessage() . "\n", FILE_APPEND);
        }

        // If we reach here, sending failed
        @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " EMAIL: all methods failed for order $orderId; debug=" . json_encode($emailDebug) . "\n", FILE_APPEND);
        return false;
    }

    // Minimal SMTP sender using stream sockets (supports STARTTLS on port 587)
    function smtp_send(array $cfg, $to, $subject, $body, $from)
    {
        $host = $cfg['host'];
        $port = $cfg['port'] ?? 587;
        $timeout = 30;

        $errNo = 0;
        $errStr = '';
        $remote = $host . ':' . $port;
        $fp = stream_socket_client($remote, $errNo, $errStr, $timeout, STREAM_CLIENT_CONNECT);
        if (!$fp) {
            error_log("SMTP connect failed: $errNo - $errStr");
            return false;
        }

        // Read initial server response
        $res = fgets($fp, 515);

        $send = function ($cmd) use ($fp) {
            fwrite($fp, $cmd . "\r\n");
            return trim(fgets($fp, 515));
        };

        $ehlo = $send('EHLO ' . gethostname());
        // Start TLS if needed
        $encryption = strtolower($cfg['encryption'] ?? '');
        if ($encryption === 'tls' || $port == 587) {
            $start = $send('STARTTLS');
            // enable crypto
            if (!stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                error_log('Failed to enable TLS on SMTP connection');
                fclose($fp);
                return false;
            }
            // EHLO again after STARTTLS
            $ehlo = $send('EHLO ' . gethostname());
        }

        // AUTH LOGIN
        $send('AUTH LOGIN');
        $send(base64_encode($cfg['username']));
        $send(base64_encode($cfg['password']));

        // MAIL FROM / RCPT TO
        $send('MAIL FROM: <' . $from . '>');
        $send('RCPT TO: <' . $to . '>');
        $send('DATA');

        // Build headers
        $headers = [];
        $headers[] = 'From: ' . $from;
        $headers[] = 'To: ' . $to;
        $headers[] = 'Subject: ' . $subject;
        $headers[] = 'Date: ' . date('r');
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-Type: text/plain; charset=UTF-8';

        $data = implode("\r\n", $headers) . "\r\n\r\n" . $body . "\r\n.";
        fwrite($fp, $data . "\r\n");
        $resp = fgets($fp, 515);

        // QUIT
        $send('QUIT');
        fclose($fp);

        // Check for 250 response in $resp
        if (strpos($resp, '250') !== false || strpos($resp, '354') !== false) {
            return true;
        }
        error_log('SMTP send response: ' . $resp);
        return false;
    }

// Send order confirmation email to customer
function sendOrderEmailToCustomer($orderId, $customerName, $customerEmail, $totalPrice, $items, $shippingAddress) {
    // Load SMTP config
    $cfg = [];
    if (file_exists(__DIR__ . '/mph_v3/mail_config.php')) {
        $cfg = include __DIR__ . '/mph_v3/mail_config.php';
    } elseif (file_exists(__DIR__ . '/mail_config.php')) {
        $cfg = include __DIR__ . '/mail_config.php';
    }

    $subject = "Order Confirmation - Order #$orderId";
    
    $itemsList = '';
    foreach ($items as $item) {
        $title = isset($item['title']) ? $item['title'] : (isset($item['name']) ? $item['name'] : 'Product');
        $qty = isset($item['quantity']) ? (int)$item['quantity'] : (isset($item['qty']) ? (int)$item['qty'] : 1);
        $price = isset($item['price']) ? number_format((float)$item['price'], 2) : '0.00';
        $lineTotal = number_format(((float)($item['price'] ?? 0) * $qty), 2);
        $itemsList .= "  - {$title} x {$qty} @ \${$price} = \${$lineTotal}\r\n";
    }

    $body = "Dear " . htmlspecialchars($customerName) . ",\r\n\r\n";
    $body .= "Thank you for your order! Your order has been successfully placed.\r\n\r\n";
    $body .= "Order ID: #$orderId\r\n";
    $body .= "Order Date: " . date('F j, Y \a\t g:i A') . "\r\n";
    $body .= "Total: \$" . number_format($totalPrice, 2) . "\r\n\r\n";
    $body .= "Items Ordered:\r\n$itemsList\r\n";
    $body .= "Shipping Address:\r\n$shippingAddress\r\n\r\n";
    $body .= "Your order is being prepared. You will receive a shipping confirmation email once your items are on the way.\r\n\r\n";
    $body .= "If you have any questions, please don't hesitate to contact us.\r\n\r\n";
    $body .= "Best regards,\r\nEsa's Fashion Team";

    // Try to send via PHPMailer if available
    if (!empty($cfg) && !empty($cfg['host']) && !empty($cfg['username'])) {
        if (file_exists(__DIR__ . '/mph_v3/vendor/autoload.php') || file_exists(__DIR__ . '/vendor/autoload.php')) {
            try {
                if (file_exists(__DIR__ . '/mph_v3/vendor/autoload.php')) {
                    require_once __DIR__ . '/mph_v3/vendor/autoload.php';
                } else {
                    require_once __DIR__ . '/vendor/autoload.php';
                }
                $mail = new PHPMailer\PHPMailer\PHPMailer(true);
                $mail->isSMTP();
                $mail->Host = $cfg['host'];
                $mail->SMTPAuth = true;
                $mail->Username = $cfg['username'];
                $mail->Password = $cfg['password'] ?? '';
                if (!empty($cfg['encryption'])) $mail->SMTPSecure = $cfg['encryption'];
                $mail->Port = $cfg['port'] ?? 587;
                $mail->setFrom($cfg['from_email'] ?? $cfg['username'], $cfg['from_name'] ?? 'Esa\'s Fashion');
                $mail->addAddress($customerEmail, $customerName);
                $mail->Subject = $subject;
                $mail->Body = $body;
                $mail->AltBody = strip_tags($body);
                $mail->send();
                @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " CUSTOMER_EMAIL: phpmailer OK for order $orderId to $customerEmail\n", FILE_APPEND);
                return true;
            } catch (Exception $e) {
                error_log("PHPMailer customer email error: " . $e->getMessage());
            }
        }

        // Fallback: try PHP mail()
        try {
            $from = ($cfg['from_email'] ?? $cfg['username'] ?? 'noreply@esa-fashion.local');
            $fromName = $cfg['from_name'] ?? 'Esa\'s Fashion';
            $headers = "From: {$fromName} <{$from}>\r\n" .
                       "Reply-To: {$from}\r\n" .
                       "MIME-Version: 1.0\r\n" .
                       "Content-Type: text/plain; charset=UTF-8\r\n";
            $sent = @mail($customerEmail, $subject, $body, $headers);
            if ($sent) {
                @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " CUSTOMER_EMAIL: mail() OK for order $orderId to $customerEmail\n", FILE_APPEND);
                return true;
            }
            error_log('mail() customer email failed for order ' . $orderId);
        } catch (Exception $e) {
            error_log('mail() customer email exception: ' . $e->getMessage());
        }
    }

    // Fallback SMTP methods
    try {
        if (!empty($cfg['host']) && !empty($cfg['username']) && !empty($cfg['password'])) {
            if (function_exists('smtp_send_local') === false) {
                function smtp_send_local($host, $port, $username, $password, $from, $to, $subject, $body, $encryption = '') {
                    $timeout = 10; $errno = 0; $errstr = '';
                    $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
                    if (!$fp) return ['ok' => false, 'error' => "Connection failed: $errstr ($errno)"];
                    $read = function() use ($fp) { $s = ''; while ($line = fgets($fp, 515)) { $s .= $line; if (substr($line,3,1) == ' ') break; } return $s; };
                    $send = function($cmd) use ($fp) { fputs($fp, $cmd . "\r\n"); };
                    $read();
                    $send("EHLO localhost"); $ehlo = $read();
                    if (stripos($ehlo, 'STARTTLS') !== false && strtolower($encryption) === 'tls') {
                        $send("STARTTLS"); $read();
                        stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                        $send("EHLO localhost"); $read();
                    }
                    $send('AUTH LOGIN'); $read();
                    $send(base64_encode($username)); $read();
                    $send(base64_encode($password)); $authRes = $read();
                    if (stripos($authRes, '235') === false) { fclose($fp); return ['ok'=>false,'error'=>'SMTP auth failed: '.trim($authRes)]; }
                    $send('MAIL FROM: <' . $from . '>'); $read();
                    $send('RCPT TO: <' . $to . '>'); $rcpt = $read();
                    if (stripos($rcpt,'250')===false && stripos($rcpt,'251')===false) { fclose($fp); return ['ok'=>false,'error'=>'RCPT TO failed: '.trim($rcpt)]; }
                    $send('DATA'); $read();
                    $headers = "From: " . $from . "\r\n" .
                               "To: " . $to . "\r\n" .
                               "Subject: " . $subject . "\r\n" .
                               "MIME-Version: 1.0\r\n" .
                               "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
                    $send($headers . $body . "\r\n.");
                    $dataRes = $read();
                    $send('QUIT'); $read(); fclose($fp);
                    if (stripos($dataRes,'250')===false) return ['ok'=>false,'error'=>'DATA failed: '.trim($dataRes)];
                    return ['ok'=>true];
                }
            }

            $fast = smtp_send_local($cfg['host'], $cfg['port'] ?? 587, $cfg['username'], $cfg['password'] ?? '', $from ?? ($cfg['from_email'] ?? $cfg['username']), $customerEmail, $subject, $body, $cfg['encryption'] ?? '');
            if (!empty($fast['ok'])) {
                @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " CUSTOMER_EMAIL: smtp_send_local OK for order $orderId to $customerEmail\n", FILE_APPEND);
                return true;
            }
        }
    } catch (Exception $e) {
        error_log('SMTP customer email failed: ' . $e->getMessage());
    }

    @file_put_contents(__DIR__ . '/logs/api_place_order.log', date('c') . " CUSTOMER_EMAIL: all methods failed for order $orderId to $customerEmail\n", FILE_APPEND);
    return false;
}
