<?php
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 = 20;
$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 = ['whatsapp'=>1, 'sms'=>2, 'email'=>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 = tableExists($conn,'communications') ? $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") : false;
$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?'WhatsApp':((int)$id===2?'SMS':((int)$id===3?'Email':'Message'))); }
function crm_msg_source_label($m){ return !empty($m['campaign_name']) ? 'Campaign: '.$m['campaign_name'] : ucfirst($m['source_type'] ?? 'Direct'); }
?>
<div class="fade-in message-log-page">
  <div class="card filter-card-clean" style="padding:18px;margin-bottom:16px">
    <form method="get" class="message-log-filter">
      <input type="hidden" name="page" value="message_logs">
      <div class="form-group"><label class="form-label">Search</label><input type="text" name="search" class="form-control" placeholder="Search..." value="<?= htmlspecialchars($search) ?>"></div>
      <div class="form-group"><label class="form-label">Type</label><select name="type" class="form-control"><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></div>
      <div class="form-group"><label class="form-label">Status</label><select name="status" class="form-control"><option value="">All Status</option><option value="sent" <?= $status==='sent'?'selected':'' ?>>Sent</option><option value="failed" <?= $status==='failed'?'selected':'' ?>>Failed</option></select></div>
      <div class="form-group"><label class="form-label">User</label><select name="user_id" class="form-control"><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></div>
      <div class="form-group"><label class="form-label">From Date</label><input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>"></div>
      <div class="form-group"><label class="form-label">To Date</label><input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>"></div>
      <div class="form-group" style="align-self:end"><button class="btn btn-primary">Filter</button> <a class="btn btn-secondary" href="index.php?page=message_logs">Clear</a></div>
    </form>
  </div>

  <div class="card message-log-card">
    <div class="card-header-clean"><span class="card-title">Messages Log</span><span class="text-xs text-muted"><?= number_format($total_rows) ?> messages</span></div>
    <div class="table-wrapper"><table class="crm-table message-log-table"><thead><tr><th style="width:145px">Date</th><th style="width:160px">Customer</th><th style="width:95px">Type</th><th style="width:95px">Status</th><th style="width:170px">Recipient</th><th style="width:170px">Source</th><th style="width:150px">Sender</th><th>Message</th><th style="width:160px">Response</th></tr></thead><tbody>
    <?php if(!$logs || $logs->num_rows===0): ?><tr><td colspan="9" class="text-center text-muted" style="padding:34px">No messages found</td></tr><?php else: while($m=$logs->fetch_assoc()): ?>
      <tr>
        <td><strong><?= htmlspecialchars(date('Y-m-d', strtotime($m['date_created']))) ?></strong><div class="text-xs text-muted"><?= htmlspecialchars(date('H:i:s', strtotime($m['date_created']))) ?></div></td>
        <td><strong><?= htmlspecialchars($m['customer_name'] ?: $m['business_name'] ?: '—') ?></strong></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 class="mono-cell"><?= htmlspecialchars($m['recipient'] ?? '') ?></td>
        <td><?= htmlspecialchars(crm_msg_source_label($m)) ?></td>
        <td><?= htmlspecialchars($m['sender'] ?? '') ?><?= !empty($m['user_name']) ? '<div class="text-xs text-muted">By '.htmlspecialchars($m['user_name']).'</div>' : '' ?></td>
        <td class="message-cell"><?= nl2br(htmlspecialchars(mb_strimwidth(trim(preg_replace('/\s+/', ' ', html_entity_decode(strip_tags($m['message'] ?? '')))),0,180,'...'))) ?></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></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_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>
