<?php
// Standalone Messages Log page with standard filters + pagination
requirePermission($conn, 'message_logs', 'view');

$search = isset($_GET['search']) ? sanitize($conn, $_GET['search']) : '';
$type   = isset($_GET['type']) ? sanitize($conn, $_GET['type']) : '';
$status = isset($_GET['status']) ? sanitize($conn, $_GET['status']) : '';
$user_filter = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$date_from = isset($_GET['date_from']) ? sanitize($conn, $_GET['date_from']) : '';
$date_to   = isset($_GET['date_to']) ? sanitize($conn, $_GET['date_to']) : '';
$page_num = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
$per_page = defined('CRM_DEFAULT_PER_PAGE') ? CRM_DEFAULT_PER_PAGE : 30;
$offset = ($page_num - 1) * $per_page;
$hasCampaignCol = tableExists($conn,'communications') && columnExists($conn,'communications','campaign_id');
$hasSourceTypeCol = tableExists($conn,'communications') && columnExists($conn,'communications','source_type');
$campaignSelect = $hasCampaignCol ? ', ca.name campaign_name' : ', NULL campaign_name';
$sourceSelect = $hasSourceTypeCol ? ', cm.source_type' : ", 'direct' source_type";
$campaignJoin = $hasCampaignCol ? ' LEFT JOIN campaign ca ON ca.id=cm.campaign_id ' : '';

$where = " WHERE cm.account_id=$account_id";
if ($search) $where .= " AND (c.customer_name LIKE '%$search%' OR c.business_name LIKE '%$search%' OR cm.recipient LIKE '%$search%' OR cm.sender LIKE '%$search%' OR cm.subject LIKE '%$search%' OR cm.message LIKE '%$search%' OR cm.response LIKE '%$search%')";
if ($type !== '') {
  $typeMap = ['email'=>1, 'sms'=>2, 'whatsapp'=>3];
  $typeId = $typeMap[$type] ?? (int)$type;
  if ($typeId) $where .= " AND cm.message_type_id=$typeId";
}
if ($status !== '') $where .= " AND cm.status='$status'";
if ($user_filter) $where .= " AND cm.user_id=$user_filter";
if ($date_from) $where .= " AND DATE(cm.date_created) >= '$date_from'";
if ($date_to) $where .= " AND DATE(cm.date_created) <= '$date_to'";

$countRes = $conn->query("SELECT COUNT(*) total FROM communications cm LEFT JOIN customers c ON c.id=cm.customer_id LEFT JOIN users u ON u.id=cm.user_id $where");
$total_rows = ($countRes && $countRes->num_rows) ? (int)$countRes->fetch_assoc()['total'] : 0;
$total_pages = max(1, (int)ceil($total_rows / $per_page));
$users_for_filter = $conn->query("SELECT id,name FROM users WHERE account_id=$account_id ORDER BY name");
$logs = tableExists($conn,'communications') ? $conn->query("SELECT cm.*, u.name user_name, c.customer_name, c.business_name $campaignSelect $sourceSelect FROM communications cm LEFT JOIN users u ON u.id=cm.user_id LEFT JOIN customers c ON c.id=cm.customer_id $campaignJoin $where ORDER BY cm.date_created DESC LIMIT $offset, $per_page") : false;
function crm_msg_type_label($id){ return ((int)$id===1?'Email':((int)$id===2?'SMS':((int)$id===3?'WhatsApp':'Message'))); }
?>
<div class="fade-in">
  <div class="toolbar" style="justify-content:space-between;gap:12px;flex-wrap:wrap">
    <span class="card-title">Messages Log</span>
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
      <input type="hidden" name="page" value="message_logs">
      <input type="text" name="search" class="form-control" style="width:220px" placeholder="Search messages..." value="<?= htmlspecialchars($search) ?>">
      <select name="type" class="form-control" style="width:150px"><option value="">All Types</option><option value="whatsapp" <?= $type==='whatsapp'?'selected':'' ?>>WhatsApp</option><option value="email" <?= $type==='email'?'selected':'' ?>>Email</option><option value="sms" <?= $type==='sms'?'selected':'' ?>>SMS</option></select>
      <select name="status" class="form-control" style="width:140px"><option value="">All Status</option><option value="sent" <?= $status==='sent'?'selected':'' ?>>Sent</option><option value="failed" <?= $status==='failed'?'selected':'' ?>>Failed</option></select>
      <select name="user_id" class="form-control" style="width:170px"><option value="0">All Users</option><?php while($u=$users_for_filter->fetch_assoc()): ?><option value="<?= $u['id'] ?>" <?= $user_filter==$u['id']?'selected':'' ?>><?= htmlspecialchars($u['name']) ?></option><?php endwhile; ?></select>
      <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
      <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
      <button class="btn btn-primary">Filter</button><a class="btn btn-secondary" href="index.php?page=message_logs">Clear</a>
    </form>
  </div>
  <div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Date</th><th>Customer</th><th>Type</th><th>Status</th><th>Recipient</th><th>Source</th><th>Sender</th><th>Message</th><th>Response</th></tr></thead><tbody>
  <?php if(!$logs || $logs->num_rows===0): ?><tr><td colspan="9" class="text-center text-muted">No messages yet</td></tr><?php else: while($m=$logs->fetch_assoc()): ?>
    <tr><td><?= htmlspecialchars($m['date_created']) ?></td><td><?= htmlspecialchars($m['customer_name'] ?: $m['business_name'] ?: '—') ?></td><td><span class="badge badge-blue"><?= crm_msg_type_label($m['message_type_id']) ?></span></td><td><span class="badge badge-<?= $m['status']==='sent'?'green':'red' ?>"><?= htmlspecialchars($m['status']) ?></span></td><td><?= htmlspecialchars($m['recipient'] ?? '') ?></td><td><?= !empty($m['campaign_name']) ? 'Campaign: '.htmlspecialchars($m['campaign_name']) : htmlspecialchars(ucfirst($m['source_type'] ?? 'Direct')) ?></td><td><?= htmlspecialchars($m['sender'] ?? '') ?><?= !empty($m['user_name']) ? '<div class="text-xs text-muted">By '.htmlspecialchars($m['user_name']).'</div>' : '' ?></td><td><?= nl2br(htmlspecialchars(mb_strimwidth($m['message'] ?? '',0,150,'...'))) ?></td><td><?= htmlspecialchars(mb_strimwidth($m['response'] ?? '',0,90,'...')) ?></td></tr>
  <?php endwhile; endif; ?></tbody></table></div>
  <div class="list-footer"><div class="list-count">Showing <strong><?= $total_rows ? number_format($offset + 1) : 0 ?> – <?= number_format(min($offset + ($logs ? $logs->num_rows : 0), $total_rows)) ?></strong> of <strong><?= number_format($total_rows) ?></strong> messages</div><div class="pagination"><?php if($total_pages>1): $baseParams=$_GET; $baseParams['page']='message_logs'; unset($baseParams['p']); if($page_num>1): $baseParams['p']=$page_num-1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($baseParams) ?>">‹</a><?php endif; ?><span class="btn btn-primary btn-sm">Page <?= $page_num ?> / <?= $total_pages ?></span><?php if($page_num<$total_pages): $baseParams['p']=$page_num+1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($baseParams) ?>">›</a><?php endif; endif; ?></div></div>
  </div>
</div>
