<?php
require_once("../../autoloader.php");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

$headers = apache_request_headers();
$response = array();
$controller = new SubscriberModel;

date_default_timezone_set('Africa/Lagos');

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['action']) && $_GET['action'] == 'storeQuery') {
    try {
        $sId = filter_input(INPUT_POST, 'sId', FILTER_SANITIZE_STRING);
        $ref = filter_input(INPUT_POST, 'ref', FILTER_SANITIZE_STRING);
        $heading = filter_input(INPUT_POST, 'heading', FILTER_SANITIZE_STRING);
        $queryContent = filter_input(INPUT_POST, 'queryContent', FILTER_SANITIZE_STRING);

       
        $query_id = $controller->storeQuery($sId, $ref, $heading, $queryContent);

        // Optional: Log to file for debugging (consider using a proper logging library)
        file_put_contents('imagelol.txt', json_encode($query_id, JSON_PRETTY_PRINT), FILE_APPEND);

        echo json_encode([
            "message" => "Query submitted successfully",
            "query_id" => $query_id['id'],
            "status" => $query_id['status']
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(["error" => $e->getMessage()]);
    }
}

// Submit Reply with Image
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'storeReply') {
    // Get raw JSON input
    $rawInput = file_get_contents("php://input");
    $jsonData = json_decode($rawInput, true);

    // Log raw input
    $logData = [
        'timestamp' => date('Y-m-d H:i:s'),
        'endpoint' => $_SERVER['REQUEST_URI'],
        'raw_input' => $jsonData,
        'client_ip' => $_SERVER['REMOTE_ADDR'],
        'user_agent' => $_SERVER['HTTP_USER_AGENT'],
    ];
    file_put_contents(__DIR__ . '/request_logs.txt', json_encode($logData, JSON_PRETTY_PRINT) . PHP_EOL, FILE_APPEND);

    // Safely extract data
    $issueId = $jsonData['issueId'] ?? '';
    $replyContent = $jsonData['replyContent'] ?? '';
    $replyby = $jsonData['replyby'] ?? '';
    $image1 = $jsonData['image'] ?? '';

    // Decode and save image
    $imagePath = '';
    if (!empty($image1)) {
        $imageData = base64_decode($image1);
        $img = imagecreatefromstring($imageData);
        if ($img !== false) {
            $imageFormat = imageistruecolor($img) ? 'png' : 'jpg';
            $imageName = 'user_image_' . uniqid() . '.' . $imageFormat;
            $uploadDirectory = '/home2/wapaycom/new.wapay.com.ng/api/mobile/uploadimage/images/';

            // Save image
            if ($imageFormat === 'jpg') {
                imagejpeg($img, $uploadDirectory . $imageName);
            } else {
                imagepng($img, $uploadDirectory . $imageName);
            }

            $imagePath = 'https://new.wapay.com.ng/api/mobile/uploadimage/images/' . $imageName;
        }
    }

    // Store the reply
    $controller->storeReply($issueId, $replyContent, $replyby, $imagePath);
    echo json_encode(["message" => "Reply submitted successfully"]);
}



if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'storeReplyText') {
    // Get raw input (because axios sends JSON by default)
    $rawInput = file_get_contents("php://input");
    $jsonData = json_decode($rawInput, true); // true = return as associative array

   

    // Safely extract variables
    $issueId = $jsonData['issueId'] ?? '';
    $replyContent = $jsonData['replyContent'] ?? '';
    $replyby = $jsonData['replyby'] ?? '';
    $image = $jsonData['image'] ?? '';

    $controller->storeReply($issueId, $replyContent, $replyby, $image);
    echo json_encode(["message" => "Reply submitted successfully"]);
}


if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['action'] == 'getQueries') {
    $userId = $_GET['id'];

    $result = $controller->getQueries($userId);
// Convert 'id' and 'issue_id' to strings
foreach ($result as &$item) {
    if (isset($item['id'])) {
        $item['id'] = (string) $item['id'];
    }
    if (isset($item['issue_id'])) {
        $item['issue_id'] = (string) $item['issue_id'];
    }
}


    file_put_contents('imagebblol.txt', json_encode($result, JSON_PRETTY_PRINT));
    echo json_encode($result);
}



// Get Queries and Replies
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['action'] == 'getQueryAndReplies') {
    $issueId = $_GET['id'];
    $result = $controller->getQueriesAndReplies($issueId);

   // Cast specific fields to strings
foreach ($result as &$item) {
    if (isset($item['id'])) {
        $item['id'] = (string) $item['id'];
    }

    if (isset($item['replies']) && is_array($item['replies'])) {
        foreach ($item['replies'] as &$reply) {
            if (isset($reply['id'])) {
                $reply['id'] = (string) $reply['id'];
            }
            if (isset($reply['issue_id'])) {
                $reply['issue_id'] = (string) $reply['issue_id'];
            }
        }
        unset($reply); // good practice
    }
}

    unset($item); // good practice

    file_put_contents('imagebblol.txt', json_encode($result,JSON_PRETTY_PRINT));
    echo json_encode($result);
}

// Get Unread Count
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['action'] == 'getUnread') {
    $userId = $_GET['id'];
    $result =  $controller->getUnread($userId);
    echo json_encode($result);
}
