<?php
/**
 * SmartThink LMS - Cohort Class
 *
 * Handles cohort management and cohort-aware enrollment helpers.
 */

class Cohort {
    private $db;
    private $table = 'cohorts';

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * Find the best open cohort for a given course and student region.
     *
     * Preference order:
     *  - status = 'open'
     *  - region-specific first, then 'global'
     *  - earliest non-null start_date
     *  - respects max_capacity when set
     */
    public function findOpenCohortForEnrollment($courseId, $region) {
        $courseId = (int)$courseId;
        if ($courseId <= 0) {
            return null;
        }

        $region = $region ?: 'usa';

        $cohorts = $this->db->getAll(
            "SELECT c.*, 
                    (SELECT COUNT(*) 
                       FROM course_enrollments ce 
                      WHERE ce.cohort_id = c.id 
                        AND ce.status IN ('active','pending','suspended')) AS enrolled_count
               FROM {$this->table} c
              WHERE c.course_id = ?
                AND c.status = 'open'
                AND (c.region = ? OR c.region = 'global')
           ORDER BY (c.region = ?) DESC, c.start_date IS NULL, c.start_date ASC",
            [$courseId, $region, $region]
        );

        if (!$cohorts) {
            return null;
        }

        foreach ($cohorts as $cohort) {
            $maxCapacity = isset($cohort['max_capacity']) ? (int)$cohort['max_capacity'] : 0;
            $enrolled    = isset($cohort['enrolled_count']) ? (int)$cohort['enrolled_count'] : 0;

            // If no max_capacity set, or still has room, use this cohort
            if ($maxCapacity <= 0 || $enrolled < $maxCapacity) {
                return $cohort;
            }
        }

        return null;
    }
}
