<?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');

// Secure Submit Query
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'storeTicket') {

    // Helper function to sanitize string input
    function cleanInput($data) {
        return htmlspecialchars(strip_tags(trim($data)));
    }

    // Validate and sanitize inputs
    $user_id = isset($_POST['user_id']) ? cleanInput($_POST['user_id']) : '';
    $price = isset($_POST['price']) ? trim($_POST['price']) : '';
    $description = isset($_POST['description']) ? cleanInput($_POST['description']) : '';
    $title = isset($_POST['title']) ? cleanInput($_POST['title']) : '';
    $role = isset($_POST['role']) ? cleanInput($_POST['role']) : '';

    // Validate numeric and non-negative price
    if (!is_numeric($price) || $price < 0) {
        echo json_encode(["status" => "fail", "msg" => "Price must be a non-negative number."]);
        exit;
    }

    // Basic required field check
    if (empty($user_id) || empty($price) || empty($title) || empty($description) || empty($role)) {
        echo json_encode(["status" => "fail", "msg" => "All fields are required."]);
        exit;
    }

    // Call controller securely
    $result = $controller->submitEscrowTikect($user_id, (float)$price, $description, $title, $role);
    echo json_encode($result);
}


if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'joinTicket') {
    $user_id = $_POST['user_id'];
    $id = $_POST['ticket_id'];
    $result= $controller->joinEscrowTicket($user_id,$id);
    echo json_encode($result);
}

 if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'cancelTicket') {
    $user_id = $_POST['user_id'];
    $id = $_POST['ticket_id'];
    $result= $controller->cancelEscrowTikect($id, $user_id);
    echo json_encode($result);
}


 if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'verifyBankAccount') {
    $accountNumber    = $_POST['accountNumber'];
  $bank_code = $_POST['bank_code'];
    $result= $controller->verifyBankAccount($accountNumber,$bank_code);
    echo json_encode($result);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'makeTransfer') {
    // Extract data from POST request
    $sessionId = $_POST['sessionId'];
    $debitAccountNumber = $_POST['debitAccountNumber'];
    $beneficiaryBankCode = $_POST['beneficiaryBankCode'];
    $beneficiaryAccountNumber = $_POST['beneficiaryAccountNumber'];
    $amount = $_POST['amount'];
    $narration = $_POST['narration'];
    $paymentReference = $_POST['paymentReference'];
    $saveBeneficiary = isset($_POST['saveBeneficiary']) ? $_POST['saveBeneficiary'] : false;

    // Call the function to process the transfer
    $result = $controller->make_transfer(
        $sessionId,
        $debitAccountNumber,
        $beneficiaryBankCode,
        $beneficiaryAccountNumber,
        $amount,
        $narration,
        $paymentReference,
        $saveBeneficiary
    );
    
    // Send the result back as a JSON response
    echo json_encode($result);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['action']) && $_GET['action'] == 'upgradeUserData') {
    // Get the ID parameter from POST
    $id = $_POST['id'];
    $idCard = isset($_FILES['id_card']) ? $_FILES['id_card'] : null;
    $proofOfAddress = isset($_FILES['proof_of_address']) ? $_FILES['proof_of_address'] : null;
    $verificationVideo = isset($_FILES['verification_video']) ? $_FILES['verification_video'] : null;
    $result = $controller->userUpgradeData($id, $idCard, $proofOfAddress, $verificationVideo);
    
    // Output the result in JSON format
    echo $result;
}


 if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'getBankList') {
    
    $result= $controller->getBankList();
    echo json_encode($result);
}

// Submit Reply
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'storeReply') {
    $issueId = $_POST['issueId'];
    $replyContent = $_POST['replyContent'];
    $replyby = $_POST['replyby'];
   $image1 = $_POST['image'];
    file_put_contents('slls.txt',json_encode($image1));
    $imageData = base64_decode($image1);
    $img = imagecreatefromstring($imageData);
            $imageFormat = 'png'; 
            if (imageistruecolor($img)) {
                $imageFormat = 'png';
            } else {
                $imageFormat = 'jpg';
            }
            $imageName = 'user_image_' . uniqid() . '.' . $imageFormat;
            $uploadDirectory = '/home/midekiai/app.midescrow.com.ng/api/mobile/uploadimage/images/';
            if ($imageFormat === 'jpg') {
                imagejpeg($img, $uploadDirectory . $imageName);
            } else {
                imagepng($img, $uploadDirectory . $imageName); // Save as PNG by default
            }
            $imagePath = 'https://app.midescrow.com.ng/api/mobile/uploadimage/images/' . $imageName;
            $controller->storeEscrowReply($issueId, $replyContent, $replyby,$imagePath);
    echo json_encode(["message" => "Reply submitted successfully"]);
}


// Submit Reply
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['action'] == 'storeReplyText') {
    $issueId = $_POST['issueId'];
    $replyContent = $_POST['replyContent'];
    $replyby = $_POST['replyby'];
    $image = "";
  
     $controller->storeEscrowReply($issueId, $replyContent, $replyby,$image);
    echo json_encode(["message" => "Reply submitted successfully"]);
}

if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['action'] == 'getTickets') {
    $userId = $_GET['id'];
    $result = $controller->getEscrowList($userId);

    // Cast necessary fields to match Dart model
    $typedResult = array_map(function ($item) {
    return [
        'id' => (int) $item->id,
        'userId' => (string) $item->userId,
        'name' => $item->name,
        'sEmail' => $item->sEmail ?? null,
        'bEmail' => $item->bEmail ?? null,
        'sPhone' => $item->sPhone ?? null,
        'bPhone' => $item->bPhone ?? null,
        'price' => (int) $item->price,
        'title' => $item->title,
        'description' => $item->description,
        'status' => $item->status,
        'paymentId' => isset($item->paymentId) ? (string) $item->paymentId : null,
        'amounttopay' => (int) $item->amounttopay,
        'details' => $item->details ?? null,
        'paid' => $item->paid,
        'sellerId' => isset($item->sellerId) ? (string) $item->sellerId : null,
        'role' => $item->role,
        'pickup' => $item->pickup,
        'deliver' => $item->deliver,
        'created_at' => $item->created_at,
    ];
}, $result);


   
    echo json_encode($typedResult);
}


if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['action'] == 'getEscrowAndReplies') {
    $issueId = $_GET['id'];
    $user_id = $_GET['user_id'];

    $result = $controller->getEscrowAndReplies($user_id, $issueId);

    // Ensure numeric fields are cast to proper types
    foreach ($result as &$item) {
        $item['id'] = (int) $item['id'];
        $item['price'] = (int) $item['price'];
        $item['amounttopay'] = (int) $item['amounttopay'];

        if (isset($item['escrowreply']) && is_array($item['escrowreply'])) {
            foreach ($item['escrowreply'] as &$reply) {
                $reply['id'] = (int) $reply['id'];
                $reply['escrow_id'] = (int) $reply['escrow_id'];
            }
        }
    }

    // Save to file for logging/debugging
   

    // Return final JSON to client
    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);
}
