<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

// Get report type from query string
$reportType = isset($_GET['type']) ? trim($_GET['type']) : 'overview';
$startDate = isset($_GET['start_date']) ? trim($_GET['start_date']) : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? trim($_GET['end_date']) : date('Y-m-d');

// Data arrays
$data = [];
$labels = [];

switch ($reportType) {
    case 'overview':
        // Overall stats
        $data['users'] = $db->get("SELECT COUNT(*) AS cnt FROM users WHERE created_at BETWEEN ? AND ?", [$startDate, $endDate]);
        $data['courses'] = $db->get("SELECT COUNT(*) AS cnt FROM courses WHERE created_at BETWEEN ? AND ?", [$startDate, $endDate]);
        $data['enrollments'] = $db->get("SELECT COUNT(*) AS cnt FROM course_enrollments WHERE enrollment_date BETWEEN ? AND ?", [$startDate, $endDate]);
        $data['revenue'] = $db->get("SELECT COALESCE(SUM(amount), 0) AS total FROM payments WHERE payment_status = 'completed' AND paid_at BETWEEN ? AND ?", [$startDate, $endDate]);
        $data['certificates'] = $db->get("SELECT COUNT(*) AS cnt FROM certificates WHERE issue_date BETWEEN ? AND ?", [$startDate, $endDate]);
        break;

    case 'enrollments':
        // Enrollments by day
        $rows = $db->getAll(
            "SELECT DATE(enrollment_date) AS date, COUNT(*) AS count
             FROM course_enrollments
             WHERE enrollment_date BETWEEN ? AND ?
             GROUP BY DATE(enrollment_date)
             ORDER BY date",
            [$startDate, $endDate]
        );
        foreach ($rows as $row) {
            $labels[] = $row['date'];
            $data[] = (int)$row['count'];
        }
        break;

    case 'revenue':
        // Revenue by day
        $rows = $db->getAll(
            "SELECT DATE(paid_at) AS date, SUM(amount) AS total
             FROM payments
             WHERE payment_status = 'completed' AND paid_at BETWEEN ? AND ?
             GROUP BY DATE(paid_at)
             ORDER BY date",
            [$startDate, $endDate]
        );
        foreach ($rows as $row) {
            $labels[] = $row['date'];
            $data[] = (float)$row['total'];
        }
        break;

    case 'courses':
        // Top courses by enrollments
        $rows = $db->getAll(
            "SELECT c.title, COUNT(ce.id) AS enrollment_count
             FROM courses c
             LEFT JOIN course_enrollments ce ON c.id = ce.course_id
             WHERE ce.enrollment_date BETWEEN ? AND ?
             GROUP BY c.id
             ORDER BY enrollment_count DESC
             LIMIT 10",
            [$startDate, $endDate]
        );
        foreach ($rows as $row) {
            $labels[] = $row['title'];
            $data[] = (int)$row['enrollment_count'];
        }
        break;

    case 'regions':
        // Users by region
        $rows = $db->getAll(
            "SELECT region, COUNT(*) AS count
             FROM users
             WHERE created_at BETWEEN ? AND ?
             GROUP BY region
             ORDER BY count DESC",
            [$startDate, $endDate]
        );
        foreach ($rows as $row) {
            $labels[] = ucfirst($row['region'] ?? 'Unknown');
            $data[] = (int)$row['count'];
        }
        break;
}

$pageTitle = 'Reports';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Reports</h1>
    <p class="text-muted mb-0">Generate and view system reports</p>
  </div>
  <div>
    <button class="btn btn-outline-primary" onclick="window.print()">
      <i class="fas fa-print me-2"></i>Print Report
    </button>
  </div>
</div>

<div class="card mb-4">
  <div class="card-body">
    <form method="get" class="row g-3">
      <div class="col-md-3">
        <label class="form-label">Report Type</label>
        <select name="type" class="form-select">
          <option value="overview" <?php echo $reportType === 'overview' ? 'selected' : ''; ?>>Overview</option>
          <option value="enrollments" <?php echo $reportType === 'enrollments' ? 'selected' : ''; ?>>Enrollments</option>
          <option value="revenue" <?php echo $reportType === 'revenue' ? 'selected' : ''; ?>>Revenue</option>
          <option value="courses" <?php echo $reportType === 'courses' ? 'selected' : ''; ?>>Top Courses</option>
          <option value="regions" <?php echo $reportType === 'regions' ? 'selected' : ''; ?>>Users by Region</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">Start Date</label>
        <input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($startDate); ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label">End Date</label>
        <input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($endDate); ?>">
      </div>
      <div class="col-md-3 align-self-end">
        <button type="submit" class="btn btn-primary w-100">Generate Report</button>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-header">
    <h5 class="mb-0">
      <?php
      $titles = [
          'overview' => 'Overview Report',
          'enrollments' => 'Enrollments Report',
          'revenue' => 'Revenue Report',
          'courses' => 'Top Courses Report',
          'regions' => 'Users by Region Report'
      ];
      echo $titles[$reportType] ?? 'Report';
      ?>
    </h5>
    <small class="text-muted">Period: <?php echo htmlspecialchars($startDate); ?> to <?php echo htmlspecialchars($endDate); ?></small>
  </div>
  <div class="card-body">
    <?php if ($reportType === 'overview'): ?>
      <div class="row g-4">
        <div class="col-md-6 col-lg-3">
          <div class="card bg-light">
            <div class="card-body text-center">
              <h4 class="mb-1"><?php echo number_format((int)($data['users']['cnt'] ?? 0)); ?></h4>
              <p class="mb-0">New Users</p>
            </div>
          </div>
        </div>
        <div class="col-md-6 col-lg-3">
          <div class="card bg-light">
            <div class="card-body text-center">
              <h4 class="mb-1"><?php echo number_format((int)($data['courses']['cnt'] ?? 0)); ?></h4>
              <p class="mb-0">New Courses</p>
            </div>
          </div>
        </div>
        <div class="col-md-6 col-lg-3">
          <div class="card bg-light">
            <div class="card-body text-center">
              <h4 class="mb-1"><?php echo number_format((int)($data['enrollments']['cnt'] ?? 0)); ?></h4>
              <p class="mb-0">Enrollments</p>
            </div>
          </div>
        </div>
        <div class="col-md-6 col-lg-3">
          <div class="card bg-light">
            <div class="card-body text-center">
              <h4 class="mb-1"><?php echo number_format((float)($data['revenue']['total'] ?? 0), 2); ?></h4>
              <p class="mb-0">Revenue</p>
            </div>
          </div>
        </div>
      </div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table table-striped">
          <thead>
            <tr>
              <th><?php echo ucfirst($reportType); ?></th>
              <th>Value</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($labels as $i => $label): ?>
              <tr>
                <td><?php echo htmlspecialchars($label); ?></td>
                <td><?php echo is_numeric($data[$i]) ? number_format($data[$i]) : htmlspecialchars($data[$i]); ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
