<?php
require("header.php");
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// ================= SETTINGS & MAIL CONFIG =================
$stmt = $pdo->query("SELECT * FROM settings ORDER BY id DESC LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

$cname  = $settings['domain_name'];
$curl   = $settings['url'];
$cemail = $settings['email2'];
$cpass  = $settings['password'];
$chost  = $settings['contact_email'];
$cport  = $settings['service1'];
$LOGO   = $settings['LOGO'];

function sendEmail($to, $subject, $body) {
    global $chost, $cemail, $cpass, $cname, $cport;
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = $chost;
        $mail->SMTPAuth   = true;
        $mail->Username   = $cemail;
        $mail->Password   = $cpass;
        $mail->Port       = $cport;
        $mail->SMTPSecure = ($cport == 465)
            ? PHPMailer::ENCRYPTION_SMTPS
            : PHPMailer::ENCRYPTION_STARTTLS;
        $mail->setFrom($cemail, $cname);
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->send();
    } catch (Exception $e) {
        error_log("PHPMailer error: " . $mail->ErrorInfo);
    }
}

// ================= AUTH =================
if (!isset($_SESSION['email'])) {
    header("Location: login.php");
    exit;
}
$email = $_SESSION['email'];

// ================= TIMEZONE =================
$userTz = $_SESSION['user_timezone'] ?? 'UTC';
date_default_timezone_set($userTz);

// ================= FETCH INVESTMENT =================
$inv = null;
$errorMessage = "";
if (isset($_GET['plan']) && is_numeric($_GET['plan'])) {
    $planId = (int)$_GET['plan'];
    $stmt = $pdo->prepare("SELECT * FROM invest WHERE (id=? OR pack_id=?) AND email=? LIMIT 1");
    $stmt->execute([$planId, $planId, $email]);
    $inv = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$inv) $errorMessage = "Investment not found for this account.";
} else {
    $errorMessage = "Invalid or missing investment ID.";
}

