<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect data
    $name = htmlspecialchars($_POST['name'] ?? '');
    $phone = htmlspecialchars($_POST['phone'] ?? '');
    $location = htmlspecialchars($_POST['location'] ?? '');
    $address = htmlspecialchars($_POST['address'] ?? '');
    $quantity = floatval($_POST['quantity'] ?? 0);
    $date = htmlspecialchars($_POST['date'] ?? '');
    $time = htmlspecialchars($_POST['time'] ?? '');
    $product = htmlspecialchars($_POST['product_name'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $unitType = htmlspecialchars($_POST['unit_type'] ?? '');
    $deliveryPrice = explode('|', $location)[0] ?? 0;
    $total = $price * $quantity + $deliveryPrice;

    // Email body
    $body = "New Order:\n\n";
    $body .= "Product: $product\n";
    $body .= "Customer: $name\n";
    $body .= "Phone: $phone\n";
    $body .= "Location: $location\n";
    $body .= "Address: $address\n";
    $body .= "Quantity: $quantity $unitType\n";
    $body .= "Delivery Date/Time: $date $time\n";
    $body .= "Total: $total манат\n";

    // SMTP config from your details
    $smtpHost = 'mail.3-damja.com';
    $smtpPort = 465;
    $smtpUser = 'dukan@3-damja.com';
    $smtpPass = 'BNF&%#26fq~ER+@';
    $fromEmail = 'dukan@3-damja.com';
    $fromName = 'Лавка 3-DAMJA Dukan';
    $toEmail = 'dukan@3-damja.com'; // Change if needed (e.g., admin email)
    $subject = "New Order: $product";

    // Simple SMTP sender (using fsockopen for SSL)
    $socket = fsockopen('ssl://' . $smtpHost, $smtpPort, $errno, $errstr, 30);
    if (!$socket) {
        error_log("SMTP Connection failed: $errstr ($errno)");
        die('Error sending email. Check server logs.');
    }

    // SMTP commands (basic auth)
    fputs($socket, "EHLO " . $_SERVER['SERVER_NAME'] . "\r\n");
    fputs($socket, "AUTH LOGIN\r\n");
    fputs($socket, base64_encode($smtpUser) . "\r\n");
    fputs($socket, base64_encode($smtpPass) . "\r\n");
    fputs($socket, "MAIL FROM: <$fromEmail>\r\n");
    fputs($socket, "RCPT TO: <$toEmail>\r\n");
    fputs($socket, "DATA\r\n");
    fputs($socket, "From: $fromName <$fromEmail>\r\n");
    fputs($socket, "To: $toEmail\r\n");
    fputs($socket, "Subject: $subject\r\n");
    fputs($socket, "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
    fputs($socket, $body . "\r\n");
    fputs($socket, ".\r\n");
    fputs($socket, "QUIT\r\n");
    fclose($socket);

    // Redirect or success message
    echo '<script>alert("Заказ отправлен! / Сипарыş iberildi!"); window.location.href="/thank-you.html";</script>'; // Create thank-you.html
} else {
    die('Invalid request.');
}
?>