<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();
$db = getDB();

// Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')) {
    if (!empty($_POST['update_status'])) {
        $db->prepare("UPDATE contact_messages SET status = ? WHERE id = ?")
           ->execute([sanitize($_POST['status']), (int)$_POST['id']]);
        setFlash('success', 'Statut mis à jour.');
    }
    if (!empty($_POST['save_note'])) {
        $db->prepare("UPDATE contact_messages SET note_interne = ? WHERE id = ?")
           ->execute([sanitize($_POST['note_interne']), (int)$_POST['id']]);
        setFlash('success', 'Note enregistrée.');
    }
    redirect(SITE_URL . '/admin/contacts' . (!empty($_GET['id']) ? '?id='.(int)$_GET['id'] : ''));
}

// CSV Export
if (isset($_GET['export'])) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="contacts-' . date('Y-m-d') . '.csv"');
    echo "\xEF\xBB\xBF"; // BOM for Excel
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID','Nom','Email','Téléphone','Profil','Profil 2','Message','Statut','Date'], ';');
    $rows = $db->query("SELECT * FROM contact_messages ORDER BY created_at DESC")->fetchAll();
    foreach ($rows as $r) {
        fputcsv($out, [$r['id'],$r['nom'],$r['email'],$r['phone'],$r['profil_je_suis'],$r['profil_je_le_suis'],$r['message'],$r['status'],date('d/m/Y H:i',strtotime($r['created_at']))], ';');
    }
    fclose($out); exit;
}

// View single
$detail = null;
if (!empty($_GET['id'])) {
    $stmt = $db->prepare("SELECT * FROM contact_messages WHERE id = ?");
    $stmt->execute([(int)$_GET['id']]);
    $detail = $stmt->fetch();
    // Mark as read
    if ($detail && $detail['status'] === 'nouveau') {
        $db->prepare("UPDATE contact_messages SET status = 'traite' WHERE id = ?")->execute([(int)$_GET['id']]);
        $detail['status'] = 'traite';
    }
}

// List filters
$where = ['1=1']; $params = [];
if (!empty($_GET['profil'])) { $where[] = "profil_je_suis = ?"; $params[] = $_GET['profil']; }
if (!empty($_GET['status'])) { $where[] = "status = ?"; $params[] = $_GET['status']; }
$whereClause = implode(' AND ', $where);
$contacts = $db->prepare("SELECT * FROM contact_messages WHERE $whereClause ORDER BY created_at DESC");
$contacts->execute($params);
$contacts = $contacts->fetchAll();

$pageTitle = 'Messages de contact'; $activeNav = 'contacts';
include __DIR__ . '/layout.php';
?>

<div class="flex justify-between items-center mb-6">
  <div class="flex gap-3 flex-wrap">
    <form method="GET" class="flex gap-3">
      <select name="profil" onchange="this.form.submit()" class="border border-gray-200 px-3 py-2 text-sm font-sans focus:outline-none focus:border-black">
        <option value="">Tous les profils</option>
        <?php foreach(['Propriétaire','Acheteur','Agent','Investisseur','Vendeur'] as $p): ?>
        <option value="<?=$p?>" <?=($_GET['profil']??'')===$p?'selected':''?>><?=$p?></option>
        <?php endforeach; ?>
      </select>
      <select name="status" onchange="this.form.submit()" class="border border-gray-200 px-3 py-2 text-sm font-sans focus:outline-none focus:border-black">
        <option value="">Tous statuts</option>
        <?php foreach(['nouveau','traite','archive'] as $s): ?>
        <option value="<?=$s?>" <?=($_GET['status']??'')===$s?'selected':''?>><?=ucfirst($s)?></option>
        <?php endforeach; ?>
      </select>
    </form>
  </div>
  <a href="?export=1" class="border border-gray-200 text-xs tracking-[0.1em] uppercase px-4 py-2 font-sans hover:bg-gray-50 transition-colors flex items-center gap-2">
    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>
    Exporter CSV
  </a>
</div>

