<?php
// All account activities, reminders and communications
$filter_user = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$filter_type = isset($_GET['type']) ? sanitize($conn, $_GET['type']) : '';
$activity_search = isset($_GET['activity_search']) ? sanitize($conn, $_GET['activity_search']) : '';
$whereUserAct = $filter_user ? " AND a.user_id=$filter_user" : '';
$whereTypeAct = $filter_type ? " AND at.name='$filter_type'" : '';
$whereSearchAct = $activity_search ? " AND (a.text LIKE '%$activity_search%' OR a.comment LIKE '%$activity_search%' OR l.title LIKE '%$activity_search%' OR c.customer_name LIKE '%$activity_search%')" : '';
$users_for_filter = $conn->query("SELECT id,name FROM users WHERE account_id=$account_id ORDER BY name");
$activity_types_filter = $conn->query("SELECT name FROM activity_type ORDER BY name");
$page_num = isset($_GET['page_num']) ? max(1,(int)$_GET['page_num']) : 1;
$per_page = defined('CRM_DEFAULT_PER_PAGE') ? CRM_DEFAULT_PER_PAGE : 30;
$offset = ($page_num-1) * $per_page;
$totalActQ = $conn->query("SELECT COUNT(*) cnt FROM lead_activities a LEFT JOIN activity_type at ON at.id=a.activity_type_id LEFT JOIN leads l ON l.id=a.lead_id LEFT JOIN customers c ON c.id=l.customer_id WHERE l.account_id=$account_id $whereUserAct $whereTypeAct $whereSearchAct");
$total_rows = $totalActQ ? (int)$totalActQ->fetch_assoc()['cnt'] : 0;
$total_pages = max(1, (int)ceil($total_rows / $per_page));
$activities = $conn->query("
  SELECT a.*, at.name type_name, u.name user_name, l.title lead_title, c.customer_name
  FROM lead_activities a
  LEFT JOIN activity_type at ON at.id=a.activity_type_id
  LEFT JOIN users u ON u.id=a.user_id
  LEFT JOIN leads l ON l.id=a.lead_id
  LEFT JOIN customers c ON c.id=l.customer_id
  WHERE l.account_id=$account_id $whereUserAct $whereTypeAct $whereSearchAct
  ORDER BY COALESCE(a.date_activitie, DATE(a.datetime)) DESC, a.datetime DESC
  LIMIT $offset, $per_page
");
$communications = tableExists($conn,'communications') ? $conn->query("
  SELECT cm.*, u.name user_name, c.customer_name
  FROM communications cm
  LEFT JOIN users u ON u.id=cm.user_id
  LEFT JOIN customers c ON c.id=cm.customer_id
  WHERE c.account_id=$account_id
  ORDER BY cm.date_created DESC LIMIT 100
") : false;
?>
<div class="fade-in">
  <div class="toolbar" style="justify-content:space-between;gap:12px;flex-wrap:wrap">
    <span class="card-title">All Activities</span>
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap">
      <input type="hidden" name="page" value="activities">
      <input type="text" name="activity_search" class="form-control" style="width:220px" placeholder="Search activities..." value="<?= htmlspecialchars($activity_search) ?>">
      <select name="user_id" class="form-control" style="width:180px"><option value="0">All Users</option><?php while($u=$users_for_filter->fetch_assoc()): ?><option value="<?= $u['id'] ?>" <?= $filter_user==$u['id']?'selected':'' ?>><?= htmlspecialchars($u['name']) ?></option><?php endwhile; ?></select>
      <select name="type" class="form-control" style="width:180px"><option value="">All Types</option><?php while($t=$activity_types_filter->fetch_assoc()): ?><option value="<?= htmlspecialchars($t['name']) ?>" <?= $filter_type===$t['name']?'selected':'' ?>><?= htmlspecialchars($t['name']) ?></option><?php endwhile; ?></select>
      <button class="btn btn-primary">Filter</button><a class="btn btn-secondary" href="index.php?page=activities">Clear</a>
    </form>
  </div>
  <div class="card"><div class="table-wrapper"><table class="crm-table">
    <thead><tr><th>Date</th><th>Type</th><th>Lead / Customer</th><th>Comment</th><th>User</th></tr></thead><tbody>
    <?php if(!$activities || $activities->num_rows===0): ?><tr><td colspan="5" class="text-center text-muted">No activities yet</td></tr><?php else: while($a=$activities->fetch_assoc()): ?>
      <tr><td><?= htmlspecialchars($a['date_activitie'] && $a['date_activitie']!='0000-00-00' ? $a['date_activitie'] : date('Y-m-d', strtotime($a['datetime']))) ?></td><td><span class="badge badge-blue"><?= htmlspecialchars($a['type_name'] ?? 'Activity') ?></span></td><td><a href="index.php?page=lead&id=<?= (int)$a['lead_id'] ?>"><?= htmlspecialchars($a['lead_title'] ?: ('Lead #'.$a['lead_id'])) ?></a><div class="text-xs text-muted"><a href="index.php?page=customers&search=<?= urlencode($a['customer_name'] ?? '') ?>"><?= htmlspecialchars($a['customer_name'] ?? '') ?></a></div></td><td><?= nl2br(htmlspecialchars($a['comment'] ?: $a['text'])) ?></td><td><?= htmlspecialchars($a['user_name'] ?? 'User') ?></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 + ($activities ? $activities->num_rows : 0), $total_rows)) ?></strong> of <strong><?= number_format($total_rows) ?></strong> activities</div>
      <?php if ($total_pages > 1): ?>
      <div class="pagination">
        <?php $qs=$_GET; $qs['page']='activities'; ?>
        <?php if($page_num>1): $qs['page_num']=$page_num-1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($qs) ?>">← Previous</a><?php endif; ?>
        <?php for($i=max(1,$page_num-2); $i<=min($total_pages,$page_num+2); $i++): $qs['page_num']=$i; ?>
          <?= $i==$page_num ? '<span class="btn btn-primary btn-sm">'.$i.'</span>' : '<a class="btn btn-secondary btn-sm" href="?'.htmlspecialchars(http_build_query($qs)).'">'.$i.'</a>' ?>
        <?php endfor; ?>
        <?php if($page_num<$total_pages): $qs['page_num']=$page_num+1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($qs) ?>">Next →</a><?php endif; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <div class="card" style="margin-top:20px"><div class="card-header"><span class="card-title">Messages Log</span></div><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Date</th><th>Customer</th><th>Type</th><th>Status</th><th>Sender</th><th>Message</th></tr></thead><tbody>
  <?php if(!$communications || $communications->num_rows===0): ?><tr><td colspan="6" class="text-center text-muted">No messages yet</td></tr><?php else: while($m=$communications->fetch_assoc()): ?>
    <tr><td><?= htmlspecialchars($m['date_created']) ?></td><td><?= htmlspecialchars($m['customer_name'] ?? '') ?></td><td><?= htmlspecialchars($m['message_type_id']) ?></td><td><span class="badge badge-<?= $m['status']==='sent'?'green':'red' ?>"><?= htmlspecialchars($m['status']) ?></span></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,120,'...'))) ?></td></tr>
  <?php endwhile; endif; ?></tbody></table></div></div>
</div>
