<?php
/**
 * Contact Form Handler with AJAX support
 * Sends emails to client and admin using templates
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'config.php';

// Enable error logging
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

// Function to sanitize input
function sanitize_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Function to validate email
function validate_email($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

// Function to send email using PHP mail() or SMTP
function send_email($to, $subject, $message, $headers) {
    // For production, use PHPMailer or similar
    return mail($to, $subject, $message, $headers);
}

// Function to get client email template
function get_client_template($data) {
    ob_start();
    include 'templates/client-template.php';
    return ob_get_clean();
}

// Function to get admin email template
function get_admin_template($data) {
    ob_start();
    include 'templates/admin-template.php';
    return ob_get_clean();
}

// Function to log contact
function log_contact($data) {
    $log_file = __DIR__ . '/contacts.log';
    $log_entry = date('Y-m-d H:i:s') . ' | ' . 
                 $data['name'] . ' | ' . 
                 $data['email'] . ' | ' . 
                 $data['phone'] . ' | ' . 
                 $data['interest'] . ' | ' . 
                 $_SERVER['REMOTE_ADDR'] . PHP_EOL;
    
    file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
}

// Main handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    // If no JSON, try POST data
    if (!$input) {
        $input = $_POST;
    }
    
    // Validate required fields
    $errors = [];
    
    if (empty($input['name'])) {
        $errors[] = 'Name is required';
    } else {
        $name = sanitize_input($input['name']);
    }
    
    if (empty($input['email'])) {
        $errors[] = 'Email is required';
    } elseif (!validate_email($input['email'])) {
        $errors[] = 'Invalid email format';
    } else {
        $email = sanitize_input($input['email']);
    }
    
    if (empty($input['message'])) {
        $errors[] = 'Message is required';
    } else {
        $message = sanitize_input($input['message']);
    }
    
    // Optional fields
    $phone = isset($input['phone']) ? sanitize_input($input['phone']) : '';
    $interest = isset($input['interest']) ? sanitize_input($input['interest']) : 'General Inquiry';
    
    // Honeypot check
    if (!empty($input['website'])) {
        // Bot detected
        echo json_encode(['success' => false, 'message' => 'Bot detected']);
        exit;
    }
    
    // Rate limiting
    session_start();
    $ip = $_SERVER['REMOTE_ADDR'];
    $time = time();
    
    if (isset($_SESSION['last_submit'][$ip]) && ($time - $_SESSION['last_submit'][$ip] < 60)) {
        echo json_encode(['success' => false, 'message' => 'Please wait 60 seconds before submitting again']);
        exit;
    }
    
    $_SESSION['last_submit'][$ip] = $time;
    
    // If validation passes
    if (empty($errors)) {
        
        // Prepare data for templates
        $data = [
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'interest' => $interest,
            'message' => $message,
            'date' => date('F j, Y'),
            'time' => date('g:i A'),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'user_agent' => $_SERVER['HTTP_USER_AGENT']
        ];
        
        // Log contact
        log_contact($data);
        
        // Get email templates
        $client_html = get_client_template($data);
        $admin_html = get_admin_template($data);
        
        // Email headers
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: " . SITE_NAME . " <" . SITE_EMAIL . ">\r\n";
        $headers .= "Reply-To: " . $email . "\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();
        
        // Send confirmation to client
        $client_subject = "Thank you for contacting " . SITE_NAME;
        $client_sent = send_email($email, $client_subject, $client_html, $headers);
        
        // Send notification to admin
        $admin_subject = "New Contact Form Submission - " . $name;
        $admin_sent = send_email(ADMIN_EMAIL, $admin_subject, $admin_html, $headers);
        
        if ($client_sent && $admin_sent) {
            echo json_encode([
                'success' => true,
                'message' => 'Thank you for your message! We will get back to you within 24 hours.'
            ]);
        } else {
            // Still success to user, but log error
            error_log("Email sending failed for contact from: " . $email);
            echo json_encode([
                'success' => true,
                'message' => 'Thank you for your message! We will get back to you soon.'
            ]);
        }
        
    } else {
        // Return validation errors
        echo json_encode([
            'success' => false,
            'errors' => $errors
        ]);
    }
    
} else {
    // Method not allowed
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}
?>