<?php
header('Content-Type: text/html; charset=utf-8');
header('Content-Language: he');
echo '<?xml version="1.0" encoding="utf-8"?>'.chr(13);
date_default_timezone_set('Asia/Jerusalem');

// Enable error logging for debugging
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

// Log all POST data for debugging
file_put_contents('form_debug.log', date('Y-m-d H:i:s') . " - Form submission:\n" . print_r($_POST, true) . "\n\n", FILE_APPEND);

// Variables from the form - FIXED field names to match your HTML
$lead_full_name = $_POST['lead_full_name'] ?? '';
$lead_phone1 = $_POST['lead_phone1'] ?? '';
$lead_email = $_POST['lead_email'] ?? '';
$lead_driving_range = $_POST['lead_driving_range'] ?? ''; // ADDED - this was missing
$accept = isset($_POST['lead_f_1']) ? 'כן' : 'לא'; // FIXED - your form uses lead_f_1, not acceptCheckbox
$submission_time = date('Y-m-d H:i:s');

// FIXED UTM parameter names to match your HTML form
$utm_source = $_POST['lead_source'] ?? '';
$utm_medium = $_POST['lead_site_src'] ?? '';
$utm_campaign = $_POST['lead_f_2'] ?? '';
$utm_term = $_POST['lead_f_3'] ?? '';
$utm_content = $_POST['lead_f_4'] ?? '';
$gclid = $_POST['gclid'] ?? '';
$page_url = $_POST['lead_f_5'] ?? '';

// Validation
if (empty($lead_full_name) || empty($lead_phone1) || empty($lead_email)) {
    file_put_contents('form_debug.log', date('Y-m-d H:i:s') . " - ERROR: Missing required fields\n", FILE_APPEND);
    echo "<script>alert('שגיאה: חסרים שדות חובה'); history.back();</script>";
    exit;
}

// Add recipients here
$to = 'costa@costa.co.il';

$subject = "פניה חדשה - משאית חשמלית פאריזון - " . $lead_full_name;
$subject = mb_encode_mimeheader($subject, 'UTF-8', 'B', "\r\n");

$headers = "From: noreply@costa.agency\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

// Build UTM details section
$utm_message = "";
if (!empty($utm_source)) {
    $utm_message .= "<tr><td>UTM Source</td><td>$utm_source</td></tr>";
}
if (!empty($utm_medium)) {
    $utm_message .= "<tr><td>UTM Medium</td><td>$utm_medium</td></tr>";
}
if (!empty($utm_campaign)) {
    $utm_message .= "<tr><td>UTM Campaign</td><td>$utm_campaign</td></tr>";
}
if (!empty($utm_term)) {
    $utm_message .= "<tr><td>UTM Term</td><td>$utm_term</td></tr>";
}
if (!empty($utm_content)) {
    $utm_message .= "<tr><td>UTM Content</td><td>$utm_content</td></tr>";
}
if (!empty($gclid)) {
    $utm_message .= "<tr><td>GCLID</td><td>$gclid</td></tr>";
}
if (!empty($page_url)) {
    $utm_message .= "<tr><td>Page URL</td><td>$page_url</td></tr>";
}

// UPDATED email body with the driving range field
$message = "
    <html>
        <body style='direction:rtl;font-family:Arial, Helvetica, sans-serif'>
            <h2>פניה חדשה - משאית חשמלית פאריזון</h2>
            <table border='1' cellpadding='5' cellspacing='0'>
                <tr><td><strong>שם מלא</strong></td><td>$lead_full_name</td></tr>
                <tr><td><strong>טלפון</strong></td><td>$lead_phone1</td></tr>
                <tr><td><strong>דוא''ל</strong></td><td>$lead_email</td></tr>
                <tr><td><strong>טווח נסיעה יומי</strong></td><td>$lead_driving_range</td></tr>
                <tr><td><strong>אישור קבלת פרסום</strong></td><td>$accept</td></tr>
                <tr><td><strong>זמן הגשה</strong></td><td>$submission_time</td></tr>
                $utm_message
            </table>
        </body>
    </html>
    ";

// Send email to company and log result
$mail_result = mail($to, $subject, $message, $headers);
if ($mail_result) {
    file_put_contents('form_debug.log', date('Y-m-d H:i:s') . " - Email sent successfully to $to\n", FILE_APPEND);
    
    // Also save lead to backup file
    $lead_backup = date('Y-m-d H:i:s') . " | $lead_full_name | $lead_phone1 | $lead_email | $lead_driving_range\n";
    file_put_contents('leads_backup.txt', $lead_backup, FILE_APPEND | LOCK_EX);
} else {
    file_put_contents('form_debug.log', date('Y-m-d H:i:s') . " - ERROR: Failed to send email to $to\n", FILE_APPEND);
    echo "<script>alert('שגיאה בשליחת הטופס. אנא נסו שוב.'); history.back();</script>";
    exit;
}

// Send confirmation to the user
$user_subject = "פנייתך התקבלה בהצלחה - משאית חשמלית פאריזון";
$user_subject = mb_encode_mimeheader($user_subject, 'UTF-8', 'B', "\r\n");
$user_message = "
    <html>
        <body style='direction:rtl;font-family:Arial, Helvetica, sans-serif'>
            <p>שלום " . htmlspecialchars($lead_full_name) . ",</p>
            <p>פנייתך התקבלה בהצלחה ונציג מטעמנו יצור איתך קשר בהקדם.</p>
            <p>עד שניצור איתך קשר אנו מזמינים אותך להיכנס לאתר שלנו לפרטים נוספים על המשאית החשמלי.</p>
            <p>לכניסה לאתר <a href='https://farizon-trucks.co.il/'>לחץ כאן</a>.</p>
        </body>
    </html>
    ";

$user_mail_result = mail($lead_email, $user_subject, $user_message, $headers);
if (!$user_mail_result) {
    file_put_contents('form_debug.log', date('Y-m-d H:i:s') . " - WARNING: Failed to send confirmation email to user $lead_email\n", FILE_APPEND);
}

echo "<script>location.replace('thankyou.html');</script>";
?>