
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);
require __DIR__ . '/BaseController.php';

class ReportsController extends BaseController {
  public function index(): void {
    $u = require_login($this->pdo, $this->config);

    // Simple activity report (MVP)
    $from = $_GET['from'] ?? date('Y-m-01');
    $to = $_GET['to'] ?? date('Y-m-d');

    $params = [$from.' 00:00:00', $to.' 23:59:59'];
    $where = "a.created_at BETWEEN ? AND ?";

    // scope: CC agent sees only their lead logs; BR agent sees only their opp logs; managers see broader
    if (has_role($u, ['CC_AGENT'])) {
      $where .= " AND a.actor_user_id=?";
      $params[] = $u['id'];
    } elseif (has_role($u, ['BR_AGENT'])) {
      $where .= " AND a.actor_user_id=?";
      $params[] = $u['id'];
    } elseif (has_role($u, ['BR_MGR'])) {
      // show opp logs for branch by joining opportunities
      $where .= " AND (a.entity_type!='opportunity' OR a.entity_id IN (SELECT id FROM opportunities WHERE branch_id=?))";
      $params[] = $u['branch_id'];
    }

    $st = $this->pdo->prepare("SELECT a.*, u.name actor_name
                               FROM activity_logs a
                               LEFT JOIN users u ON u.id=a.actor_user_id
                               WHERE {$where}
                               ORDER BY a.id DESC
                               LIMIT 500");
    $st->execute($params);
    $rows = $st->fetchAll();

    $this->render('reports/index.php', ['u'=>$u,'rows'=>$rows,'from'=>$from,'to'=>$to]);
  }
}
