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

// ------------------- SESSION & TIMEZONE AJAX HANDLER -------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_timezone'])) {
    $_SESSION['user_timezone'] = preg_replace('/[^A-Za-z0-9_\/\-\+]/', '', $_POST['user_timezone']);
    $_SESSION['user_location'] = $_POST['user_location'] ?? 'Unknown';
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['status' => 'ok', 'tz' => $_SESSION['user_timezone']]);
    exit;
}

if (!isset($_SESSION['user_timezone']) || empty($_SESSION['user_timezone'])) {
    $_SESSION['user_timezone'] = 'UTC';
}
$userTz = $_SESSION['user_timezone'];
date_default_timezone_set($userTz);

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

// ------------------- FETCH INVESTMENTS -------------------
try {
    $stmt = $pdo->prepare("SELECT * FROM invest WHERE email = ? ORDER BY id DESC");
    $stmt->execute([$email]);
    $investments = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Database Error: " . htmlspecialchars($e->getMessage()));
}

// ------------------- DATETIME HELPERS -------------------
function dtLocalOrUtc(string $localTime = null, string $utcTime = null, string $userTz = 'UTC'): ?DateTime {
    try {
        if (!empty($localTime)) {
            // 🟢 Local time is already in user's timezone
            return new DateTime($localTime, new DateTimeZone($userTz));
        } elseif (!empty($utcTime)) {
            // 🟢 Convert UTC timestamp to user's timezone
            $dt = new DateTime($utcTime, new DateTimeZone('UTC'));
            $dt->setTimezone(new DateTimeZone($userTz));
            return $dt;
        }
    } catch (Exception $e) {
        return null;
    }
    return null;
}

function formatForDisplay(?DateTime $dt): string {
    if (!$dt) return 'N/A';
    return $dt->format('M d, Y h:i A');
}

function humanDuration(int $minutes): string {
    if ($minutes < 60) return "$minutes minute" . ($minutes == 1 ? '' : 's');
    if ($minutes < 1440) {
        $h = floor($minutes / 60);
        $m = $minutes % 60;
        return "$h hour" . ($h == 1 ? '' : 's') . ($m ? " $m min" : '');
    }
    if ($minutes < 10080) {
        $d = floor($minutes / 1440);
        return "$d day" . ($d == 1 ? '' : 's');
    }
    if ($minutes < 43200) {
        $w = floor($minutes / 10080);
        return "$w week" . ($w == 1 ? '' : 's');
    }
    $mo = floor($minutes / 43200);
    return "$mo month" . ($mo == 1 ? '' : 's');
}

function statusBadge(array &$inv, DateTime $endDt, DateTime $nowDt, PDO $pdo) {
    $stored = strtolower(trim($inv['status'] ?? ''));
    $computed = ($nowDt > $endDt) ? 'expired' : 'active';
    if ($stored !== $computed) {
        try {
            $pdo->prepare("UPDATE invest SET status = ? WHERE id = ?")
                ->execute([$computed, $inv['id']]);
            $inv['status'] = $computed;
        } catch (PDOException $e) {}
    }
    $display = strtolower($inv['status']);
    if ($display === 'active') return ['text'=>'Active','color'=>'bg-[#2FE6DE]/10 text-[#2FE6DE]','icon'=>'check-circle'];
    if ($display === 'expired') return ['text'=>'Expired','color'=>'bg-red-400/10 text-red-400','icon'=>'clock'];
    if ($display === 'completed') return ['text'=>'Completed','color'=>'bg-green-500/10 text-green-400','icon'=>'badge-check'];
    return ['text'=>ucfirst($display),'color'=>'bg-gray-500/10 text-gray-400','icon'=>'minus-circle'];
}

$nowUser = new DateTime('now', new DateTimeZone($userTz));
?>

