<?php
/**
 * API Handler - Contact Form
 * Aegean Dominance - İzmir Tenteci V2
 */

declare(strict_types=1);

// CORS headers for API
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

require_once __DIR__ . '/../../config/config.php';

try {
    $db = Database::getInstance();
    
    // Get input
    $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    
    // Validate required fields
    $name = trim($input['name'] ?? '');
    $phone = trim($input['phone'] ?? '');
    $email = trim($input['email'] ?? '');
    $message = trim($input['message'] ?? '');
    $serviceType = trim($input['service_type'] ?? '');
    
    if (empty($name) || empty($phone)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Ad ve telefon zorunludur.']);
        exit;
    }
    
    // Validate phone (basic Turkish format)
    $phone = preg_replace('/\D/', '', $phone);
    if (strlen($phone) < 10 || strlen($phone) > 12) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Geçerli bir telefon numarası girin.']);
        exit;
    }
    
    // Validate email if provided
    if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Geçerli bir e-posta adresi girin.']);
        exit;
    }
    
    // Get client info
    $ipAddress = $_SERVER['HTTP_CF_CONNECTING_IP'] 
        ?? $_SERVER['HTTP_X_FORWARDED_FOR'] 
        ?? $_SERVER['REMOTE_ADDR'] 
        ?? '0.0.0.0';
    $userAgent = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 500);
    $pageUrl = $input['page_url'] ?? $_SERVER['HTTP_REFERER'] ?? '';
    
    // Insert into database
    $db->execute(
        "INSERT INTO contact_forms (name, phone, email, message, service_type, ip_address, user_agent, page_url, status) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'new')",
        [$name, $phone, $email, $message, $serviceType, $ipAddress, $userAgent, $pageUrl]
    );
    
    $leadId = $db->lastInsertId();
    
    // Success
    echo json_encode([
        'success' => true,
        'message' => 'Mesajınız başarıyla gönderildi. En kısa sürede size dönüş yapacağız.',
        'lead_id' => $leadId
    ]);
    
} catch (Exception $e) {
    error_log("API Contact Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Bir hata oluştu. Lütfen tekrar deneyin.']);
}
