<?php
session_start();
if (!isset($_SESSION['admin'])) {
  header('Location: index.php');
  exit();
}
// Load contact messages
$file = '../data/messages.json';
$messages = file_exists($file) ? json_decode(file_get_contents($file), true) : [];

// Load trading tips
$file = '../data/trading_tips.json';
$tips = file_exists($file) ? json_decode(file_get_contents($file), true) : [];

// Load weekly roundups
$file = '../data/weekly_roundup.json';
$weekly = file_exists($file) ? json_decode(file_get_contents($file), true) : [];

// Load market analysis
$file = '../data/market_analysis.json';
$market = file_exists($file) ? json_decode(file_get_contents($file), true) : [];

if (isset($_SESSION['message'])) {
    echo '<p>' . $_SESSION['message'] . '</p>';
    unset($_SESSION['message']);
}

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load posts 
$postsFile = __DIR__ . '/posts.json';
$posts = file_exists($postsFile) ? json_decode(file_get_contents($postsFile), true) : [];

function shortenText($text, $maxLength = 100) {
    if (strlen($text) > $maxLength) {
        $text = substr($text, 0, $maxLength) . '...';
    }
    return $text;
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Admin Dashboard</title>
   <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            background: #f4f4f4;
        }
        .container {
            max-width: 1200px;
            margin: 40px auto;
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .dashboardImage{
          width: 100px;
          height: 100px;
          border-radius: 10px;
        }
        .tags {
      margin-bottom: 10px;
    }
    .tags span {
      background-color: #007bff;
      color: white;
      padding: 2px 5px;
      margin-right: 3px; 
      font-size: 10px;
      border-radius: 5px;
      display: inline-block;
    }
    h2 {
        margin-bottom: 20px;
        text-align: center;
        color: #222;
    }
    table {
        width: 100%;
        border-collapse: collapse;
    }
    thead {
        background-color: #59981a;
        color: #ecf87f;
    }
    th, td {
        padding: 12px 15px;
        border: 1px solid #ddd;
        font-size: 14px;
    }
    tr:nth-child(even) {
        background-color: #f9f9f9;
    }
    .no-messages {
        text-align: center;
        color: #888;
        font-style: italic;
        margin-top: 30px;
    }
    .backtoadmin{
        margin-left: 11%;
        padding: 15px;
        border-radius: 10px;
        background-color: #59981a;
        color: #fff;
        border: none;
        margin-top: 20px;
    }
    .backtoadmin a{
        text-decoration: none;
        color: #ecf87f;
        font-size: 16px;
    }
    .nav{
        width: 1200px;
        margin: 20px auto;
    }
    .edit{
        padding:5px; background:#007bff; color:#fff; margin:2px;
    }
    .delete{
        padding:5px; background:#dc3545; color:#fff;margin:2px;
    }
    .acts{
        display: flex;
    }
    .toggle-btn {
      margin: 10px 0;
      padding: 8px 12px;
      background: transparent;
      color: #59981a;
      border: none;
      cursor: pointer;
      border-radius: 5px;
    }
    .toggle-btn:hover {
      background: #999;
    }
   
    </style>
</head>   
<body>
<div class="nav">
    <h1>Admin Dashboard</h1>
    <a href="new_post.php" style="padding:10px 20px; background:#59981a; color:#ecf87f; text-decoration:none; border-radius:5px; margin-bottom:20px; display:inline-block;">+ Add New Post</a>
    <a href="trading_tips.php" style="padding:10px 20px; background:#59981a; color:#ecf87f; text-decoration:none; border-radius:5px; margin-bottom:20px; display:inline-block;">+ Add Trading tips</a>
    <a href="weekly_roundup.php" style="padding:10px 20px; background:#59981a; color:#ecf87f; text-decoration:none; border-radius:5px; margin-bottom:20px; display:inline-block;">+ Add Weekly Roundup</a>
    <a href="market_analysis.php" style="padding:10px 20px; background:#59981a; color:#ecf87f; text-decoration:none; border-radius:5px; margin-bottom:20px; display:inline-block;">+ Add Market Analysis</a>
</div>

<div class="container">
    <h2 class="toggle-btn" onclick="toggleTable('table1')">Current Posts</h2>
    <?php if (!empty($posts)): ?>
        <table id="table1">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Title</th>
                    <th>Meta Desc.</th>
                    <th>Tags</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($posts)): ?>
                <div class="no-posts">No posts available.</div>
                <?php else: ?>
                <?php foreach (array_reverse($posts) as $index => $post): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td>
                                <?php if (!empty($post['imageurl'])): ?>
                                <img class="dashboardImage" src="../<?= htmlspecialchars($post['imageurl']) ?>" alt="Post image">
                                <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($post['title']) ?></td>
                        <td><?= htmlspecialchars($post['summary']) ?></td>
                        <td>
                            <div class="tags">
                                <?php if (!empty($post['tags'])): ?>
                                <?php foreach ($post['tags'] as $tag): ?>
                                    <span>#<?= htmlspecialchars($tag) ?></span>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                          </td>
                        <td><?= htmlspecialchars($post['published_at']) ?><br></td>
                        <td class="acts">
                            <a class="edit" href="edit_post.php?id=<?= urlencode($post['id']) ?>">Edit</a>
                            <a href="delete_post.php?id=<?= urlencode($post['id']) ?>" class="delete" onclick="return confirm('Delete this post?');">Delete</a>
                        </td>
                    <?php endforeach; ?>
                  <?php endif; ?>
            </tbody>
        </table>
        <?php endif; ?>
