<?php
// Contact Form Handler for PayOnline
// This script processes contact form submissions and saves them to the admin panel

header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Function to sanitize input data
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) !== false;
}

// Check if form was submitted via POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Method not allowed'
    ]);
    exit;
}

try {
    // Get and sanitize form data
    $company = sanitize_input($_POST['company'] ?? '');
    $name = sanitize_input($_POST['name'] ?? '');
    $email = sanitize_input($_POST['email'] ?? '');
    $phone = sanitize_input($_POST['phone'] ?? '');
    $employees = sanitize_input($_POST['employees'] ?? '');
    $selected_plan = sanitize_input($_POST['selected_plan'] ?? '');
    $modules = $_POST['modules'] ?? [];
    $message = sanitize_input($_POST['message'] ?? '');

    // Validate required fields
    if (empty($company) || empty($name) || empty($email) || empty($employees) || empty($selected_plan)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Please fill in all required fields'
        ]);
        exit;
    }

    // Validate email format
    if (!validate_email($email)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Please enter a valid email address'
        ]);
        exit;
    }

    // Sanitize modules array
    $allowed_modules = ['recruitment', 'onboarding', 'performance', 'time_attendance', 'leave', 'payroll'];
    $modules = array_intersect($modules, $allowed_modules);

    // Create contact data array
    $contact_data = [
        'id' => uniqid('contact_', true),
        'company' => $company,
        'name' => $name,
        'job_title' => 'Contact Form',
        'email' => $email,
        'phone' => $phone,
        'industry' => 'general',
        'employees' => $employees,
        'country' => 'Not specified',
        'selected_plan' => $selected_plan,
        'modules' => $modules,
        'message' => $message,
        'status' => 'pending',
        'timestamp' => date('c'),
        'type' => 'contact_form'
    ];

    // Save to JSON file for admin panel to read
    $data_file = __DIR__ . '/admin_panel/data/contacts.json';
    $backup_file = __DIR__ . '/admin_panel/data/contacts_backup.json';

    // Create directory if it doesn't exist
    $data_dir = dirname($data_file);
    if (!file_exists($data_dir)) {
        mkdir($data_dir, 0755, true);
    }

    // Read existing contacts
    $contacts = [];
    if (file_exists($data_file)) {
        $json_data = file_get_contents($data_file);
        if ($json_data !== false) {
            $contacts = json_decode($json_data, true) ?: [];
        }
    }

    // Add new contact
    $contacts[] = $contact_data;

    // Keep only last 1000 contacts
    if (count($contacts) > 1000) {
        $contacts = array_slice($contacts, -1000);
    }

    // Save to file
    $json_output = json_encode($contacts, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    
    // Create backup before saving
    if (file_exists($data_file)) {
        copy($data_file, $backup_file);
    }

    if (file_put_contents($data_file, $json_output, LOCK_EX) === false) {
        throw new Exception('Failed to save contact data');
    }

    // Also save as individual quote for admin panel compatibility
    $quotes_file = __DIR__ . '/admin_panel/data/quotes.json';
    $quotes = [];
    
    if (file_exists($quotes_file)) {
        $quotes_data = file_get_contents($quotes_file);
        if ($quotes_data !== false) {
            $quotes = json_decode($quotes_data, true) ?: [];
        }
    }

    // Convert contact to quote format for admin panel
    $quote_data = [
        'id' => $contact_data['id'],
        'company' => $contact_data['company'],
        'name' => $contact_data['name'],
        'job_title' => $contact_data['job_title'],
        'email' => $contact_data['email'],
        'phone' => $contact_data['phone'],
        'industry' => $contact_data['industry'],
        'employees' => $contact_data['employees'],
        'country' => $contact_data['country'],
        'selected_plan' => $contact_data['selected_plan'],
        'modules' => $contact_data['modules'],
        'message' => $contact_data['message'],
        'status' => $contact_data['status'],
        'timestamp' => $contact_data['timestamp'],
        'type' => 'contact_form'
    ];

    $quotes[] = $quote_data;
    
    // Keep only last 1000 quotes
    if (count($quotes) > 1000) {
        $quotes = array_slice($quotes, -1000);
    }

    file_put_contents($quotes_file, json_encode($quotes, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);

    // Send email notification (optional)
    $to_email = 'admin@payonline.com';
    $subject = 'New Contact Form Submission - PayOnline';
    
    $modules_text = !empty($modules) ? implode(', ', $modules) : 'None selected';
    
    $email_message = "
    New contact form submission received:
    
    Company: $company
    Contact Person: $name
    Email: $email
    Phone: $phone
    Employees: $employees
    Selected Plan: $selected_plan
    Modules: $modules_text
    Message: $message
    
    Submitted: " . date('Y-m-d H:i:s') . "
    ";

    $headers = "From: noreply@payonline.com\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    // Try to send email (comment out if not configured)
    // @mail($to_email, $subject, $email_message, $headers);

    // Return success response
    echo json_encode([
        'success' => true,
        'message' => 'Thank you for contacting us! We will get back to you soon.',
        'data' => $contact_data
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while processing your request. Please try again.',
        'error' => $e->getMessage()
    ]);
}
?>
