<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 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 __DIR__ . '/../adminapi/includes/message.php';
require_once __DIR__ . '/../adminapi/includes/response.php';
require_once __DIR__ . '/../adminapi/includes/utils.php';
require_once __DIR__ . '/../adminapi/includes/validator.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
    ob_clean(); // ✅ remove any accidental whitespace before JSON
    $jsonData = file_get_contents('php://input');
    $data = json_decode($jsonData, true);

    if ($data === null) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON']);
        exit;
    }

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

    global $pdo;
    $messageObj = new Message();

    $successCount = 0;
    $failedCount = 0;
    $messageIds = [];

    foreach ($data['messages'] as $msg) {
        $type = $msg['type'] ?? '';
        $title = $msg['title'] ?? '';
        $mobile = $msg['mobile'] ?? '';
        $subheading = $msg['subheading'] ?? '';
        $image = $msg['image'] ?? '';
        $device_id = $msg['device_id'] ?? '';

        if (empty($title) || empty($mobile) || empty($subheading)) {
            $failedCount++;
            continue;
        }

        $messageData = [
            'type' => $type,
            'title' => $title,
            'mobile' => $mobile,
            'subheading' => $subheading,
            'image' => $image,
            'device_id' => $device_id
        ];

        $messageId = $messageObj->addMessage($messageData);

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

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

    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);
    echo json_encode(['error' => 'Exception occurred', 'message' => $e->getMessage()]);
}
