<?php
// ====== BOOTSTRAP (tanpa output HTML) ======
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/db.php';

require_login();

$pdo = db();

// ---------- Schema safety (contact_messages) ----------
$pdo->exec("
  CREATE TABLE IF NOT EXISTS contact_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(120) NOT NULL,
    email VARCHAR(160) DEFAULT NULL,
    subject VARCHAR(180) DEFAULT NULL,
    message TEXT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    is_read TINYINT(1) NOT NULL DEFAULT 0
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// ---------- Helpers ----------
function qint($v){ return max(0, (int)$v); }
$ok  = flash('ok');
$err = flash('err');

// ---------- Actions (POST) ----------
if (is_post()){
  csrf_check();
  $action = trim($_POST['action'] ?? '');

  if ($action === 'delete') {
    $id = qint($_POST['id'] ?? 0);
    if ($id > 0){
      $st = $pdo->prepare("DELETE FROM contact_messages WHERE id=?");
      $st->execute([$id]);
      flash('ok','Pesan dihapus.');
    } else {
      flash('err','ID tidak valid.');
    }
    header('Location: contacts.php'); exit;
  }

  if ($action === 'markread') {
    $id = qint($_POST['id'] ?? 0);
    if ($id > 0){
      $pdo->prepare("UPDATE contact_messages SET is_read=1 WHERE id=?")->execute([$id]);
      flash('ok','Pesan ditandai sudah dibaca.');
      header('Location: contacts.php?read='.$id); exit;
    }
    flash('err','ID tidak valid.');
    header('Location: contacts.php'); exit;
  }

  if ($action === 'markunread') {
    $id = qint($_POST['id'] ?? 0);
    if ($id > 0){
      $pdo->prepare("UPDATE contact_messages SET is_read=0 WHERE id=?")->execute([$id]);
      flash('ok','Pesan ditandai belum dibaca.');
      header('Location: contacts.php?read='.$id); exit;
    }
    flash('err','ID tidak valid.');
    header('Location: contacts.php'); exit;
  }
}

// ---------- Read single (GET ?read=ID) ----------
$view = null;
$readId = isset($_GET['read']) ? qint($_GET['read']) : 0;
if ($readId > 0){
  $st = $pdo->prepare("SELECT * FROM contact_messages WHERE id=?");
  $st->execute([$readId]);
  $view = $st->fetch();
  if ($view){
    if ((int)$view['is_read'] === 0){
      $pdo->prepare("UPDATE contact_messages SET is_read=1 WHERE id=?")->execute([$readId]);
      $view['is_read'] = 1;
    }
  } else {
    flash('err', 'Pesan tidak ditemukan.');
    header('Location: contacts.php'); exit;
  }
}

// ---------- List (search + paging) ----------
$kw   = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$pp   = 10;
$off  = ($page - 1) * $pp;

$where = "1=1";
$args  = [];
if ($kw !== ''){
  $where = "(name LIKE ? OR email LIKE ? OR subject LIKE ? OR message LIKE ?)";
  $like  = '%'.$kw.'%';
  $args  = [$like,$like,$like,$like];
}

$cntSt = $pdo->prepare("SELECT COUNT(*) FROM contact_messages WHERE $where");
$cntSt->execute($args);
$total = (int)$cntSt->fetchColumn();
$pages = max(1, (int)ceil($total / $pp));

$listSt = $pdo->prepare("
  SELECT id,name,email,subject,is_read,created_at,LEFT(message,180) AS snippet
  FROM contact_messages
  WHERE $where
  ORDER BY is_read ASC, created_at DESC, id DESC
  LIMIT $pp OFFSET $off
");
$listSt->execute($args);
$rows = $listSt->fetchAll();

// ---------- Output ----------
require_once __DIR__ . '/_layout_top.php';
?>
<div class="container py-4">

  <?php if($ok): ?>
    <div class="alert alert-success d-flex align-items-center"><i class="bi bi-check-circle me-2"></i><div><?php echo e($ok) ?></div></div>
  <?php endif; ?>
  <?php if($err): ?>
    <div class="alert alert-danger d-flex align-items-center"><i class="bi bi-exclamation-triangle me-2"></i><div><?php echo e($err) ?></div></div>
  <?php endif; ?>

  <div class="card shadow-sm mb-4">
    <div class="card-header d-flex flex-wrap gap-2 justify-content-between align-items-center">
      <h5 class="mb-0"><i class="bi bi-inbox me-2"></i>Kontak Masuk</h5>
      <form class="d-flex" method="get" action="contacts.php" role="search">
        <input class="form-control form-control-sm me-2" type="search" name="q" placeholder="Cari nama/email/subject…" value="<?php echo e($kw) ?>">
        <button class="btn btn-sm btn-outline-primary"><i class="bi bi-search"></i></button>
      </form>
    </div>
    <div class="table-responsive">
      <table class="table table-sm align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th style="width:60px;">#</th>
            <th>Pengirim</th>
            <th>Subjek</th>
            <th style="width:160px;">Waktu</th>
            <th style="width:200px;">Aksi</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr class="<?php echo ((int)$r['is_read']===0?'table-warning':''); ?>">
            <td><?php echo (int)$r['id']; ?></td>
            <td>
              <div class="fw-semibold"><?php echo e($r['name']); ?></div>
              <div class="text-muted small"><?php echo e($r['email'] ?: '—'); ?></div>
            </td>
            <td>
              <div class="fw-medium"><?php echo e($r['subject'] ?: '(tanpa subjek)'); ?></div>
              <div class="text-muted small text-truncate" style="max-width:420px;"><?php echo e($r['snippet']); ?><?php echo (strlen($r['snippet'])>=180?'…':''); ?></div>
            </td>
            <td class="text-muted small"><?php echo e($r['created_at']); ?></td>
            <td>
              <div class="d-flex flex-wrap gap-2">
                <a class="btn btn-sm btn-outline-primary" href="contacts.php?read=<?php echo (int)$r['id']; ?>"><i class="bi bi-eye me-1"></i>Lihat</a>
                <?php if((int)$r['is_read']===0): ?>
                  <form method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="markread">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-success"><i class="bi bi-check2-circle me-1"></i>Tandai dibaca</button>
                  </form>
                <?php else: ?>
                  <form method="post" class="d-inline">
                    <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                    <input type="hidden" name="action" value="markunread">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-warning"><i class="bi bi-arrow-counterclockwise me-1"></i>Batal dibaca</button>
                  </form>
                <?php endif; ?>
                <form method="post" class="d-inline" onsubmit="return confirm('Hapus pesan ini?')">
                  <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                  <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash me-1"></i>Hapus</button>
                </form>
              </div>
            </td>
          </tr>
        <?php endforeach; if(empty($rows)): ?>
          <tr><td colspan="5" class="text-center text-muted py-4">Belum ada data.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if($pages > 1): ?>
      <div class="card-footer d-flex justify-content-between align-items-center">
        <div class="text-muted small">Total: <?php echo (int)$total; ?> pesan</div>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <?php
            $base = 'contacts.php';
            $qs = $_GET; unset($qs['page']);
            $baseQs = http_build_query($qs);
            $mk = function($p) use ($base, $baseQs){ return $base.'?'.($baseQs ? $baseQs.'&' : '').'page='.$p; };
            ?>
            <li class="page-item <?php echo ($page<=1?'disabled':''); ?>">
              <a class="page-link" href="<?php echo e($mk(max(1,$page-1))); ?>">&laquo;</a>
            </li>
            <?php
              $start = max(1, $page-2);
              $end   = min($pages, $page+2);
              for($i=$start;$i<=$end;$i++):
            ?>
              <li class="page-item <?php echo ($i===$page?'active':''); ?>">
                <a class="page-link" href="<?php echo e($mk($i)); ?>"><?php echo $i; ?></a>
              </li>
            <?php endfor; ?>
            <li class="page-item <?php echo ($page>=$pages?'disabled':''); ?>">
              <a class="page-link" href="<?php echo e($mk(min($pages,$page+1))); ?>">&raquo;</a>
            </li>
          </ul>
        </nav>
      </div>
    <?php endif; ?>
  </div>

  <!-- Detail Viewer -->
  <?php if($view): ?>
    <div class="card shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-envelope-open me-2"></i>Detail Pesan</h5>
        <a href="contacts.php" class="btn btn-sm btn-outline-secondary"><i class="bi bi-x-lg me-1"></i>Tutup</a>
      </div>
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <div class="mb-2"><span class="text-muted">Nama</span><div class="fw-semibold"><?php echo e($view['name']); ?></div></div>
            <div class="mb-2"><span class="text-muted">Email</span>
              <div class="fw-semibold">
                <?php if(!empty($view['email'])): ?>
                  <a href="mailto:<?php echo e($view['email']); ?>"><?php echo e($view['email']); ?></a>
                <?php else: ?> — <?php endif; ?>
              </div>
            </div>
          </div>
          <div class="col-md-6 text-md-end">
            <div class="mb-2"><span class="text-muted">Waktu</span><div class="fw-semibold"><?php echo e($view['created_at']); ?></div></div>
            <div class="mb-2"><span class="text-muted">Status</span>
              <div>
                <?php if((int)$view['is_read']===1): ?>
                  <span class="badge text-bg-success">Sudah dibaca</span>
                <?php else: ?>
                  <span class="badge text-bg-warning">Belum dibaca</span>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>
        <hr>
        <div class="mb-2"><span class="text-muted">Subjek</span><div class="fw-semibold"><?php echo e($view['subject'] ?: '(tanpa subjek)'); ?></div></div>
        <div class="mb-2"><span class="text-muted">Pesan</span>
          <div class="border rounded p-3" style="white-space:pre-line"><?php echo e($view['message']); ?></div>
        </div>
      </div>
      <div class="card-footer d-flex gap-2">
        <?php if((int)$view['is_read']===0): ?>
          <form method="post">
            <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
            <input type="hidden" name="action" value="markread">
            <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
            <button class="btn btn-success btn-sm"><i class="bi bi-check2-circle me-1"></i>Tandai dibaca</button>
          </form>
        <?php else: ?>
          <form method="post">
            <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
            <input type="hidden" name="action" value="markunread">
            <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
            <button class="btn btn-warning btn-sm"><i class="bi bi-arrow-counterclockwise me-1"></i>Batal dibaca</button>
          </form>
        <?php endif; ?>
        <form method="post" onsubmit="return confirm('Hapus pesan ini?')">
          <input type="hidden" name="csrf" value="<?php echo e(csrf_token()) ?>">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?php echo (int)$view['id']; ?>">
          <button class="btn btn-outline-danger btn-sm"><i class="bi bi-trash me-1"></i>Hapus</button>
        </form>
      </div>
    </div>
  <?php endif; ?>

</div>

<?php require __DIR__ . '/_layout_bottom.php'; ?>
