
<?php
$page_title = 'Support Chat';
require_once '../config/config.php';
require_once '../config/db.php';
$db = getDbConnection();
$missed = isset($_GET['missed']) && $_GET['missed'] == '1';
if($missed){
  $messages = $db->query("SELECT * FROM support_chat WHERE email_send=1 ORDER BY created_at DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);
}else{
  $messages = $db->query("SELECT * FROM support_chat ORDER BY created_at DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);
}

ob_start();
?>
<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row justify-content-center">
    <div class="col-lg-8">
      <div class="card mb-4">
        <div class="card-header bg-primary text-white">
          <h4 class="mb-0"><i class="fa fa-comments"></i> Support Chat - Clients</h4>
        </div>
        <div class="card-body p-0" style="background:#f7f7f7;border-radius:0 0 12px 12px;">
          <div class="py-4">
            <h5 class="mb-3">Conversations manquées :</h5>
            <?php if (empty($messages)): ?>
              <div class="text-center py-4 text-muted">Aucune conversation manquée.</div>
            <?php else:
              // Regrouper par conversation_id
              $convs = [];
              foreach($messages as $msg){
                $convs[$msg['conversation_id']][] = $msg;
              }
              foreach($convs as $convId => $convMsgs):
                $first = $convMsgs[0];
                $lastMsg = end($convMsgs);
                $isClosed = intval($lastMsg['closed']) === 1;
                $userName = $first['user_name'];
                $userEmail = $first['user_email'];
                $lastDate = $lastMsg['created_at'];
            ?>
              <a href="chat.php?conv=<?php echo $convId; ?>" class="d-block mb-2 p-2 bg-white rounded shadow-sm text-dark" style="text-decoration:none;position:relative;">
                <strong>Conversation #<?php echo $convId; ?></strong>
                <?php if($isClosed): ?>
                  <span style="background:#ff9800;color:#fff;border-radius:12px;padding:2px 10px;font-size:0.95em;font-weight:600;margin-left:10px;vertical-align:middle;display:inline-block;">Manquée</span>
                <?php endif; ?>
                <?php if($userName): ?>
                  <span class="ms-2" style="font-weight:500;color:#007bff;"><?php echo htmlspecialchars($userName); ?></span>
                <?php endif; ?>
                <?php if($userEmail): ?>
                  <span class="ms-2" style="font-size:0.95em;color:#888;">(<?php echo htmlspecialchars($userEmail); ?>)</span>
                <?php endif; ?>
                <span class="text-muted ms-2" style="font-size:0.9em;">Dernier message : <?php echo date('d/m/Y H:i', strtotime($lastDate)); ?></span>
              </a>
            <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php
// Traitement de la réponse admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['chat_id'],$_POST['admin_reply'])) {
    $chat_id = intval($_POST['chat_id']);
    $admin_reply = trim($_POST['admin_reply']);
    if ($chat_id && $admin_reply) {
        $stmt = $db->prepare("UPDATE support_chat SET admin_reply=?, replied_at=NOW() WHERE id=?");
        $stmt->execute([$admin_reply, $chat_id]);
        header('Location: support-chat-admin.php');
        exit;
    }
}
$page_content = ob_get_clean();
include 'template.php';
