<?php
session_start();
require_once '../include/Constants.php';
require_once '../models/User.php';
require_once '../include/Helper.php';
require_once '../models/Wallet.php';
require_once '../models/Upgrade.php';
require_once '../models/Investment.php';
require_once '../models/Invoice.php';
require_once '../include/DatabaseConn.php';
require_once '../models/Admin.php';

header('Content-Type: application/json');

// Check if admin is logged in
$admin = Admin::getCurrentAdmin();
if (is_null($admin)) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

// Get POST data
$upgrade_id = $_POST['upgrade_id'];
$user_email = $_POST['user_email'];

$db = new DatabaseConn();
$link = $db->connect();

try {
    // Retrieve the Upgrade object
    $upgrade = Upgrade::getUpgradeById($link, $upgrade_id);
    if (is_null($upgrade)) {
        throw new Exception('Upgrade request not found.');
    }

    // Get the amount from the Upgrade object
    $upgrade_amount = $upgrade->getAmount();

    // Get the user's current investment (Invoice)
    $invoices = Invoice::getCurrentInvoices($link, $user_email);
    if (is_null($invoices) || count($invoices) == 0) {
        throw new Exception('User does not have an active investment.');
    }
    $invoice = Invoice::getInvoiceById($link, $upgrade->invoice_id); 
    $upgrade_amount  = $invoice->getAmount() + $upgrade_amount;
    
     $days = $invoice->getDays();
    
    $u_days = $upgrade->getDuration();
    
    $days = $days + $u_days;
    
    $investment_plans = Investment::getInvesments($link);
    $new_plan = null;
    foreach ($investment_plans as $plan) {
        $min = $plan->getMinUnformatted();
        $max = $plan->getMaxUnformatted();
        if ($max == -1) {
            $max = PHP_INT_MAX; // Treat -1 as unlimited
        }
        if ($upgrade_amount >= $min && $upgrade_amount <= $max) {
            $new_plan = $plan;
            break;
        }
    }
    if (is_null($new_plan)) {
        throw new Exception('No suitable investment plan found for the upgrade amount.');
    }

    // Update the user's Invoice to the new plan
    $invoice_id = $invoice->getId();
    $package = $new_plan->getName();
    $roi = $new_plan->getPercentage();
   // $days = $new_plan->getDays();
    $amount = $upgrade_amount;

    // Update the Invoice in the database
    $update_success = Invoice::upgradeInvoice($link, $invoice_id, $package, $roi, $days, $amount);
    if (!$update_success) {
        throw new Exception('Failed to upgrade the user\'s investment.');
    }

    // Update the status of the Upgrade to "Approved"
    $status_update_success = Upgrade::approveUpgrade($link, $upgrade_id);
    if (!$status_update_success) {
        throw new Exception('Failed to update the upgrade status.');
    }
    $time  = time();
    mysqli_query($link, "insert into topup(amount, `status`, `user`, `date`, `invoice`) values({$upgrade->getAmount()}, 'Upgraded', '$user_email', '$time','$invoice_id')");
    mysqli_query($link, "insert into pendingduration( `status`, `user`,  `invoice`, `duration`) values( 'pending', '$user_email','$invoice_id', '$u_days')");
    echo json_encode(['success' => true, 'message' => 'User investment upgraded successfully.']);
} catch (Exception $e) {
    // Handle exceptions and send error response
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