<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden">
    <div class="bg-[#0F0A1F] rounded-2xl p-6 mb-6">
        <div class="flex flex-col sm:flex-row items-center justify-between gap-4">
            <div class="flex items-center gap-4">
                <div class="bg-[#1A1428] p-3 rounded-xl">
                    <i data-lucide="briefcase" class="w-6 h-6 text-[#2FE6DE]"></i>
                </div>
                <div>
                    <h1 class="text-xl font-medium">My Investment Plans</h1>
                    <div class="flex items-center text-sm text-gray-400">
                        <a href="dashboard.php" class="hover:text-[#2FE6DE]">Dashboard</a>
                        <i data-lucide="chevron-right" class="w-4 h-4 mx-2"></i>
                        <span>My Plans</span>
                    </div>
                </div>
            </div>
            <div class="text-sm text-gray-400">
                <span id="tzLabel"><?= htmlspecialchars($userTz) ?></span> —
                <span id="userTime"><?= $nowUser->format('M d, Y h:i:s A') ?></span>
            </div>
        </div>
    </div>

    <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <?php if (!empty($investments)): ?>
            <?php foreach ($investments as $inv): 
                $plan = htmlspecialchars($inv['plan'] ?? 'Unnamed');
                $amount = number_format((float)($inv['amount'] ?? 0), 2);
                $currency = htmlspecialchars($inv['user_cur'] ?? '$');
                $durationMin = (int)($inv['duration'] ?? 0);

                // ✅ Use user's local_time directly if available
                $startDt = dtLocalOrUtc($inv['local_time'] ?? null, $inv['date'] ?? null, $userTz);
                $endDt = clone $startDt;
                $endDt->modify("+{$durationMin} minutes");

                $startDisplay = formatForDisplay($startDt);
                $endDisplay = formatForDisplay($endDt);
                $durationText = humanDuration($durationMin);

                $statusData = statusBadge($inv, $endDt, $nowUser, $pdo);
                $invId = (int)$inv['id']; // ✅ use ID
            ?>
            <div class="bg-[#0F0A1F] rounded-2xl hover:shadow-lg hover:shadow-[#2FE6DE]/5 transition-all duration-300">
                <div class="p-6 border-b border-[#1A1428]">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center gap-3">
                            <div class="bg-[#1A1428] p-2 rounded-lg">
                                <i data-lucide="trending-up" class="w-5 h-5 text-[#2FE6DE]"></i>
                            </div>
                            <h4 class="font-medium"><?= $plan ?></h4>
                        </div>
                        <div class="flex items-center gap-2 px-3 py-1 rounded-full <?= $statusData['color'] ?> text-sm">
                            <i data-lucide="<?= $statusData['icon'] ?>" class="w-4 h-4"></i>
                            <span><?= $statusData['text'] ?></span>
                        </div>
                    </div>
                    <div class="flex items-baseline gap-2">
                        <span class="text-2xl font-medium"><?= $currency ?><?= $amount ?></span>
                        <span class="text-sm text-gray-400">Invested</span>
                    </div>
                </div>

                <div class="p-6 space-y-4">
                    <div class="flex items-center gap-3">
                        <div class="bg-[#1A1428] p-2 rounded-lg"><i data-lucide="clock" class="w-4 h-4 text-[#2FE6DE]"></i></div>
                        <div>
                            <div class="text-sm text-gray-400">Duration</div>
                            <div><?= $durationText ?></div>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <div class="bg-[#1A1428] p-2 rounded-lg"><i data-lucide="calendar" class="w-4 h-4 text-[#2FE6DE]"></i></div>
                        <div>
                            <div class="text-sm text-gray-400">Started</div>
                            <div><?= $startDisplay ?></div>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <div class="bg-[#1A1428] p-2 rounded-lg"><i data-lucide="calendar-x" class="w-4 h-4 text-[#2FE6DE]"></i></div>
                        <div>
                            <div class="text-sm text-gray-400">Ends</div>
                            <div><?= $endDisplay ?></div>
                        </div>
                    </div>
                </div>

                <div class="p-6 border-t border-[#1A1428]">
                    <a href="investment_details.php?plan=<?= $invId ?>"
                       class="flex items-center justify-between p-3 bg-[#1A1428] text-[#2FE6DE] rounded-xl hover:bg-[#2A243B] transition-colors group">
                        <span>View Details</span>
                        <i data-lucide="arrow-right" class="w-5 h-5 group-hover:translate-x-1 transition-transform"></i>
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-span-full text-center text-gray-400 py-10">
                <i data-lucide="folder-x" class="w-8 h-8 mx-auto mb-3 text-gray-500"></i>
                <p>No investments found yet.</p>
            </div>
        <?php endif; ?>
    </div>
</main>

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

<script>
// Auto-update local clock every second
setInterval(() => {
    const el = document.getElementById('userTime');
    if (el) {
        const now = new Date();
        el.textContent = now.toLocaleString([], {
            month:'short', day:'2-digit', year:'numeric',
            hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:true
        });
    }
}, 1000);
</script>
