<?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%')" : '';
$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;
$countSql = "SELECT COUNT(*) total 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";
$countRes = $conn->query($countSql);
$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");
$activity_types_filter = $conn->query("SELECT name FROM activity_type ORDER BY name");
$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
");
?>
<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>
      <div class="pagination">
        <?php if ($total_pages > 1): ?>
          <?php $baseParams=$_GET; $baseParams['page']='activities'; unset($baseParams['p']); ?>
          <?php 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; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div>
