<?php
// Meeting Request Handler for PayOnline
header('Content-Type: application/json');

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

// Function to send JSON response
function sendResponse($success, $message, $data = null) {
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

// Validate and sanitize input data
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Invalid request method');
}

// Get and validate form data
$required_fields = ['company_name', 'fname', 'lname', 'email', 'phone'];
$missing_fields = [];

foreach ($required_fields as $field) {
    if (empty($_POST[$field])) {
        $missing_fields[] = $field;
    }
}

if (!empty($missing_fields)) {
    sendResponse(false, 'Please fill in all required fields', ['missing_fields' => $missing_fields]);
}

// Sanitize all inputs
$company_name = sanitizeInput($_POST['company_name']);
$client_code = sanitizeInput($_POST['client_code'] ?? '');
$fname = sanitizeInput($_POST['fname']);
$lname = sanitizeInput($_POST['lname']);
$role = sanitizeInput($_POST['role'] ?? '');
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$zip = sanitizeInput($_POST['zip'] ?? '');
$phone = sanitizeInput($_POST['phone']);
$message = sanitizeInput($_POST['message'] ?? '');

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(false, 'Please enter a valid email address');
}

// Validate phone number (basic validation)
if (!preg_match('/^[\d\s\-\+\(\)]+$/', $phone)) {
    sendResponse(false, 'Please enter a valid phone number');
}

// Create meeting request data
$meeting_request = [
    'id' => uniqid('meeting_'),
    'company_name' => $company_name,
    'client_code' => $client_code,
    'first_name' => $fname,
    'last_name' => $lname,
    'full_name' => $fname . ' ' . $lname,
    'role' => $role,
    'email' => $email,
    'zip_code' => $zip,
    'phone' => $phone,
    'message' => $message,
    'status' => 'pending',
    'created_at' => date('Y-m-d H:i:s'),
    'date' => date('Y-m-d'),
    'type' => 'meeting_request'
];

// Save to data file (JSON format)
$data_file = 'data/meeting_requests.json';
$data_dir = dirname($data_file);

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

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

// Add new request to the beginning of the array
array_unshift($existing_requests, $meeting_request);

// Save updated data
if (file_put_contents($data_file, json_encode($existing_requests, JSON_PRETTY_PRINT)) === false) {
    sendResponse(false, 'Failed to save meeting request. Please try again.');
}

// Send email notification (optional)
$to = 'admin@payonline.com';
$subject = 'New Meeting Request - ' . $company_name;
$email_message = "
A new meeting request has been submitted:

Company: $company_name
Client Code: $client_code
Contact Person: $fname $lname
Role: $role
Email: $email
Phone: $phone
Zip Code: $zip

Message:
$message

Submitted on: " . 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 (commented out for development)
// mail($to, $subject, $email_message, $headers);

sendResponse(true, 'Meeting request submitted successfully! We will contact you soon.', $meeting_request);
?>
