<?php
// Allow cross-origin requests
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

// Include required files
require_once '../includes/message.php';
require_once '../includes/utils.php';

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

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

try {
    // Get JSON data from request body
    $jsonData = file_get_contents('php://input');
    $data = json_decode($jsonData, true);

    // Check if data was successfully decoded
    if ($data === null) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Invalid JSON data']);
        exit;
    }

    // Extract required fields
     $type = $data['type'] ?? '';
    $title = $data['title'] ?? '';
    $mobile = $data['mobile'] ?? '';
    $subheading = $data['subheading'] ?? '';
    $image = $data['image'] ?? '';

    // Validate data
    if (empty($title) || empty($mobile) || empty($subheading)) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Required fields missing: title, mobile, and subheading are required']);
        exit;
    }

    // Create message object
    $messageObj = new Message();

    // Prepare message data
    $messageData = [
        'type' => $type,
        'title' => $title,
        'mobile' => $mobile,
        'subheading' => $subheading,
        'image' => $image
    ];

    // Add message to database
    $messageId = $messageObj->addMessage($messageData);

    if ($messageId) {
        // Log activity
        Utils::logActivity(0, 'api_add_message', "Added message via API: {$messageId}");

        // Return success response
        http_response_code(201); // Created
        echo json_encode([
            'id' => $messageId,
            'success' => true,
            'message' => 'Message added successfully'
        ]);
    } else {
        http_response_code(500); // Internal Server Error
        echo json_encode(['error' => 'Failed to add message']);
    }
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    echo json_encode(['error' => 'An error occurred', 'message' => $e->getMessage()]);
}
?>