if ($inv) {
    $currency  = $inv['user_cur'] ?? '$';
    $amount    = (float)$inv['amount'];
    $percent   = (float)$inv['percent'];
    $duration  = (int)$inv['duration'];
    $roi_total = (float)$inv['roi_total'];
    $status    = strtolower($inv['status']);
    $planName  = htmlspecialchars($inv['plan']);
    $startTime = $inv['local_time'] ?? $inv['date'];

    // ================= TIME CALCULATION =================
    $startDt = new DateTime($startTime, new DateTimeZone($userTz));
    $endDt   = clone $startDt;
    $endDt->modify("+{$duration} minutes");
    $nowDt   = new DateTime('now', new DateTimeZone($userTz));

    $startTs = $startDt->getTimestamp();
    $endTs   = $endDt->getTimestamp();
    $nowTs   = $nowDt->getTimestamp();

    // ================= AUTO ROI CALCULATION EVERY 5 MIN =================
    $intervalsElapsed = floor(($nowTs - $startTs) / 300);
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM roi_history WHERE invest_id=? AND email=?");
    $stmt->execute([$inv['id'], $email]);
    $recordedIntervals = (int)$stmt->fetchColumn();

    if ($intervalsElapsed > $recordedIntervals && $nowTs < $endTs && $status !== 'completed') {
        $roiPerInterval = ($amount * $percent / 100) / ($duration / 5);
        $profit = round($roiPerInterval, 2);
        $createdAt = $nowDt->format('Y-m-d H:i:s');

        $stmt = $pdo->prepare("INSERT INTO roi_history (invest_id, email, amount, percentage, created_at)
                               VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$inv['id'], $email, $profit, $percent, $createdAt]);

        $pdo->prepare("UPDATE invest SET roi_total = roi_total + ? WHERE id=?")
            ->execute([$profit, $inv['id']]);
        $pdo->prepare("UPDATE logins SET iprofit = COALESCE(iprofit,0) + ? WHERE email=?")
            ->execute([$profit, $email]);

        $roi_total += $profit;
    }

    // ================= AUTO COMPLETE + EMAIL NOTIFY =================
    if ($nowTs >= $endTs && $status !== 'completed') {
        $pdo->prepare("UPDATE invest SET status='completed' WHERE id=?")->execute([$inv['id']]);
        $status = 'completed';

        // --- Email HTML template ---
        $subject = "🎉 Your Investment Has Completed Successfully!";
        $body = "
        <div style='background:#0f0a1f;color:#fff;padding:40px;text-align:center;font-family:Arial,sans-serif;'>
            <div style='max-width:600px;margin:auto;background:#1a1428;padding:30px;border-radius:20px;
                        box-shadow:0 0 20px rgba(47,230,222,0.3);'>
                <img src='{$LOGO}' alt='{$cname}' style='max-width:120px;margin-bottom:20px;'>
                <h2 style='color:#2FE6DE;font-size:22px;'>Investment Completed</h2>
                <p style='font-size:16px;margin-top:10px;'>
                    Hi <strong>{$email}</strong>, your investment in
                    <strong>{$planName}</strong> has been successfully completed.
                </p>
                <div style='background:#0f0a1f;border-radius:15px;padding:20px;margin:20px 0;'>
                    <p>💰 Amount Invested: <strong>{$currency}" . number_format($amount,2) . "</strong></p>
                    <p>📈 Total Profit Earned: <strong>{$currency}" . number_format($roi_total,2) . "</strong></p>
                    <p>🕓 Duration: <strong>{$duration} minutes</strong></p>
                    <p>📅 Completed On: <strong>" . $nowDt->format('M d, Y h:i A') . "</strong></p>
                </div>
                <div style='margin-top:25px;'>
                    <a href='{$curl}/investments.php' style='background:#2FE6DE;color:#0f0a1f;
                       padding:12px 30px;text-decoration:none;border-radius:30px;
                       font-weight:bold;display:inline-block;transition:0.3s;'>
                       View Investment
                    </a>
                </div>
                <p style='font-size:12px;color:#aaa;margin-top:25px;'>&copy; {$cname} — All Rights Reserved.</p>
            </div>
            <div style='margin-top:15px;font-size:12px;color:#777;'>
                <p>This is an automated message, please do not reply.</p>
            </div>
        </div>";

        sendEmail($email, $subject, $body);
    }

    // ================= FETCH ROI HISTORY =================
    $stmt = $pdo->prepare("SELECT * FROM roi_history WHERE invest_id=? AND email=? ORDER BY id DESC");
    $stmt->execute([$inv['id'], $email]);
    $roiHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// ================= HELPERS =================