<div class="grid lg:grid-cols-3 gap-6">
  <!-- List -->
  <div class="lg:col-span-2 bg-white border border-gray-200">
    <table class="w-full admin-table">
      <thead class="border-b border-gray-100"><tr>
        <th>Client</th><th>Profil</th><th>Statut</th><th>Date</th><th></th>
      </tr></thead>
      <tbody>
        <?php if(empty($contacts)): ?>
        <tr><td colspan="5" class="text-center py-12 text-gray-400">Aucun message.</td></tr>
        <?php endif; ?>
        <?php foreach($contacts as $c): ?>
        <tr class="<?=($detail && $detail['id']==$c['id'])?'bg-gray-50':''?>">
          <td>
            <div class="font-medium text-black"><?=htmlspecialchars($c['nom'])?></div>
            <div class="text-xs text-gray-400"><?=htmlspecialchars($c['email'])?></div>
          </td>
          <td class="text-gray-500"><?=htmlspecialchars($c['profil_je_suis']??'—')?></td>
          <td>
            <span class="text-[9px] tracking-[0.1em] uppercase px-2 py-0.5 <?=$c['status']==='nouveau'?'bg-black text-white':($c['status']==='archive'?'border border-gray-200 text-gray-300':'border border-gray-200 text-gray-500')?>">
              <?=$c['status']?>
            </span>
          </td>
          <td class="text-xs text-gray-400"><?=date('d/m/Y', strtotime($c['created_at']))?></td>
          <td><a href="?id=<?=$c['id']?>" class="text-xs text-gray-400 hover:text-black transition-colors">Voir →</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Detail -->
  <div>
    <?php if ($detail): ?>
    <div class="bg-white border border-gray-200 p-6 space-y-5">
      <div>
        <p class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-1">Expéditeur</p>
        <p class="font-medium text-black font-sans"><?=htmlspecialchars($detail['nom'])?></p>
        <p class="text-sm text-gray-500 font-sans"><?=htmlspecialchars($detail['email'])?></p>
        <?php if($detail['phone']): ?><p class="text-sm text-gray-500 font-sans"><?=htmlspecialchars($detail['phone'])?></p><?php endif; ?>
      </div>
      <div>
        <p class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-1">Profils</p>
        <p class="text-sm font-sans">Je suis : <strong><?=htmlspecialchars($detail['profil_je_suis']??'—')?></strong></p>
        <?php if($detail['profil_je_le_suis']): ?>
        <p class="text-sm font-sans">Je le suis : <strong><?=htmlspecialchars($detail['profil_je_le_suis'])?></strong></p>
        <?php endif; ?>
      </div>
      <div>
        <p class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-1">Message</p>
        <p class="text-sm text-gray-700 font-sans leading-relaxed"><?=nl2br(htmlspecialchars($detail['message']))?></p>
      </div>
      <!-- Status update -->
      <form method="POST" class="flex gap-2">
        <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
        <input type="hidden" name="id" value="<?=$detail['id']?>"/>
        <select name="status" class="border border-gray-200 text-xs font-sans px-3 py-2 flex-1 focus:outline-none">
          <?php foreach(['nouveau','traite','archive'] as $s): ?>
          <option value="<?=$s?>" <?=$detail['status']===$s?'selected':''?>><?=ucfirst($s)?></option>
          <?php endforeach; ?>
        </select>
        <button type="submit" name="update_status" class="bg-black text-white text-xs px-4 py-2 font-sans hover:bg-gray-900 transition-colors">OK</button>
      </form>
      <!-- Note -->
      <form method="POST">
        <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
        <input type="hidden" name="id" value="<?=$detail['id']?>"/>
        <p class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Note interne</p>
        <textarea name="note_interne" rows="3" class="w-full border border-gray-200 p-3 text-sm font-sans focus:outline-none focus:border-black resize-none"><?=htmlspecialchars($detail['note_interne']??'')?></textarea>
        <button type="submit" name="save_note" class="mt-2 text-xs tracking-[0.1em] uppercase border border-black px-4 py-2 font-sans hover:bg-black hover:text-white transition-all">Enregistrer la note</button>
      </form>
    </div>
    <?php else: ?>
    <div class="bg-white border border-gray-200 p-8 text-center text-gray-400">
      <p class="text-sm font-sans">Sélectionnez un message pour le consulter.</p>
    </div>
    <?php endif; ?>
  </div>
</div>

<?php include __DIR__ . '/layout_footer.php'; ?>
