<?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;
    }

    // Check if the messages array exists
    if (!isset($data['messages']) || !is_array($data['messages'])) {
        http_response_code(400); // Bad Request
        echo json_encode(['error' => 'Missing messages array']);
        exit;
    }

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

    // Counter for successful inserts
    $successCount = 0;
    $failedCount = 0;
    $messageIds = [];

    // Process each message
    foreach ($data['messages'] as $message) {
        // Extract message data
        $type = $message['type'] ?? '';
        $title = $message['title'] ?? '';
        $mobile = $message['mobile'] ?? '';
        $subheading = $message['subheading'] ?? '';
        $image = $message['image'] ?? '';

        // Skip if required fields are missing
        if (empty($title) || empty($mobile) || empty($subheading)) {
            $failedCount++;
            continue;
        }

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

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

        if ($messageId) {
            $successCount++;
            $messageIds[] = $messageId;
        } else {
            $failedCount++;
        }
    }

    // Log activity
    if ($successCount > 0) {
        Utils::logActivity(0, 'api_add_multiple_messages', "Added {$successCount} messages via API");
    }

    // Return response
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => "Processed {$successCount} messages successfully, {$failedCount} failed",
        'success_count' => $successCount,
        'failed_count' => $failedCount,
        'message_ids' => $messageIds
    ]);
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    echo json_encode(['error' => 'An error occurred', 'message' => $e->getMessage()]);
}
?>