</div>

<div class="container" id="messages">
    <h2 class="toggle-btn" onclick="toggleTable('table2')">Inbox - Contact Messages</h2>

    <?php if (!empty($messages)): ?>
        <table id="table2">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Subject</th>
                    <th>Message</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach (array_reverse($messages) as $index => $msg): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td><?= htmlspecialchars($msg['name']) ?></td>
                        <td><?= htmlspecialchars($msg['email']) ?></td>
                        <td><?= htmlspecialchars($msg['subject']) ?></td>
                        <td><?= nl2br(shortenText($msg['message'], 100)) ?></td>
                        <td><?= $msg['date'] ?><br></td>
                        <td>
                            <a href="delete_message.php?id=<?= $index ?>" onclick="return confirm('Delete this message?')">🗑️ Delete</a>
                        </td>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p class="no-messages">No messages received yet.</p>
    <?php endif; ?>
</div>

<div class="container">
    <h2 class="toggle-btn" onclick="toggleTable('table3')">Trading Tips</h2>

    <?php if (!empty($tips)): ?>
        <table id="table3">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Title</th>
                    <th>Content</th>
                    <th>Tags</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <?php if (empty($tips)): ?>
                <div class="no-posts">No posts available.</div>
                <?php else: ?>
                <?php foreach (array_reverse($tips) as $index => $tip): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td>
                                <?php if (!empty($tip['imageurl'])): ?>
                                <img class="dashboardImage" src="../<?= htmlspecialchars($tip['imageurl']) ?>" alt="Post image">
                                <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($tip['title']) ?></td>
                        <td><?= htmlspecialchars($tip['summary']) ?></td>
                        <td>
                            <div class="tags">
                                <?php if (!empty($tip['tags'])): ?>
                                <?php foreach ($tip['tags'] as $tag): ?>
                                    <span>#<?= htmlspecialchars($tag) ?></span>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                          </td>
                        <td><?= htmlspecialchars($tip['published_at']) ?><br></td>
                        <td class="acts">
                            <a class="edit" href="edit_post.php?id=<?= urlencode($tip['id']) ?>">Edit</a>
                            <a href="delete_post.php?id=<?= urlencode($tip['id']) ?>" class="delete" onclick="return confirm('Delete this post?');">Delete</a>
                        </td>
                    <?php endforeach; ?>
                  <?php endif; ?>
            </tbody>
        </table>
        <?php endif; ?>