function formatDuration($minutes) {
    if ($minutes < 60) return "$minutes minute" . ($minutes == 1 ? "" : "s");
    if ($minutes < 1440) return round($minutes / 60, 1) . " hour(s)";
    if ($minutes < 10080) return round($minutes / 1440, 1) . " day(s)";
    if ($minutes < 43200) return round($minutes / 10080, 1) . " week(s)";
    if ($minutes < 525600) return round($minutes / 43200, 1) . " month(s)";
    return round($minutes / 525600, 1) . " year(s)";
}
function formatDateTime(DateTime $dt) {
    return $dt->format('M d, Y h:i A');
}
?>
<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">

    <?php if ($errorMessage): ?>
        <div class="bg-red-900/20 border border-red-700 text-red-300 rounded-xl p-4 mb-6">
            <?= htmlspecialchars($errorMessage) ?>
        </div>
    <?php elseif ($inv): ?>
        <div class="bg-[#0F0A1F] rounded-2xl p-6 space-y-6 shadow-lg shadow-[#2FE6DE]/10">

            <div class="flex items-center justify-between">
                <h2 class="text-2xl font-semibold text-[#2FE6DE]"><?= $planName ?></h2>
                <span class="px-4 py-1 rounded-full <?= $status === 'completed' ? 'bg-red-600/10 text-red-400' : 'bg-green-500/10 text-green-400' ?>">
                    <?= ucfirst($status) ?>
                </span>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 text-center border-t border-[#1A1428] pt-6">
                <div>
                    <p class="text-gray-400 text-sm">Invested</p>
                    <p class="text-3xl font-semibold"><?= $currency ?><?= number_format($amount, 2) ?></p>
                </div>
                <div>
                    <p class="text-gray-400 text-sm">Profit Earned</p>
                    <p id="profitDisplay" class="text-3xl font-semibold text-green-400">
                        <?= $currency ?><?= number_format($roi_total, 2) ?>
                    </p>
                </div>
                <div>
                    <p class="text-gray-400 text-sm">Total Return</p>
                    <p class="text-3xl font-semibold text-[#2FE6DE]">
                        <?= $currency ?><?= number_format($amount + $roi_total, 2) ?>
                    </p>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
                <div class="bg-[#1A1428] p-6 rounded-xl space-y-3">
                    <h3 class="text-lg font-medium">Plan Info</h3>
                    <p><span class="text-gray-400">Duration:</span> <?= formatDuration($duration) ?></p>
                    <p><span class="text-gray-400">ROI %:</span> <?= number_format($percent, 2) ?>%</p>
                    <p><span class="text-gray-400">Status:</span> <?= ucfirst($status) ?></p>
                </div>
                <div class="bg-[#1A1428] p-6 rounded-xl space-y-3">
                    <h3 class="text-lg font-medium">Timeline</h3>
                    <p><span class="text-gray-400">Started:</span> <?= formatDateTime($startDt) ?></p>
                    <p><span class="text-gray-400">Ends:</span> <?= formatDateTime($endDt) ?></p>
                    <p><span class="text-gray-400">Time Remaining:</span>
                        <span id="countdown" class="font-semibold text-[#2FE6DE]">Loading...</span>
                    </p>
                    <?php if ($status === 'completed'): ?>
                        <p class="mt-2 text-sm text-yellow-300"><strong>Signal:</strong> STOP — Investment completed</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ROI HISTORY -->
            <div class="mt-10">
                <h3 class="text-xl font-semibold mb-3">ROI History</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full text-sm text-left text-gray-300">
                        <thead class="text-gray-400 uppercase bg-[#1A1428]">
                            <tr><th class="px-4 py-3">Amount</th><th class="px-4 py-3">Percentage</th><th class="px-4 py-3">Date</th></tr>
                        </thead>
                        <tbody id="roiHistoryBody">
                            <?php if (!empty($roiHistory)): foreach ($roiHistory as $r): ?>
                                <tr class="border-b border-[#1A1428] hover:bg-[#1A1428]/50">
                                    <td class="px-4 py-3 text-green-400"><?= $currency ?><?= number_format($r['amount'],2) ?></td>
                                    <td class="px-4 py-3"><?= $r['percentage'] ?>%</td>
                                    <td class="px-4 py-3"><?= formatDateTime(new DateTime($r['created_at'], new DateTimeZone($userTz))) ?></td>
                                </tr>
                            <?php endforeach; else: ?>
                                <tr><td colspan="3" class="text-center py-6 text-gray-500">No ROI history yet.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- REAL-TIME AUTO REFRESH -->
        <script>
        const startTs = <?= json_encode($startTs * 1000) ?>;
        const endTs = <?= json_encode($endTs * 1000) ?>;
        const countdownEl = document.getElementById('countdown');
        function format(ms) {
            if (ms <= 0) return '00:00:00';
            let s = Math.floor(ms / 1000);
            const h = Math.floor(s / 3600);
            s %= 3600;
            const m = Math.floor(s / 60);
            s %= 60;
            return `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
        }
        function tick() {
            const left = endTs - Date.now();
            countdownEl.textContent = format(left);
            if (left > 0) requestAnimationFrame(tick);
        }
        tick();
        setInterval(() => {
            fetch(window.location.href)
              .then(r => r.text())
              .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, "text/html");
                const newBody = doc.querySelector("#roiHistoryBody");
                const newProfit = doc.querySelector("#profitDisplay");
                if (newBody && newProfit) {
                    document.querySelector("#roiHistoryBody").innerHTML = newBody.innerHTML;
                    document.querySelector("#profitDisplay").innerHTML = newProfit.innerHTML;
                }
              });
        }, 300000);
        </script>

    <?php else: ?>
        <div class="bg-[#0F0A1F] text-center p-10 rounded-2xl text-gray-400">
            <i data-lucide="folder-x" class="w-8 h-8 mx-auto mb-3 text-gray-500"></i>
            <p>No investment details found.</p>
        </div>
    <?php endif; ?>
</main>
<?php require("footer.php"); ?>
