<?php
session_start();
require __DIR__ . '/../config.php';
require __DIR__ . '/../vendor/smtp_mailer.php';

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CREATE LIST
    if (isset($_POST['create_list'])) {
        $stmt = $pdo->prepare('INSERT INTO lists (name) VALUES (?)');
        $stmt->execute([$_POST['name']]);
        $msg = '✅ List created successfully!';
    }

    // UPLOAD CSV
    if (isset($_POST['upload_csv']) && isset($_FILES['csv'])) {
        $list_id = intval($_POST['list_id']);
        $double_optin = isset($_POST['double_optin']) ? 1 : 0;
        $csv = fopen($_FILES['csv']['tmp_name'], 'r');
        $count = 0;

        while (($row = fgetcsv($csv)) !== false) {
            $email = trim($row[0]);
            $name = $row[1] ?? '';
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $stmt = $pdo->prepare('INSERT INTO list_contacts (list_id,email,name,unsubscribed) VALUES (?,?,?,?)');
                $stmt->execute([$list_id, $email, $name, $double_optin ? 1 : 0]);
                $contact_id = $pdo->lastInsertId();
                $count++;

                if ($double_optin) {
                    $token = md5($contact_id . (get_config()['unsubscribe_secret'] ?? 'secret_key'));
                    $confirm_url = get_config()['base_url'] . '/public/confirm_subscribe.php?cid=' . $contact_id . '&token=' . $token;
                    $subject = 'Confirm your subscription';
                    $body = "<p>Hello " . htmlspecialchars($name) . ",</p>
                            <p>Please confirm your subscription:
                            <a href='" . $confirm_url . "'>Confirm subscription</a></p>";
                    send_smtp_mail(get_config(), $email, $name, $subject, $body);
                }
            }
        }
        fclose($csv);
        $msg = "✅ Uploaded $count contacts" . ($double_optin ? ' (confirmation emails sent)' : '');
    }

    // DELETE LIST
    if (isset($_POST['delete_list'])) {
        $list_id = intval($_POST['list_id']);
        $pdo->prepare('DELETE FROM list_contacts WHERE list_id=?')->execute([$list_id]);
        $pdo->prepare('DELETE FROM lists WHERE id=?')->execute([$list_id]);
        $msg = '🗑️ List deleted successfully!';
    }
}

$lists = $pdo->query('SELECT * FROM lists')->fetchAll();
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Templates Management</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Poppins', sans-serif; background: #f8fafc; color: #1e293b; }

/* Sidebar */
.sidebar {
    position: fixed; top: 0; left: 0;
    width: 240px; height: 100%;
    background: #1e293b; color: #fff;
    overflow-y: auto; z-index: 100;
}
.sidebar h2 { font-size: 20px; padding: 20px; color: #38bdf8; }
.sidebar a {
    display: block; padding: 12px 20px;
    color: #cbd5e1; text-decoration: none;
    border-radius: 6px; transition: 0.2s;
}
.sidebar a:hover, .sidebar a.active { background: #334155; color: #fff; }

/* Header */
.header {
    position: fixed; top: 0; left: 240px; right: 0;
    height: 70px; background: #fff;
    display: flex; align-items: center; justify-content: space-between;
    padding: 0 25px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); z-index: 90;
}
.header h1 { font-size: 20px; font-weight: 600; }
.header .btn {
    background: #2563eb; color: #fff; border: none;
    padding: 8px 16px; border-radius: 8px; cursor: pointer;
    text-decoration: none; font-weight: 500; margin-left: 8px;
}
.header .btn:hover { background: #1e40af; }

/* Main content */
.container {
    margin-left: 240px; padding: 100px 25px 40px;
    background: #f8fafc; min-height: 100vh;
}

/* Cards */
.card {
    background: #fff; border-radius: 12px;
    padding: 25px; box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    margin-bottom: 25px; max-width: 700px;
}

/* Forms */
form label { display: block; margin-bottom: 6px; font-weight: 500; }
input[type=text], select, input[type=file] {
    width: 100%; padding: 10px; border: 1px solid #d1d5db;
    border-radius: 8px; margin-bottom: 12px;
}
.btn-primary {
    background: #2563eb; color: #fff; border: none;
    padding: 10px 18px; border-radius: 8px;
    font-weight: 600; cursor: pointer;
}
.btn-primary:hover { background: #1d4ed8; }
.btn-danger { background: #dc2626; color: #fff; border: none; padding: 8px 14px; border-radius: 8px; cursor: pointer; }
.btn-danger:hover { background: #b91c1c; }

/* Message */
.message {
    background: #dcfce7; color: #166534;
    border: 1px solid #86efac; padding: 12px;
    border-radius: 8px; margin-bottom: 20px; font-weight: 500;
}

/* List */
.list-item {
    display: flex; justify-content: space-between;
    align-items: center; border-bottom: 1px solid #e5e7eb; padding: 10px 0;
}
.list-item a { text-decoration: none; color: #2563eb; }
.list-item a:hover { text-decoration: underline; }
</style>
</head>
<body>

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

<!-- Header -->
<div class="header">
    <h1>Templates Management</h1>
    <div>
        <button class="btn">🌙</button>
        <a href="logout.php" class="btn">Logout</a>
    </div>
</div>

<!-- Page content -->
<div class="container">
    <?php if ($msg): ?>
        <div class="message"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>

    <div class="card">
        <h3>Create New List</h3>
        <form method="post">
            <label>New List Name</label>
            <input type="text" name="name" required placeholder="Enter list name">
            <button class="btn-primary" name="create_list">Create List</button>
        </form>
    </div>

    <div class="card">
        <h3>Upload CSV to List</h3>
        <form method="post" enctype="multipart/form-data">
            <label>Select List</label>
            <select name="list_id" required>
                <option value="">-- Choose List --</option>
                <?php foreach ($lists as $l): ?>
                    <option value="<?= $l['id'] ?>"><?= htmlspecialchars($l['name']) ?></option>
                <?php endforeach; ?>
            </select>

            <label>CSV file (email,name)</label>
            <input type="file" name="csv" accept=".csv" required>

            <label><input type="checkbox" name="double_optin" value="1"> Use double opt-in</label>
            <button class="btn-primary" name="upload_csv">Upload CSV</button>
        </form>
    </div>

    <div class="card">
        <h3>Existing Lists</h3>
        <?php if (count($lists) === 0): ?>
            <p>No lists created yet.</p>
        <?php else: ?>
            <?php foreach ($lists as $l): ?>
                <div class="list-item">
                    <div>
                        <strong><?= htmlspecialchars($l['name']) ?></strong> —
                        <a href="contacts.php?list=<?= $l['id'] ?>">View Contacts</a>
                    </div>
                    <form method="post" onsubmit="return confirm('Are you sure you want to delete this list?')">
                        <input type="hidden" name="list_id" value="<?= $l['id'] ?>">
                        <button class="btn-danger" name="delete_list">Delete</button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

</body>
</html>
