<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once __DIR__ . '/../config.php'; // ✅ safe include

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

$pdo = get_pdo();
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['create_campaign'])) {
        $stmt = $pdo->prepare('INSERT INTO campaigns (name, template_id, list_id, subject, status, created_at) VALUES (?,?,?,?, "draft", NOW())');
        $stmt->execute([
            $_POST['name'],
            $_POST['template_id'],
            $_POST['list_id'],
            $_POST['subject']
        ]);
        $msg = '✅ Campaign created successfully.';
    }

    if (isset($_POST['start_campaign'])) {
        $campaign_id = intval($_POST['campaign_id']);
        $pdo->prepare('UPDATE campaigns SET status="sending" WHERE id=?')->execute([$campaign_id]);

        $send_worker = __DIR__ . '/../send_worker.php';
        if (function_exists('exec')) {
            @exec('php ' . escapeshellarg($send_worker) . ' ' . $campaign_id . ' > /dev/null 2>&1 &');
            $msg = '🚀 Campaign started (background process triggered).';
        } else {
            include $send_worker;
            $msg = '⚙️ Campaign started (sent via direct include).';
        }
    }
}

$templates = $pdo->query('SELECT * FROM templates')->fetchAll();
$lists = $pdo->query('SELECT * FROM lists')->fetchAll();
$campaigns = $pdo->query('SELECT * FROM campaigns ORDER BY created_at DESC')->fetchAll();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Campaigns - Admin Panel</title>
<style>
/* ====== Global ====== */
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
  font-family: "Inter", Arial, sans-serif;
  background: #f3f4f6;
  color: #333;
  min-height: 100vh;
}

/* ====== Sidebar ====== */
.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  width: 240px;
  height: 100vh;
  background: #fff;
  border-right: 1px solid #ddd;
  padding: 20px;
  overflow-y: auto;
}

.sidebar h3 {
  color: #0d6efd;
  margin-bottom: 20px;
  font-size: 22px;
}

.sidebar a {
  display: block;
  padding: 10px 14px;
  color: #333;
  text-decoration: none;
  border-radius: 6px;
  font-weight: 500;
  margin-bottom: 5px;
  transition: 0.2s;
}

.sidebar a:hover,
.sidebar a.active {
  background: #0d6efd;
  color: #fff;
}

/* ====== Header ====== */
header {
  position: fixed;
  top: 0;
  left: 240px;
  right: 0;
  height: 60px;
  background: #0d6efd;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 25px;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

header h1 {
  font-size: 18px;
  margin: 0;
}

/* ====== Main Content ====== */
.main {
  margin-left: 240px;
  padding: 80px 25px 25px 25px;
}

/* ====== Container ====== */
.container {
  background: #fff;
  padding: 20px 25px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

/* ====== Buttons, Forms ====== */
form label {
  display: block;
  margin-top: 10px;
  font-weight: 600;
}

form input,
form select {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button.btn {
  background: #0d6efd;
  color: #fff;
  border: none;
  padding: 8px 14px;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 12px;
}

button.btn:hover {
  background: #0b5ed7;
}

/* ====== Table ====== */
.table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.table th, .table td {
  border: 1px solid #eee;
  padding: 10px;
  text-align: left;
}

.table th {
  background: #f9fafb;
}

/* ====== Alerts ====== */
.alert {
  background: #e9fce9;
  border: 1px solid #b4e2b4;
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 5px;
}
</style>
</head>
<body>

<!-- Sidebar -->
<nav class="sidebar">
    <h3>Admin Panel</h3>
    <a href="dashboard.php">Dashboard</a>
    <a href="lists.php">Lists</a>
    <a href="templates.php">Templates</a>
    <a href="campaigns.php" class="active">Campaigns</a>
    <a href="reports.php">📊 Reports</a>
        <a href="contacts.php">👥 Contacts</a>
        <a href="logout.php">🚪 Logout</a>
</nav>

<!-- Header -->
<header>
    <h1>Campaign Management</h1>
    <a href="logout.php" style="color:#fff;text-decoration:none;">Logout</a>
</header>

<!-- Main Body -->
<div class="main">
  <div class="container">
      <?php if ($msg): ?>
          <div class="alert"><?php echo htmlspecialchars($msg); ?></div>
      <?php endif; ?>

      <h2 style="color:#0d6efd;">Create Campaign</h2>
      <form method="post">
          <label>Name</label>
          <input name="name" required>

          <label>Subject</label>
          <input name="subject" required>

          <label>Template</label>
          <select name="template_id" required>
              <option value="">Select Template</option>
              <?php foreach ($templates as $t): ?>
                  <option value="<?= htmlspecialchars($t['id']) ?>"><?= htmlspecialchars($t['name']) ?></option>
              <?php endforeach; ?>
          </select>

          <label>List</label>
          <select name="list_id" required>
              <option value="">Select List</option>
              <?php foreach ($lists as $l): ?>
                  <option value="<?= htmlspecialchars($l['id']) ?>"><?= htmlspecialchars($l['name']) ?></option>
              <?php endforeach; ?>
          </select>

          <button class="btn" name="create_campaign">Create Campaign</button>
      </form>

      <h2 style="color:#0d6efd;margin-top:25px;">Existing Campaigns</h2>
      <table class="table">
          <tr>
              <th>Name</th>
              <th>Subject</th>
              <th>Status</th>
              <th>Action</th>
          </tr>
          <?php foreach ($campaigns as $c): ?>
              <tr>
                  <td><?= htmlspecialchars($c['name']) ?></td>
                  <td><?= htmlspecialchars($c['subject']) ?></td>
                  <td><?= htmlspecialchars($c['status']) ?></td>
                  <td>
                      <form method="post" style="display:inline;">
                          <input type="hidden" name="campaign_id" value="<?= $c['id'] ?>">
                          <button class="btn" name="start_campaign">Start</button>
                      </form>
                  </td>
              </tr>
          <?php endforeach; ?>
      </table>
  </div>
</div>

</body>
</html>
