<?php
session_start();
require __DIR__ . '/../config.php';
if (!isset($_SESSION['admin_id'])) header('Location: login.php');
$pdo = get_pdo();
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['create_template'])) {
        $stmt = $pdo->prepare('INSERT INTO templates (name, html) VALUES (?,?)');
        $stmt->execute([$_POST['name'], $_POST['html']]);
        $msg = '✅ Template saved successfully';
    }
    if (isset($_POST['upload_image']) && isset($_FILES['image'])) {
        $template_id = intval($_POST['template_id']);
        $filename = time() . '_' . basename($_FILES['image']['name']);
        $dest = __DIR__ . '/../uploads/' . $filename;
        move_uploaded_file($_FILES['image']['tmp_name'], $dest);
        $stmt = $pdo->prepare('INSERT INTO template_images (template_id, filename) VALUES (?, ?)');
        $stmt->execute([$template_id, $filename]);
        $msg = '✅ Image uploaded successfully';
    }
}

$templates = $pdo->query('SELECT * FROM templates')->fetchAll(PDO::FETCH_ASSOC);
?>
<!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>
/* ===== Base Styles ===== */
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Poppins', sans-serif;
    background: #f3f4f6;
    color: #1e293b;
    min-height: 100vh;
}

/* ===== Sidebar ===== */
.sidebar {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    width: 240px;
    background: #1e1e2f;
    color: #fff;
    padding: 20px;
    overflow-y: auto;
}
.sidebar h2 {
    font-size: 20px;
    margin-bottom: 25px;
    color: #38bdf8;
}
.sidebar a {
    display: block;
    color: #cbd5e1;
    text-decoration: none;
    padding: 10px 14px;
    border-radius: 6px;
    font-weight: 500;
    margin-bottom: 6px;
    transition: background 0.2s, color 0.2s;
}
.sidebar a.active, .sidebar a:hover {
    background: #334155;
    color: #fff;
}

/* ===== Header ===== */
.header {
    position: fixed;
    top: 0;
    left: 240px;
    right: 0;
    height: 60px;
    background: #fff;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 25px;
    z-index: 1000;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}
.header h1 {
    font-size: 18px;
    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;
    transition: 0.2s;
    margin-left: 8px;
}
.header .btn:hover {
    background: #1e40af;
}

/* ===== Main Content ===== */
.main-content {
    margin-left: 240px;
    padding: 90px 25px 30px 25px;
}
.content-box {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    margin-bottom: 25px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
h2 {
    margin-bottom: 20px;
    color: #1e293b;
}

/* ===== Forms ===== */
form label {
    display: block;
    font-weight: 600;
    margin-top: 10px;
}
input[type=text], textarea, select, input[type=file] {
    width: 100%;
    padding: 10px;
    border-radius: 8px;
    border: 1px solid #d1d5db;
    margin-top: 6px;
    font-size: 14px;
}
textarea { height: 150px; }

.btn-primary {
    background: #2563eb;
    color: white;
    padding: 10px 18px;
    border-radius: 8px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    margin-top: 15px;
}
.btn-primary:hover {
    background: #1e40af;
}

/* ===== Template List ===== */
.template-item {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    background: #f9fafb;
}
.template-preview {
    margin-top: 10px;
    background: #fff;
    border-radius: 8px;
    padding: 8px;
    border: 1px solid #e2e8f0;
}
.template-images img {
    max-width: 150px;
    margin: 5px;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
}

/* ===== Messages ===== */
.success-msg {
    background: #e8f5e9;
    color: #166534;
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 15px;
    font-weight: 500;
}
</style>
</head>
<body>

<!-- Sidebar -->
<div class="sidebar">
    <h2>📊 Admin Panel</h2>
    <a href="dashboard.php">🏠 Dashboard</a>
    <a href="lists.php">📋 Lists</a>
    <a href="templates.php" class="active">📄 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>

<!-- Main Content -->
<div class="main-content">
    <?php if ($msg): ?>
        <div class="success-msg"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>

    <div class="content-box">
        <h2>Create Template</h2>
        <form method="post">
            <label>Name</label>
            <input type="text" name="name" placeholder="Enter template name" required>

            <label>HTML (use [[NAME]])</label>
            <textarea name="html" placeholder="Paste your HTML code..." required></textarea>

            <button class="btn-primary" name="create_template">Save Template</button>
        </form>
    </div>

    <div class="content-box">
        <h2>Upload Image</h2>
        <form method="post" enctype="multipart/form-data">
            <label>Select Template</label>
            <select name="template_id">
                <?php foreach($templates as $t): ?>
                    <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
                <?php endforeach; ?>
            </select>

            <label>Select Image</label>
            <input type="file" name="image" accept="image/*" required>

            <button class="btn-primary" name="upload_image">Upload Image</button>
        </form>
    </div>

    <div class="content-box">
        <h2>Saved Templates</h2>
        <?php foreach($templates as $t): ?>
            <div class="template-item">
                <strong><?= htmlspecialchars($t['name']) ?></strong>

                <div class="template-preview">
                    <iframe srcdoc="<?= htmlspecialchars($t['html']) ?>" style="width:100%;height:300px;border:none;border-radius:6px;"></iframe>
                </div>

                <div class="template-images">
                    <?php
                    $stmt = $pdo->prepare('SELECT filename FROM template_images WHERE template_id = ?');
                    $stmt->execute([$t['id']]);
                    $imgs = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    foreach ($imgs as $img) {
                        echo "<img src='../uploads/" . htmlspecialchars($img['filename']) . "' alt=''>";
                    }
                    ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

</body>
</html>