</div>

<div class="container">
    <h2 class="toggle-btn" onclick="toggleTable('table4')">Weekly Roundups</h2>

    <?php if (!empty($weekly)): ?>
        <table id="table4">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Title</th>
                    <th>Content</th>
                    <th>Tags</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($weekly)): ?>
                <div class="no-posts">No posts available.</div>
                <?php else: ?>
                <?php foreach (array_reverse($weekly) as $index => $week): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td>
                                <?php if (!empty($post['imageurl'])): ?>
                                <img class="dashboardImage" src="../<?= htmlspecialchars($week['imageurl']) ?>" alt="Post image">
                                <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($week['title']) ?></td>
                        <td><?= htmlspecialchars($week['summary']) ?></td>
                        <td>
                            <div class="tags">
                                <?php if (!empty($week['tags'])): ?>
                                <?php foreach ($week['tags'] as $tag): ?>
                                    <span>#<?= htmlspecialchars($tag) ?></span>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                          </td>
                        <td><?= htmlspecialchars($week['published_at']) ?><br></td>
                        <td class="acts">
                            <a class="edit" href="edit_post.php?id=<?= urlencode($week['id']) ?>">Edit</a>
                            <a href="delete_post.php?id=<?= urlencode($week['id']) ?>" class="delete" onclick="return confirm('Delete this post?');">Delete</a>
                        </td>
                    <?php endforeach; ?>
                  <?php endif; ?>
            </tbody>
        </table>
        <?php endif; ?>
</div>

<div class="container">
    <h2 class="toggle-btn" onclick="toggleTable('table5')">Market Analysis</h2>

    <?php if (!empty($market)): ?>
        <table id="table5">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Title</th>
                    <th>Content</th>
                    <th>Tags</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php if (empty($market)): ?>
                <div class="no-posts">No posts available.</div>
                <?php else: ?>
                <?php foreach (array_reverse($market) as $index => $mark): ?>
                    <tr>
                        <td><?= $index + 1 ?></td>
                        <td>
                                <?php if (!empty($mark['imageurl'])): ?>
                                <img class="dashboardImage" src="../<?= htmlspecialchars($mark['imageurl']) ?>" alt="Post image">
                                <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($mark['title']) ?></td>
                        <td><?= htmlspecialchars($mark['summary']) ?></td>
                        <td>
                            <div class="tags">
                                <?php if (!empty($mark['tags'])): ?>
                                <?php foreach ($mark['tags'] as $tag): ?>
                                    <span>#<?= htmlspecialchars($tag) ?></span>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                          </td>
                        <td><?= htmlspecialchars($mark['published_at']) ?><br></td>
                        <td class="acts">
                            <a class="edit" href="edit_post.php?id=<?= urlencode($mark['id']) ?>">Edit</a>
                            <a href="delete_post.php?id=<?= urlencode($mark['id']) ?>" class="delete" onclick="return confirm('Delete this post?');">Delete</a>
                        </td>
                    <?php endforeach; ?>
                  <?php endif; ?>
            </tbody>
        </table>
        <?php endif; ?>
</div>

  <script>
       function toggleTable(tableId) {
      const table = document.getElementById(tableId);
      if (table.style.display === "none") {
        table.style.display = "table";
      } else {
        table.style.display = "none";
      }
    }



      document.getElementById('generateNewsBtn').addEventListener('click', function () {
          const statusEl = document.getElementById('generateStatus');
          statusEl.textContent = '⏳ Generating curated news... Please wait.';

          fetch('generate_news_trigger.php', {
              method: 'POST'
          })
          .then(response => response.json())
          .then(data => {
              if (data.success) {
                  statusEl.textContent = '✅ ' + data.message;
              } else {
                  statusEl.textContent = '❌ ' + data.message;
              }
          })
          .catch(error => {
              statusEl.textContent = '❌ Error occurred: ' + error;
          });
      });
  </script>

</body>
</html>