<?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') {
   
    // echo "<pre>";
    // print_r($_POST);
    // echo "<pre>";
    // exit;
    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]);

        // FIX: exec() removed — direct include fallback
        $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>
<link rel="stylesheet" href="/assets/css/style.css">
<style>
body { font-family: Arial, sans-serif; background:#f9fafb; margin:0; color:#333; }
header { background:#0d6efd; color:#fff; padding:15px 25px; display:flex; align-items:center; justify-content:space-between; }
header h1 { font-size:20px; margin:0; }
.container { max-width:1000px; margin:30px auto; background:#fff; padding:20px 25px; border-radius:10px; box-shadow:0 2px 8px rgba(0,0,0,0.1); }
h2 { margin-top:0; color:#0d6efd; }
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 { width:100%; border-collapse:collapse; margin-top:20px; }
.table th, .table td { border:1px solid #ddd; padding:10px; text-align:left; }
.table th { background:#f1f1f1; }
.alert { background:#e9fce9; border:1px solid #b4e2b4; padding:10px; margin-bottom:15px; border-radius:5px; }
nav.sidebar { width:220px; background:#fff; border-right:1px solid #ddd; position:fixed; top:0; left:0; height:100vh; padding:20px; }
nav.sidebar a { display:block; padding:10px 15px; color:#333; text-decoration:none; border-radius:5px; margin-bottom:5px; }
nav.sidebar a:hover, nav.sidebar a.active { background:#0d6efd; color:#fff; }
.main { margin-left:240px; padding:20px; }
</style>
</head>
<body>

<!-- Sidebar -->
<nav class="sidebar">
    <h3 style="color:#0d6efd;">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>
</nav>

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

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

    <h2>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>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>
