<?php
/**
 * Contact Form API Endpoint
 */

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 __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/email.php';
require_once __DIR__ . '/../config/security.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

// Rate limiting
$clientIP = getClientIP();
if (!checkRateLimit($clientIP . '_contact', 3, 3600)) {
    http_response_code(429);
    echo json_encode(['success' => false, 'message' => 'Too many requests. Please try again later.']);
    exit;
}

// Validate and sanitize input
$name = sanitizeInput($input['name'] ?? '');
$email = sanitizeInput($input['email'] ?? '');
$phone = sanitizeInput($input['phone'] ?? '');
$service = sanitizeInput($input['service'] ?? '');
$message = sanitizeInput($input['message'] ?? '');

// Honeypot field (should be empty)
if (!empty($input['hp_confirm'] ?? '')) {
    http_response_code(200);
    echo json_encode(['success' => true, 'message' => 'Thank you for your message.']);
    exit;
}

// Validation with field-specific errors
$errors = [];
$fieldErrors = [];

if (empty($name) || strlen($name) < 2) {
    $errors[] = 'Name is required and must be at least 2 characters';
    $fieldErrors['name'] = 'Name is required and must be at least 2 characters';
}

if (empty($email) || !validateEmail($email)) {
    $errors[] = 'Valid email is required';
    $fieldErrors['email'] = 'Valid email is required';
}

if (empty($phone) || strlen($phone) < 10) {
    $errors[] = 'Valid phone number is required';
    $fieldErrors['phone'] = 'Valid phone number is required (at least 10 digits)';
}

if (empty($message) || strlen($message) < 10) {
    $errors[] = 'Message is required and must be at least 10 characters';
    $fieldErrors['message'] = 'Message is required and must be at least 10 characters';
}

if (!empty($errors)) {
    http_response_code(400);
    echo json_encode([
        'success' => false, 
        'message' => 'Please correct the errors in the form',
        'errors' => $errors,
        'fieldErrors' => $fieldErrors
    ]);
    exit;
}

try {
    $pdo = getDBConnection();
    
    // Insert into database
    $stmt = $pdo->prepare("
        INSERT INTO contact_submissions (name, email, phone, service, message, ip_address, created_at)
        VALUES (:name, :email, :phone, :service, :message, :ip_address, NOW())
    ");
    
    $stmt->execute([
        ':name' => $name,
        ':email' => $email,
        ':phone' => $phone,
        ':service' => $service,
        ':message' => $message,
        ':ip_address' => $clientIP
    ]);
    
    // Send email notification (non-blocking - don't fail if email fails)
    try {
        $emailData = [
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'service' => $service ?: 'Not specified',
            'message' => $message
        ];
        
        $emailSent = sendContactEmail($emailData);
        
        // Send auto-reply to user
        $autoReplySubject = 'Thank you for contacting Horizon Drilling';
        $autoReplyBody = "
        <html>
        <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
            <div style='max-width: 600px; margin: 0 auto; padding: 20px; background: #f8f9fa; border-radius: 8px;'>
                <div style='background: linear-gradient(135deg, #FF6B35, #00B4D8); padding: 20px; border-radius: 8px 8px 0 0; text-align: center;'>
                    <h1 style='color: white; margin: 0;'>Horizon Drilling</h1>
                </div>
                <div style='padding: 30px; background: white;'>
                    <h2 style='color: #FF6B35; margin-top: 0;'>Thank you for contacting us!</h2>
                    <p>Dear {$name},</p>
                    <p>We have received your message and will get back to you within 24 hours.</p>
                    <p>Our team is reviewing your inquiry and will contact you soon.</p>
                    <div style='margin-top: 30px; padding-top: 20px; border-top: 1px solid #e0e0e0;'>
                        <p style='margin: 0; color: #666; font-size: 14px;'><strong>Your inquiry details:</strong></p>
                        <p style='margin: 5px 0; color: #666; font-size: 14px;'>Service: " . ($service ?: 'Not specified') . "</p>
                        <p style='margin: 5px 0; color: #666; font-size: 14px;'>Phone: {$phone}</p>
                    </div>
                    <p style='margin-top: 30px;'>Best regards,<br><strong>Horizon Drilling Team</strong></p>
                    <p style='margin-top: 20px; font-size: 12px; color: #999;'>
                        Phone: +254 757 444 632<br>
                        Email: horizondrillingltd@gmail.com
                    </p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        sendEmail($email, $autoReplySubject, $autoReplyBody);
    } catch (Exception $emailError) {
        // Log email error but don't fail the submission
        error_log("Contact form email error: " . $emailError->getMessage());
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Thank you for your message. We will contact you within 24 hours.'
    ]);
    
} catch (PDOException $e) {
    error_log("Contact form database error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred while saving your message. Please try again later or contact us directly.'
    ]);
} catch (Exception $e) {
    error_log("Contact form error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'An unexpected error occurred. Please try again later or contact us directly.'
    ]);
}

