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

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

$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>
<head>
<meta charset="utf-8">
<title>Lists | Admin Panel</title>
<link rel="stylesheet" href="/assets/css/style.css">
<style>
body {
    background: #f5f6fa;
    font-family: "Inter", sans-serif;
    margin: 0;
    color: #333;
}
.container {
    margin-left: 260px;
    padding: 30px;
}
h1 {
    font-size: 28px;
    margin-bottom: 20px;
    color: #1e293b;
}
.card {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    margin-bottom: 25px;
}
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 {
    background: #2563eb;
    color: #fff;
    padding: 10px 18px;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 600;
}
.btn:hover { background: #1d4ed8; }
.btn-danger {
    background: #dc2626;
}
.btn-danger:hover {
    background: #b91c1c;
}
.message {
    background: #dcfce7;
    color: #166534;
    border: 1px solid #86efac;
    padding: 10px 15px;
    border-radius: 8px;
    margin-bottom: 20px;
}
.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;
}
</style>
</head>

<body>
<!-- Sidebar -->
<?php include 'sidebar.php'; ?>

<div class="container">
    <h1>📋 Lists</h1>

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

    <!-- Create List -->
    <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" name="create_list">Create List</button>
        </form>
    </div>

    <!-- Upload CSV -->
    <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){ echo "<option value='{$l['id']}'>".htmlspecialchars($l['name'])."</option>"; } ?>
            </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" name="upload_csv">Upload CSV</button>
        </form>
    </div>

    <!-- Existing Lists -->
    <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><?php echo htmlspecialchars($l['name']); ?></strong>  
                        — <a href="contacts.php?list=<?php echo $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="<?php echo $l['id']; ?>">
                        <button class="btn btn-danger" name="delete_list">Delete</button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
