<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Africa/Nairobi');
session_start();
require_once 'db.php';

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

$user_id = $_SESSION['user_id'];
$message = '';
$claimed_id = null;

// Handle task completion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_task'], $_POST['investment_id'])) {
    $investment_id = intval($_POST['investment_id']);
    
    $stmt = $conn->prepare("SELECT * FROM investments WHERE id = ? AND user_id = ? AND status = 'active'");
    $stmt->bind_param("ii", $investment_id, $user_id);
    $stmt->execute();
    $investment = $stmt->get_result()->fetch_assoc();

    if ($investment) {
        $last_time = strtotime($investment['last_earnings_time'] ?? '');
        $now = time();

        if (!$last_time || ($now - $last_time) >= 86400) {
            $income = (float)$investment['daily_earnings'];

            // Update user balance and income
            $updateUser = $conn->prepare("UPDATE users SET balance = balance + ?, income = income + ? WHERE id = ?");
            $updateUser->bind_param("ddi", $income, $income, $user_id);
            $updateUser->execute();

            // Update investment
            $updateInv = $conn->prepare("UPDATE investments SET total_earned = total_earned + ?, last_earnings_time = NOW() WHERE id = ?");
            $updateInv->bind_param("di", $income, $investment_id);
            $updateInv->execute();

            $message = "✅ Task for Investment ID {$investment_id} completed. ZMW " . number_format($income, 2) . " added!";
            $claimed_id = $investment_id;
        } else {
            $message = "❌ You can only complete this task every 24 hours.";
        }
    }
}

// Fetch all active investments
$sql = "SELECT * FROM investments WHERE user_id = ? AND status = 'active'";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$investments = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Daily Task</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
  <style>
    body { background: #0f1a24; color: #fff; font-family: 'Segoe UI', sans-serif; padding: 20px; padding-bottom: 80px; }
    .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
    .title { font-size: 20px; font-weight: bold; color: #00bfff; }
    .lang-btn { background: #16222a; border: 1px solid #1ca7ec; border-radius: 20px; padding: 5px 12px; color: #1ca7ec; cursor: pointer; font-size: 14px; }

    .task-card { margin-top: 20px; background: linear-gradient(to bottom, #16222a, #0f1a24); border-radius: 15px; padding: 15px; display: flex; align-items: center; gap: 15px; box-shadow: 0 0 8px rgba(0, 191, 255, 0.3); }
    .task-card img { width: 70px; border-radius: 10px; }
    .task-info { flex: 1; }
    .task-info h3 { margin-bottom: 5px; color: #00bfff; }
    .task-info p { margin: 3px 0; font-size: 14px; color: #ccc; }

    .complete-btn { background: linear-gradient(to right, #1e3c72, #2a5298); border: none; padding: 8px 18px; border-radius: 20px; cursor: pointer; font-weight: bold; color: white; transition: 0.3s; }
    .complete-btn:hover { background: linear-gradient(to right, #2a5298, #1ca7ec); }
    .complete-btn[disabled] { background: #444; cursor: not-allowed; }

    .message { margin-top: 15px; background: linear-gradient(to right, #1e3c72, #2a5298); padding: 10px; border-radius: 10px; color: #ffc107; font-weight: bold; text-align: center; box-shadow: 0 0 10px rgba(0,191,255,0.5); animation: glow 1s infinite alternate; }
    @keyframes glow { from { box-shadow: 0 0 10px #00bfff; } to { box-shadow: 0 0 20px #1ca7ec, 0 0 30px #00bfff; } }

    .reset-label { font-size: 13px; color: #1ca7ec; margin-top: 5px; }

    .bottom-nav { position: fixed; bottom: 0; left: 0; width: 100%; background: #16222a; display: flex; justify-content: space-around; padding: 10px 0; border-top: 1px solid #1ca7ec; }
    .bottom-nav div { text-align: center; font-size: 13px; color: #ccc; }
    .bottom-nav div.active { color: #00bfff; }
    .bottom-nav i { display: block; font-size: 18px; margin-bottom: 4px; }

    a { text-decoration: none; color: inherit; }
  </style>
</head>
<body>

<div class="header">
  <div class="title">Daily Task</div>
  <button class="lang-btn">🌐 English</button>
</div>

<?php if ($message): ?>
  <div class="message" id="flash-message"><?= $message ?></div>
<?php endif; ?>

<?php if ($investments->num_rows > 0): 
  while ($investment = $investments->fetch_assoc()):
    $invId = $investment['id'];
    $canClaim = !$investment['last_earnings_time'] || (time() - strtotime($investment['last_earnings_time']) >= 86400);
    $remaining = 86400 - (time() - strtotime($investment['last_earnings_time']));
    if ($remaining < 0) $remaining = 0;
?>
  <div class="task-card">
    <img src="ai.jpg" alt="AI">
    <div class="task-info">
      <h3>ID: <?= htmlspecialchars($invId) ?></h3>
      <p>Price: ZMW <?= number_format($investment['amount'], 2) ?></p>
      <p>Daily Income: ZMW <?= number_format($investment['daily_earnings'], 2) ?></p>
      <div class="reset-label">🕒 Reset in: <span id="timer<?= $invId ?>"></span></div>
    </div>
    <?php if ($canClaim): ?>
      <form method="POST">
        <input type="hidden" name="complete_task" value="1" />
        <input type="hidden" name="investment_id" value="<?= $invId ?>" />
        <button class="complete-btn" type="submit">To complete</button>
      </form>
    <?php else: ?>
      <button class="complete-btn" disabled>Completed</button>
    <?php endif; ?>
  </div>

  <script>
    let remaining<?= $invId ?> = <?= $remaining ?>;
    function formatTime<?= $invId ?>(s) {
      let h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
      return [h, m, sec].map(n => String(n).padStart(2, '0')).join(':');
    }
    setInterval(() => {
      if (remaining<?= $invId ?> > 0) {
        remaining<?= $invId ?>--;
        document.getElementById('timer<?= $invId ?>').textContent = formatTime<?= $invId ?>(remaining<?= $invId ?>);
      }
    }, 1000);
  </script>
<?php endwhile; else: ?>
  <div class="message">❌ You have no active investments.</div>
<?php endif; ?>

<div class="bottom-nav">
  <a href="home.php"><div><i class="fas fa-home"></i>Home</div></a>
  <a href="task.php"><div class="active"><i class="fas fa-tasks"></i>Task</div></a>
  <a href="team.php"><div><i class="fas fa-users"></i>Team</div></a>
  <a href="vip.php"><div><i class="fas fa-crown"></i>VIP</div></a>
  <a href="me.php"><div><i class="fas fa-user"></i>Me</div></a>
</div>

<script>
  const flash = document.getElementById('flash-message');
  if (flash) {
    setTimeout(() => { flash.style.display = 'none'; }, 5000);
  }
</script>

</body>
</html>
