<?php
// =================================================================
// CONFIGURATION - PLEASE EDIT THIS SECTION
// =================================================================
// Your cPanel Email Credentials
$smtp_host = 'localhost';                 // Try 'localhost' first for internal routing
$smtp_user = 'info@masterkeyservices.in'; // Your full email address
$smtp_pass = 'Master@1239';  // <--- ENTER YOUR PASSWORD HERE
$smtp_port = 465;                         // SSL Port (Standard for cPanel)
$to_email  = 'info@masterkeyservices.in, adrianjessi87@gmail.com'; // Where you want to receive leads
// =================================================================

// Disable display errors to prevent HTML breaking JSON response
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'php_mail_errors.log');
header('Content-Type: application/json');

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // 1. Sanitize Data
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
    $service = filter_input(INPUT_POST, 'service_name', FILTER_SANITIZE_STRING) ?: "General Inquiry";

    if (empty($name) || empty($phone)) {
        echo json_encode(["status" => "error", "message" => "Name and Phone are required."]);
        exit;
    }

    // 2. Build Email Body
    $subject = "New Lead: $service - $name";
    $body  = "New Inquiry Received:\n";
    $body .= "-----------------------------------\n";
    $body .= "Service: $service\n";
    $body .= "Name:    $name\n";
    $body .= "Phone:   $phone\n";

    // Add dynamic fields
    foreach ($_POST as $key => $value) {
        if (!in_array($key, ['name', 'phone', 'service_name'])) {
            $body .= ucfirst(str_replace('_', ' ', $key)) . ": " . htmlspecialchars(strip_tags($value)) . "\n";
        }
    }
    $body .= "-----------------------------------\n";
    $body .= "Date: " . date('Y-m-d H:i:s') . "\n";

    // 3. Send via SMTP
    // Try primary port (465)
    $result = send_smtp_email($smtp_host, $smtp_port, $smtp_user, $smtp_pass, $to_email, $subject, $body);
    
    // If failed, try fallback port (587) with different host if needed
    if ($result !== true) {
         $result = send_smtp_email('mail.masterkeyservices.in', 587, $smtp_user, $smtp_pass, $to_email, $subject, $body);
    }

    if ($result === true) {
        echo json_encode(["status" => "success", "message" => "Thank you! We have received your request."]);
    } else {
        http_response_code(500);
        // Return the actual error message for debugging
        echo json_encode(["status" => "error", "message" => "Email failed: " . $result]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Invalid Request"]);
}

// =================================================================
// CUSTOM SMTP FUNCTION
// =================================================================
function send_smtp_email($host, $port, $username, $password, $to, $subject, $message) {
    try {
        // Create context to allow self-signed certificates
        $context = stream_context_create([
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ]);

        // Protocol prefix based on port
        $protocol = ($port == 465) ? "ssl://" : "tcp://";
        
        $socket = stream_socket_client("$protocol$host:$port", $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $context);
        
        if (!$socket) { 
            error_log("SMTP Connect Failed to $host:$port - $errstr ($errno)"); 
            return "Connection Failed to $host:$port"; 
        }

        // Helper to read server response
        function read_smtp($socket) {
            $response = "";
            while ($str = fgets($socket, 515)) {
                $response .= $str;
                if (substr($str, 3, 1) == " ") break;
            }
            return $response;
        }

        read_smtp($socket); // Server greeting

        fputs($socket, "EHLO $host\r\n"); read_smtp($socket);
        
        // STARTTLS for port 587
        if ($port == 587) {
            fputs($socket, "STARTTLS\r\n");
            $tls_response = read_smtp($socket);
            if (strpos($tls_response, '220') === false) return "STARTTLS Failed";
            stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
            fputs($socket, "EHLO $host\r\n"); read_smtp($socket);
        }

        fputs($socket, "AUTH LOGIN\r\n"); read_smtp($socket);
        fputs($socket, base64_encode($username) . "\r\n"); read_smtp($socket);
        fputs($socket, base64_encode($password) . "\r\n"); 
        
        $auth_response = read_smtp($socket);
        if (strpos($auth_response, '235') === false) {
            error_log("SMTP Auth Failed: $auth_response");
            return "Authentication Failed (Check Password)";
        }

        fputs($socket, "MAIL FROM: <$username>\r\n"); read_smtp($socket);
        
        // Handle multiple recipients
        $recipients = explode(',', $to);
        foreach($recipients as $recipient) {
            $recipient = trim($recipient);
            if(!empty($recipient)) {
                fputs($socket, "RCPT TO: <$recipient>\r\n"); read_smtp($socket);
            }
        }

        fputs($socket, "DATA\r\n"); read_smtp($socket);

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $headers .= "From: MasterKey Website <$username>\r\n";
        $headers .= "Reply-To: $username\r\n";
        $headers .= "To: $to\r\n";
        $headers .= "Subject: $subject\r\n";

        fputs($socket, "$headers\r\n$message\r\n.\r\n"); 
        $send_response = read_smtp($socket);

        fputs($socket, "QUIT\r\n");
        fclose($socket);

        if (strpos($send_response, '250') !== false) {
            return true;
        } else {
            error_log("SMTP Send Failed: $send_response");
            return "Sending Failed (Server rejected content)";
        }

    } catch (Exception $e) {
        error_log("SMTP Error: " . $e->getMessage());
        return "System Error: " . $e->getMessage();
    }
}
?>