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

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

$pdo = get_pdo();

// ✅ Delete contact
if (isset($_GET['delete']) && intval($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $pdo->prepare('DELETE FROM list_contacts WHERE id=?')->execute([$id]);
    header('Location: contacts.php');
    exit;
}

// ✅ Export contacts
if (isset($_GET['export']) && intval($_GET['export'])) {
    $list_id = intval($_GET['export']);
    $stmt = $pdo->prepare('SELECT email,name,unsubscribed,bounced,created_at FROM list_contacts WHERE list_id=?');
    $stmt->execute([$list_id]);
    $rows = $stmt->fetchAll();

    header('Content-Type:text/csv');
    header('Content-Disposition: attachment; filename="contacts_list_' . $list_id . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['email', 'name', 'unsubscribed', 'bounced', 'created_at']);
    foreach ($rows as $r) {
        fputcsv($out, [$r['email'], $r['name'], $r['unsubscribed'], $r['bounced'], $r['created_at']]);
    }
    fclose($out);
    exit;
}

// ✅ List + Contacts Query
$list_filter = isset($_GET['list']) ? intval($_GET['list']) : 0;
if ($list_filter) {
    $stmt = $pdo->prepare('SELECT lc.*, l.name as list_name FROM list_contacts lc JOIN lists l ON l.id=lc.list_id WHERE lc.list_id=? ORDER BY lc.created_at DESC');
    $stmt->execute([$list_filter]);
    $contacts = $stmt->fetchAll();
} else {
    $contacts = $pdo->query('SELECT lc.*, l.name as list_name FROM list_contacts lc JOIN lists l ON l.id=lc.list_id ORDER BY lc.created_at DESC')->fetchAll();
}

$lists = $pdo->query('SELECT * FROM lists')->fetchAll();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Contacts - Admin Panel</title>
<style>
* { 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: #1e293b;
  color: #fff;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.sidebar h3 {
  color: #38bdf8;
  margin-bottom: 25px;
  font-size: 22px;
}

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

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

/* ===== Header ===== */
header {
  position: fixed;
  top: 0;
  left: 240px;
  right: 0;
  height: 60px;
  background: #fff;
  color: #1e293b;
  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;
}

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

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

h2 {
  color: #0d6efd;
  margin-bottom: 15px;
}

form label {
  font-weight: 600;
}

select {
  padding: 6px 10px;
  border-radius: 6px;
  border: 1px solid #ccc;
  margin-top: 6px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  font-size: 14px;
}

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

.table th {
  background: #f9fafb;
  font-weight: 600;
}

.btn {
  display: inline-block;
  background: #2563eb;
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  text-decoration: none;
  font-size: 14px;
  transition: background 0.2s;
}

.btn:hover {
  background: #1e40af;
}

a.delete-link {
  color: #dc2626;
  text-decoration: none;
}

a.delete-link:hover {
  text-decoration: underline;
}
</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">📧 Campaigns</a>
  <a href="reports.php">📊 Reports</a>
  <a href="contacts.php" class="active">👥 Contacts</a>
  <a href="logout.php">🚪 Logout</a>
</nav>

<!-- Header -->
<header>
  <h1>Contacts Management</h1>
  <a href="logout.php" class="btn">Logout</a>
</header>

<!-- Main Content -->
<div class="main">
  <div class="container">
    <h2>👥 Contact List</h2>

    <form method="get">
      <label>Filter by List:</label><br>
      <select name="list" onchange="this.form.submit()">
        <option value="0">All Lists</option>
        <?php foreach ($lists as $l):
          $sel = ($list_filter == $l['id']) ? 'selected' : ''; ?>
          <option value="<?= $l['id'] ?>" <?= $sel ?>><?= htmlspecialchars($l['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </form>

    <p style="margin-top:10px;">
      <a class="btn" href="contacts.php?export=<?= $list_filter ?: 0; ?>">📤 Export CSV (Current List)</a>
    </p>

    <table class="table">
      <tr>
        <th>ID</th>
        <th>Email</th>
        <th>Name</th>
        <th>List</th>
        <th>Unsub</th>
        <th>Bounced</th>
        <th>Added</th>
        <th>Action</th>
      </tr>
      <?php foreach ($contacts as $c): ?>
        <tr>
          <td><?= $c['id'] ?></td>
          <td><?= htmlspecialchars($c['email']) ?></td>
          <td><?= htmlspecialchars($c['name']) ?></td>
          <td><?= htmlspecialchars($c['list_name']) ?></td>
          <td><?= $c['unsubscribed'] ? 'Yes' : 'No' ?></td>
          <td><?= $c['bounced'] ? 'Yes' : 'No' ?></td>
          <td><?= $c['created_at'] ?></td>
          <td>
            <a class="delete-link" href="contacts.php?delete=<?= $c['id'] ?>" onclick="return confirm('Are you sure?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </table>
  </div>
</div>

</body>
</html>
