<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db  = getDB();
$view_id = (int)($_GET['view'] ?? 0);
$msg = '';

// Update status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $inq_id = (int)$_POST['inq_id'];
    $status = $_POST['status'];
    $db->prepare("UPDATE inquiries SET status=? WHERE id=?")->execute([$status, $inq_id]);
    $msg = 'Status updated.';
}

// Delete
if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM inquiries WHERE id=?")->execute([(int)$_GET['delete']]);
    redirect(SITE_URL . '/admin/inquiries.php?msg=deleted');
}

// Fetch single
$single = null;
if ($view_id) {
    $single = $db->query("SELECT i.*,p.name AS product_name FROM inquiries i LEFT JOIN products p ON i.product_id=p.id WHERE i.id=$view_id")->fetch();
    if ($single && $single['status'] === 'new') {
        $db->prepare("UPDATE inquiries SET status='read' WHERE id=?")->execute([$view_id]);
    }
}

// List
$inquiries = $db->query("SELECT i.*,p.name AS product_name FROM inquiries i LEFT JOIN products p ON i.product_id=p.id ORDER BY i.created_at DESC")->fetchAll();
$page_title = 'Inquiries';
include __DIR__ . '/header.php';
?>
<?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
<?php if (isset($_GET['msg'])): ?><div class="alert alert-success">Inquiry deleted.</div><?php endif; ?>

<?php if ($single): ?>
<div style="margin-bottom:16px;"><a href="inquiries.php" style="color:var(--blue-main);">← Back to Inquiries</a></div>
<div class="card" style="max-width:640px;">
  <div class="card-header"><h2>Inquiry #<?= $single['id'] ?></h2><span class="badge badge-<?= $single['status'] ?>"><?= ucfirst($single['status']) ?></span></div>
  <div class="card-body">
    <table style="width:100%;">
      <?php $rows = ['Name'=>$single['name'],'Phone'=>$single['phone'],'Email'=>$single['email'],'Company'=>$single['company'],'Product'=>$single['product_name'],'Message'=>$single['message'],'Date'=>date('d M Y H:i',strtotime($single['created_at']))]; ?>
      <?php foreach ($rows as $k=>$v): if (!$v) continue; ?>
      <tr><td style="padding:8px 0;font-weight:600;color:var(--text-mid);width:120px;"><?= h($k) ?></td><td style="padding:8px 0;color:var(--text-dark);"><?= h($v) ?></td></tr>
      <?php endforeach; ?>
    </table>
    <form method="POST" style="margin-top:20px;display:flex;gap:10px;align-items:center;">
      <input type="hidden" name="update_status" value="1">
      <input type="hidden" name="inq_id" value="<?= $single['id'] ?>">
      <label style="font-weight:600;font-size:.85rem;">Update Status:</label>
      <select name="status" style="padding:8px 12px;border:1.5px solid #e2e8f0;border-radius:7px;font-family:inherit;">
        <?php foreach (['new','read','replied'] as $s): ?>
        <option value="<?= $s ?>" <?= $single['status']===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
        <?php endforeach; ?>
      </select>
      <button type="submit" class="btn-primary" style="padding:9px 18px;">Update</button>
      <a href="tel:<?= h($single['phone']) ?>" class="btn-primary" style="background:var(--success);padding:9px 18px;">📞 Call</a>
    </form>
  </div>
</div>
<?php else: ?>
<div class="card">
  <div class="card-header"><h2>All Inquiries (<?= count($inquiries) ?>)</h2></div>
  <div class="table-wrap">
    <table>
      <thead><tr><th>#</th><th>Name</th><th>Phone</th><th>Company</th><th>Product</th><th>Date</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
        <?php foreach ($inquiries as $inq): ?>
        <tr>
          <td><?= $inq['id'] ?></td>
          <td><strong><?= h($inq['name']) ?></strong></td>
          <td><a href="tel:<?= h($inq['phone']) ?>"><?= h($inq['phone']) ?></a></td>
          <td><?= h($inq['company']) ?></td>
          <td><?= h($inq['product_name'] ?? '—') ?></td>
          <td><?= date('d M Y', strtotime($inq['created_at'])) ?></td>
          <td><span class="badge badge-<?= $inq['status'] ?>"><?= ucfirst($inq['status']) ?></span></td>
          <td class="action-btns">
            <a href="?view=<?= $inq['id'] ?>" class="btn-action btn-view">View</a>
            <a href="?delete=<?= $inq['id'] ?>" class="btn-action btn-delete" onclick="return confirm('Delete this inquiry?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>
<?php include __DIR__ . '/footer.php'; ?>
