<?php
/**
 * Kateel Impex - Configurable Sendmail Script
 * 
 * SETUP INSTRUCTIONS:
 * 1. For Gmail SMTP, it is highly recommended to use PHPMailer.
 * 2. If using standard mail(), ensure your server is configured for it.
 */

if (session_status() === PHP_SESSION_NONE) session_start();

// --- CONFIGURATION ---
$to_email = "kateelimpex@gmail.com"; // Your receiving email
$from_name = "Kateel Impex Website";
$from_email = "noreply@kateelimpex.com"; // Should be an email from your domain
$subject_prefix = "[Website Inquiry]";

// If you want to use SMTP (Gmail), you'll need to include PHPMailer classes
// and update the code block below. 
// ---------------------

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // 1. CAPTCHA VERIFICATION
    $user_captcha = isset($_POST['captcha']) ? intval($_POST['captcha']) : 0;
    if (!isset($_SESSION['captcha_sum']) || $user_captcha !== $_SESSION['captcha_sum']) {
        http_response_code(400);
        echo "Invalid security code. Please try again.";
        exit;
    }

    // 2. SANITIZE INPUTS
    $fullName = filter_var($_POST['fullName'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $company = filter_var($_POST['companyName'] ?? 'N/A', FILTER_SANITIZE_STRING);
    $phone = filter_var($_POST['phone'] ?? 'N/A', FILTER_SANITIZE_STRING);
    $product = filter_var($_POST['productInterest'] ?? 'Inquiry', FILTER_SANITIZE_STRING);
    $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

    if (empty($fullName) || empty($email) || empty($message)) {
        http_response_code(400);
        echo "Please fill in all required fields.";
        exit;
    }

    // 3. CONSTRUCT EMAIL
    $subject = "$subject_prefix - $product from $fullName";
    
    $body = "New inquiry received from website:\n\n";
    $body .= "Name: $fullName\n";
    $body .= "Email: $email\n";
    $body .= "Company: $company\n";
    $body .= "Phone: $phone\n";
    $body .= "Product Interest: $product\n\n";
    $body .= "Message:\n$message\n\n";
    $body .= "-----------------------------------\n";
    $body .= "Sent from Kateel Impex Contact Form";

    $headers = "From: $from_name <$from_email>\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();

    // 4. SEND (Standard mail())
    // Note: To use Gmail SMTP, you should replace this with PHPMailer logic.
    if (mail($to_email, $subject, $body, $headers)) {
        http_response_code(200);
        echo "Thank you! Your inquiry has been sent successfully.";
        // Clear captcha session after success
        unset($_SESSION['captcha_sum']);
    } else {
        http_response_code(500);
        echo "Server error: Unable to send mail. Please contact us via WhatsApp.";
    }

} else {
    http_response_code(403);
    echo "Direct access not allowed.";
}
?>
