<?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 estimation_requests SET status = ? WHERE id = ?")
           ->execute([sanitize($_POST['status']), (int)$_POST['id']]);
        setFlash('success','Statut mis à jour.');
    }
    redirect(SITE_URL . '/admin/estimations' . (!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="estimations-' . date('Y-m-d') . '.csv"');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID','Nom','Email','Téléphone','Type','Catégorie','Superficie totale','Superficie hab.','Année','Pièces','Chambres','Finition','Statut','Date'], ';');
    $rows = $db->query("SELECT * FROM estimation_requests ORDER BY created_at DESC")->fetchAll();
    foreach ($rows as $r) {
        fputcsv($out, [$r['id'],$r['nom'],$r['email'],$r['telephone'],$r['type_bien'],$r['categorie'],$r['superficie_totale'],$r['superficie_habitable'],$r['annee_construction'],$r['nombre_pieces'],$r['nombre_chambres'],$r['finition'],$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 estimation_requests WHERE id = ?");
    $stmt->execute([(int)$_GET['id']]);
    $detail = $stmt->fetch();
}

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

$statusColors = [
    'nouveau' => 'bg-black text-white',
    'contacte' => 'border border-blue-300 text-blue-600',
    'estimation_envoyee' => 'border border-green-300 text-green-600',
    'cloture' => 'border border-gray-200 text-gray-400',
];

$pageTitle = 'Demandes d\'estimation'; $activeNav = 'estimations';
include __DIR__ . '/layout.php';
?>

<div class="flex justify-between items-center mb-6">
  <form method="GET" class="flex gap-3">
    <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 les statuts</option>
      <?php foreach(['nouveau','contacte','estimation_envoyee','cloture'] as $s): ?>
      <option value="<?=$s?>" <?=($_GET['status']??'')===$s?'selected':''?>><?=ucfirst(str_replace('_',' ',$s))?></option>
      <?php endforeach; ?>
    </select>
  </form>
  <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-5 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>Demandeur</th><th>Type</th><th>Statut</th><th></th></tr></thead>
      <tbody>
        <?php if(empty($estimations)): ?>
        <tr><td colspan="4" class="text-center py-12 text-gray-400">Aucune demande.</td></tr>
        <?php endif; ?>
        <?php foreach($estimations as $e): ?>
        <tr class="<?=($detail&&$detail['id']==$e['id'])?'bg-gray-50':''?>">
          <td>
            <div class="font-medium text-black text-sm"><?=htmlspecialchars($e['nom'])?></div>
            <div class="text-xs text-gray-400"><?=date('d/m/Y',strtotime($e['created_at']))?></div>
          </td>
          <td class="text-xs text-gray-600 capitalize"><?=htmlspecialchars($e['type_bien']??'—')?></td>
          <td><span class="text-[9px] tracking-[0.1em] uppercase px-2 py-0.5 <?=$statusColors[$e['status']]??''?>"><?=htmlspecialchars($e['status'])?></span></td>
          <td><a href="?id=<?=$e['id']?>" class="text-xs text-gray-400 hover:text-black">→</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <!-- Detail -->
  <div class="lg:col-span-3">
    <?php if ($detail): ?>
    <?php $espaces = $detail['autres_espaces'] ? json_decode($detail['autres_espaces'], true) : []; ?>
    <div class="bg-white border border-gray-200 p-6 space-y-6">
      <!-- Header -->
      <div class="flex justify-between items-start">
        <div>
          <h2 class="font-serif text-xl font-light text-black"><?=htmlspecialchars($detail['nom'])?></h2>
          <p class="text-sm text-gray-500 font-sans"><?=htmlspecialchars($detail['email'])?> — <?=htmlspecialchars($detail['telephone']??'')?></p>
        </div>
        <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-2 py-1 focus:outline-none">
            <?php foreach(['nouveau','contacte','estimation_envoyee','cloture'] as $s): ?>
            <option value="<?=$s?>" <?=$detail['status']===$s?'selected':''?>><?=ucfirst(str_replace('_',' ',$s))?></option>
            <?php endforeach; ?>
          </select>
          <button type="submit" name="update_status" class="bg-black text-white text-xs px-3 py-1 font-sans">OK</button>
        </form>
      </div>

      <!-- 19 Criteria Grid -->
      <div class="grid grid-cols-2 gap-x-8 gap-y-3 text-sm font-sans border-t border-gray-100 pt-6">
        <?php
        $fields = [
            'Adresse' => $detail['adresse_type'] . (($detail['adresse_detail']) ? ' – '.$detail['adresse_detail'] : ''),
            'Type de bien' => ($detail['type_bien'] === 'Autre' ? $detail['type_bien_autre'] : $detail['type_bien']),
            'Catégorie' => $detail['categorie'],
            'Type' => $detail['type_meuble'],
            'Superficie totale' => $detail['superficie_totale'] ? $detail['superficie_totale'].' m²' : '',
            'Superficie hab.' => $detail['superficie_habitable'] ? $detail['superficie_habitable'].' m²' : '',
            'Année construction' => $detail['annee_construction'],
            'Niveaux (Villa)' => $detail['nombre_niveaux'],
            'Pièces' => $detail['nombre_pieces'],
            'Chambres' => $detail['nombre_chambres'],
            'Étage (Appt.)' => $detail['etage'],
            'Surface balcon' => $detail['surface_balcon'] ? $detail['surface_balcon'].' m²' : '',
            'Surface terrasse' => $detail['surface_terrasse'] ? $detail['surface_terrasse'].' m²' : '',
            'Surface jardin' => $detail['surface_jardin'] ? $detail['surface_jardin'].' m²' : '',
            'Autres espaces' => $espaces ? implode(', ',$espaces) : '',
            'Ascenseur' => $detail['ascenseur'],
            'Orientation' => $detail['orientation'],
            'Vue' => $detail['vue'],
            'Finition' => $detail['finition'],
        ];
        foreach ($fields as $label => $val): if (!$val && $val !== '0') continue; ?>
        <div class="border-b border-gray-50 py-2">
          <span class="text-gray-400 text-xs"><?=htmlspecialchars($label)?></span><br/>
          <span class="text-black font-medium"><?=htmlspecialchars((string)$val)?></span>
        </div>
        <?php endforeach; ?>
      </div>

      <?php if($detail['commentaires']): ?>
      <div class="border-t border-gray-100 pt-4">
        <p class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-1">Commentaires</p>
        <p class="text-sm text-gray-700 font-sans"><?=nl2br(htmlspecialchars($detail['commentaires']))?></p>
      </div>
      <?php endif; ?>
    </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 une demande pour voir le détail.</p>
    </div>
    <?php endif; ?>
  </div>
</div>

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