<?php
session_start();
require("config.php");
require("db.php");

// Ensure user logged in
if (!isset($_SESSION['SESS_USERID'])) {
    header("Location: login.php");
    exit;
}

$user_id = intval($_SESSION['SESS_USERID']);

// Only top investors may change
$q = mysqli_query($db, "SELECT top_investor, mining_period_months, expected_roi FROM logins WHERE id='$user_id' LIMIT 1");
$user = mysqli_fetch_assoc($q);
if (!$user || intval($user['top_investor']) !== 2) {
    $_SESSION['msg'] = "You are not allowed to change the mining cycle.";
    header("Location: top_investors.php");
    exit;
}

// Retrieve posted values (basic validation)
$new_months = isset($_POST['mining_period_months']) ? intval($_POST['mining_period_months']) : 0;
$new_end_date = isset($_POST['mining_end_date']) ? trim($_POST['mining_end_date']) : '';
// Keep the original stored baseline values for proportional calculation
$stored_months = max(1, intval($user['mining_period_months'] ?: 1));
$stored_expected = floatval($user['expected_roi']);

// Validate months
if ($new_months <= 0 || $new_months > 1200) {
    $_SESSION['msg'] = "Invalid mining period (months).";
    header("Location: top_investors.php");
    exit;
}

// Compute new expected ROI proportionally
// If stored_expected is 0 (no baseline), we try to derive a baseline from invest_amt if possible
if ($stored_expected <= 0) {
    // fallback: try to use invest_amt (if numeric) and assume simple rate e.g. 0.1 monthly (you can adjust later)
    $u = mysqli_query($db, "SELECT invest_amt FROM logins WHERE id='$user_id' LIMIT 1");
    $row = mysqli_fetch_assoc($u);
    $invest_amt = floatval(preg_replace('/[^0-9\.]/', '', ($row['invest_amt'] ?? 0)));
    // fallback monthly rate = 0.05 (5%) -> baseline expected = invest_amt * monthly_rate * stored_months
    $base_monthly_rate = 0.05;
    $stored_expected = $invest_amt * $base_monthly_rate * $stored_months;
}

$new_expected = round($stored_expected * ($new_months / $stored_months), 2);

// Sanitize new_end_date: if empty, set by adding months from now
if (empty($new_end_date)) {
    $new_end_date_sql = date('Y-m-d H:i:s', strtotime("+" . $new_months . " months"));
} else {
    // Try to parse, fallback if invalid
    $parsed = strtotime($new_end_date);
    if ($parsed === false) {
        $new_end_date_sql = date('Y-m-d H:i:s', strtotime("+" . $new_months . " months"));
    } else {
        $new_end_date_sql = date('Y-m-d H:i:s', $parsed);
    }
}

// Update DB
$update_sql = "
    UPDATE logins
    SET
      mining_period_months = " . intval($new_months) . ",
      mining_end_date = '" . mysqli_real_escape_string($db, $new_end_date_sql) . "',
      expected_roi = " . floatval($new_expected) . "
    WHERE id = '$user_id'
    LIMIT 1
";
mysqli_query($db, $update_sql);

$_SESSION['msg'] = "Mining cycle updated. New expected ROI: " . number_format($new_expected, 2);
header("Location: top_investors.php");
exit;
?>
