<?php
require("header.php");

// ==========================
// GET PLAN ID
// ==========================
$plan_id = (int)($_GET['id'] ?? 0);
if (!$plan_id) die("Invalid Plan ID.");

// ==========================
// FETCH SELECTED PLAN
// ==========================
try {
    $stmt = $pdo->prepare("SELECT * FROM stocks WHERE id = ? LIMIT 1");
    $stmt->execute([$plan_id]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$plan) die("Plan not found.");
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

// ==========================
// FETCH USER INFO
// ==========================
$userId = $_SESSION['SESS_USERID'] ?? 0;
if (!$userId) die("User not logged in.");

try {
    $stmt = $pdo->prepare("SELECT username, email, cur_symbol, cur_rate, balance, tot_invest, invest, ivest, tot_percent FROM logins WHERE id = ? LIMIT 1");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) die("User not found.");

    $fullname     = $user['username'];
    $email        = $user['email'];
    $cur_symbol   = $user['cur_symbol'] ?? '$';
    $cur_rate     = (float)($user['cur_rate'] ?? 1);
    $user_bal     = (float)$user['balance'];
    $tot_invest   = (float)($user['tot_invest'] ?? 0);
    $tot_percent  = (float)($user['tot_percent'] ?? 0);
    $user_bal_converted = $user_bal * $cur_rate;
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

// ==========================
// CONVERT PLAN AMOUNTS
// ==========================
$min_converted = $plan['min_amt'] * $cur_rate;
$max_converted = $plan['max_amt'] * $cur_rate;
$plan_note     = $plan['note'] ?? 'No additional information provided.';

// ==========================
// FORMAT DURATION HELPER
// ==========================
function formatDuration($minutes) {
    if ($minutes < 60) return $minutes . " minutes";
    elseif ($minutes < 1440) return round($minutes / 60) . " hour(s)";
    elseif ($minutes < 10080) return round($minutes / 1440) . " day(s)";
    elseif ($minutes < 43200) return round($minutes / 10080) . " week(s)";
    else return round($minutes / 43200) . " month(s)";
}

// ==========================
// HANDLE INVESTMENT SUBMISSION
// ==========================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'])) {
    $amount = (float)($_POST['amount'] ?? 0);
    $min = $min_converted;
    $max = $max_converted;
    $percent = $plan['percentage'];
    $duration = $plan['duration'];

    if ($amount < $min || $amount > $max) {
        echo "Amount not within plan range.";
        exit;
    } elseif ($amount > $user_bal_converted) {
        echo "Insufficient balance.";
        exit;
    } else {
        try {
            $pdo->beginTransaction();

            // ✅ Get accurate timezone + correct local time
            $userTz = $_SESSION['user_timezone'] ?? 'UTC';
            $userNow = new DateTime('now', new DateTimeZone($userTz));
            $userLocal = $userNow->format('Y-m-d H:i:s');
            $utcNow = clone $userNow;
            $utcNow->setTimezone(new DateTimeZone('UTC'));
            $utcTime = $utcNow->format('Y-m-d H:i:s');
            $userLocation = $_SESSION['user_location'] ?? 'Unknown';

            // ✅ Insert Investment (store both UTC + local time + timezone)
            $stmt = $pdo->prepare("
                INSERT INTO invest 
                (log_id, user, email, plan, status, amount, percent, min_inv, max_inv, 
                 user_cur, user_rate, user_bal, duration, pack_id, Pack_location, 
                 user_timezone, local_time, date)
                VALUES 
                (:log_id, :user, :email, :plan, :status, :amount, :percent, :min_inv, :max_inv, 
                 :user_cur, :user_rate, :user_bal, :duration, :pack_id, :Pack_location, 
                 :user_timezone, :local_time, :date)
            ");
            $stmt->execute([
                ':log_id'        => $userId,
                ':user'          => $fullname,
                ':email'         => $email,
                ':plan'          => $plan['plan'],
                ':status'        => 'Active',
                ':amount'        => $amount,
                ':percent'       => $percent,
                ':min_inv'       => $min,
                ':max_inv'       => $max,
                ':user_cur'      => $cur_symbol,
                ':user_rate'     => $cur_rate,
                ':user_bal'      => $user_bal_converted,
                ':duration'      => $duration,
                ':pack_id'       => $plan['id'],
                ':Pack_location' => $userLocation,
                ':user_timezone' => $userTz,
                ':local_time'    => $userLocal,
                ':date'          => $utcTime // Stored in UTC
            ]);

            // ✅ Update user balance
            $stmt = $pdo->prepare("
                UPDATE logins 
                SET balance = balance - (:amount / :rate),
                    tot_invest = tot_invest + :amount,
                    invest = :amount,
                    tot_percent = tot_percent + :percent,
                    ivest = 1
                WHERE id = :id
            ");
            $stmt->execute([
                ':amount'  => $amount,
                ':rate'    => $cur_rate,
                ':percent' => $percent,
                ':id'      => $userId
            ]);

            $pdo->commit();
            echo "success";
            exit;

        } catch (PDOException $e) {
            $pdo->rollBack();
            echo "Database error: " . $e->getMessage();
            exit;
        }
    }
}
?>



<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    <!-- LEFT SIDE -->
    <div class="lg:col-span-2">
        <div class="bg-[#0F0A1F] rounded-2xl p-6 space-y-6">
            <div class="flex items-center mb-2">
                <a href="buy_plan.php" class="flex items-center gap-2 text-[#2FE6DE] hover:text-[#1CD8D2] transition-all">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="w-6 h-6">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
                    </svg>
                    <span class="font-medium">Back</span>
                </a>
            </div>

            <h3 class="text-lg font-medium">Investment Amount</h3>

            <form method="post" id="investForm" novalidate>
                <div class="space-y-3">
                    <label class="text-sm text-gray-400">Custom Amount</label>

                    <input 
                        type="range" 
                        id="amountRange" 
                        min="<?= intval($min_converted) ?>" 
                        max="<?= intval($max_converted) ?>" 
                        value="<?= intval($min_converted) ?>" 
                        class="w-full accent-[#2FE6DE]"
                    />

                    <div class="bg-[#1A1428] rounded-xl p-4 mt-3">
                        <div class="relative">
                            <div class="absolute left-0 top-1/2 -translate-y-1/2 text-xl font-medium text-[#2FE6DE] px-4"><?= $cur_symbol ?></div>
                            <input 
                                type="number"
                                name="amount"
                                id="amountInput"
                                class="w-full bg-transparent pl-12 text-xl font-medium focus:outline-none"
                                value="<?= intval($min_converted) ?>"
                                min="<?= intval($min_converted) ?>"
                                max="<?= intval($max_converted) ?>"
                                required
                            >
                        </div>
                    </div>

                    <p class="text-gray-400 text-sm mt-3">
                        Available Balance: 
                        <span class="text-[#2FE6DE] font-medium"><?= $cur_symbol ?><?= number_format($user_bal_converted, 0) ?></span>
                    </p>
                </div>

                <!-- BUTTON is type=button; JS triggers the POST -->
                <button type="button" id="confirmInvestment"
                        class="w-full bg-gradient-to-r from-[#2FE6DE] to-[#2FE6DE]/80 text-black font-medium px-6 py-4 rounded-xl hover:brightness-110 transition-all">
                    Confirm Investment
                </button>
            </form>
        </div>
    </div>

    <!-- RIGHT SIDE -->
    <div class="lg:col-span-1">
        <div class="bg-[#0F0A1F] rounded-2xl p-6 space-y-4">
            <h3 class="text-lg font-medium">Investment Summary</h3>
            <div class="space-y-3">
                <div class="flex justify-between text-sm"><span class="text-gray-400">Plan</span><span class="font-medium"><?= htmlspecialchars($plan['plan']) ?></span></div>
                <div class="flex justify-between text-sm"><span class="text-gray-400">Duration</span><span class="font-medium"><?= formatDuration($plan['duration']) ?></span></div>
                <div class="flex justify-between text-sm"><span class="text-gray-400">ROI</span><span class="font-medium text-[#2FE6DE]"><?= htmlspecialchars($plan['percentage']) ?>%</span></div>
                <div class="flex justify-between text-sm"><span class="text-gray-400">Min Amount</span><span class="font-medium"><?= $cur_symbol ?><?= number_format($min_converted, 0) ?></span></div>
                <div class="flex justify-between text-sm"><span class="text-gray-400">Max Amount</span><span class="font-medium"><?= $cur_symbol ?><?= number_format($max_converted, 0) ?></span></div>
                <div class="flex justify-between text-sm border-t border-gray-700 pt-3"><span class="text-gray-400">Amount to Invest</span><span class="font-medium text-[#2FE6DE]" id="amountDisplay"><?= $cur_symbol ?><?= number_format($min_converted, 0) ?></span></div>
                <div class="border-t border-gray-700 pt-3"><span class="text-gray-400 text-sm block mb-1">Note</span><p class="text-gray-300 text-sm leading-relaxed"><?= nl2br(htmlspecialchars($plan_note)) ?></p></div>
            </div>
        </div>
    </div>
</div>
</main>

<!-- ====================== Success Popup Modal ====================== -->
<div id="successModal" class="fixed inset-0 flex items-center justify-center bg-black/70 z-50 hidden">
  <div class="bg-[#0F0A1F] rounded-2xl p-6 text-center w-80 shadow-xl">
    <h3 class="text-lg font-semibold text-[#2FE6DE] mb-3">Success!</h3>
    <p class="text-gray-300 mb-6">Successfully invested in this package.</p>
    <div class="flex justify-center gap-4">
      <button id="okBtn" class="bg-[#2FE6DE] text-black font-medium px-4 py-2 rounded-xl hover:brightness-110 transition-all">OK</button>
      <button id="cancelBtn" class="bg-gray-700 text-white font-medium px-4 py-2 rounded-xl hover:bg-gray-600 transition-all">Cancel</button>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const range = document.getElementById('amountRange');
  const input = document.getElementById('amountInput');
  const display = document.getElementById('amountDisplay');
  const form = document.getElementById('investForm');
  const button = document.getElementById('confirmInvestment');
  const modal = document.getElementById('successModal');
  const okBtn = document.getElementById('okBtn');
  const cancelBtn = document.getElementById('cancelBtn');

  if (!form || !button) {
    console.error('Invest form or button missing');
    return;
  }

  function updateDisplay(val) {
    display.textContent = "<?= $cur_symbol ?>" + parseInt(val).toLocaleString();
  }

  // sync slider -> input and display
  range.addEventListener('input', () => {
    const val = Math.round(range.value);
    input.value = val;
    updateDisplay(val);
  });

  // sync input -> slider and display (handles typing and Enter key)
  input.addEventListener('input', () => {
    input.value = input.value.replace(/[^\d]/g, '');
    let val = parseInt(input.value) || <?= intval($min_converted) ?>;
    if (val < <?= intval($min_converted) ?>) val = <?= intval($min_converted) ?>;
    if (val > <?= intval($max_converted) ?>) val = <?= intval($max_converted) ?>;
    range.value = val;
    updateDisplay(val);
  });

  // Handle Enter key submit from input: capture native form submit and route to handleSubmit
  form.addEventListener('submit', function(e) {
    e.preventDefault(); // prevent default full page submit
    handleSubmit();
  });

  // Button click (mouse) also triggers same handler
  button.addEventListener('click', function(e) {
    e.preventDefault();
    handleSubmit();
  });

  // unified submit handler (shows confirm, posts via fetch, shows modal)
  async function handleSubmit() {
    // confirm first
    const confirmAction = confirm("Are you sure you want to invest in this plan?");
    if (!confirmAction) {
      return;
    }

    // Basic client-side validation to avoid unnecessary request
    let amountVal = parseFloat(input.value);
    if (isNaN(amountVal)) {
      alert('Please enter a valid amount.');
      return;
    }
    if (amountVal < <?= floatval($min_converted) ?> || amountVal > <?= floatval($max_converted) ?>) {
      alert('Amount out of allowed range.');
      return;
    }

    // disable button to prevent double submissions
    button.disabled = true;
    button.style.opacity = '0.6';

    const formData = new FormData(form);

    try {
      // POST to same URL
      const response = await fetch(window.location.href, {
        method: 'POST',
        body: formData,
        credentials: 'same-origin',
        headers: {
          // no custom content-type — FormData sets correct headers
        }
      });

      const text = await response.text();
      const trimmed = text.trim();
      console.log('Server response:', trimmed);

      // If server returned success anywhere in response, treat as success
      if (trimmed.toLowerCase().includes('success')) {
        // show modal
        modal.classList.remove('hidden');
      } else {
        // if server returned some message (validation or error), show it
        alert('Server response: ' + trimmed);
      }
    } catch (err) {
      console.error(err);
      alert('Network error: ' + err.message);
    } finally {
      // re-enable button
      button.disabled = false;
      button.style.opacity = '';
    }
  }

  // Popup buttons
  okBtn.addEventListener('click', function() {
    window.location.href = 'buy_plan.php';
  });
  cancelBtn.addEventListener('click', function() {
    modal.classList.add('hidden');
  });

  // initial display
  updateDisplay(range.value);
});
</script>

<style>
input[type="range"]::-webkit-slider-thumb {
  background-color: #2FE6DE;
  border-radius: 50%;
}
#successModal { backdrop-filter: blur(4px); }
</style>

<?php require("footer.php"); ?>
