<?php
// academic_calculations.php - Complete academic calculations for transcripts

class AcademicCalculator {
    
    /**
     * Calculate GPA for current semester
     * @param float $total_points Sum of (credit_hours * grade_points)
     * @param float $total_credits Sum of credit hours
     * @return array ['gp' => float, 'gpr' => string]
     */
    public static function calculateGPA($total_points, $total_credits) {
        if ($total_credits != 0) {
            $gp = $total_points / $total_credits;
        } else {
            $gp = 0;
        }
        
        $gpr = number_format($gp, 2, '.', '');
        
        return [
            'gp' => $gp,
            'gpr' => $gpr
        ];
    }
    
    /**
     * Calculate CGPA (Cumulative GPA)
     * @param float $total_points Sum of all points across semesters
     * @param float $total_credits Sum of all credits across semesters
     * @return array ['cgp' => float, 'cgpr' => string]
     */
    public static function calculateCGPA($total_points, $total_credits) {
        if ($total_credits != 0) {
            $cgp = $total_points / $total_credits;
        } else {
            $cgp = 0;
        }
        
        $cgpr = number_format($cgp, 2, '.', '');
        
        return [
            'cgp' => $cgp,
            'cgpr' => $cgpr
        ];
    }
    
    /**
     * Get academic points for a specific semester
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $semester Semester number
     * @return float Total points
     */
    public static function getSemesterPoints($db, $student_number, $semester) {
        $query = "SELECT SUM(sub.credit_hours * ss.weight) as total_points
                  FROM studentsubjects ss
                  JOIN subjects sub ON ss.subjectcode = sub.subjectcode
                  WHERE ltrim(ss.student_id) = '" . $db->real_escape_string($student_number) . "'
                  AND ss.semester_id = " . (int)$semester
                  . " AND ss.grade IS NOT NULL AND ss.grade != ''";
        
        $result = $db->query($query);
        if ($result && $row = $result->fetch_assoc()) {
            return (float)$row['total_points'];
        }
        return 0;
    }
    
    /**
     * Get academic hours (credits) for a specific semester
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $semester Semester number
     * @return float Total credits
     */
    public static function getSemesterHours($db, $student_number, $semester) {
        $query = "SELECT SUM(sub.credit_hours) as total_hours
                  FROM studentsubjects ss
                  JOIN subjects sub ON ss.subjectcode = sub.subjectcode
                  WHERE ltrim(ss.student_id) = '" . $db->real_escape_string($student_number) . "'
                  AND ss.semester_id = " . (int)$semester
                  . " AND ss.grade IS NOT NULL AND ss.grade != ''";
        
        $result = $db->query($query);
        if ($result && $row = $result->fetch_assoc()) {
            return (float)$row['total_hours'];
        }
        return 0;
    }
    
    /**
     * Get cumulative points up to a specific semester
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $up_to_semester Maximum semester
     * @return float
     */
    public static function getCumulativePoints($db, $student_number, $up_to_semester) {
        $query = "SELECT SUM(sub.credit_hours * ss.weight) as total_points
                  FROM studentsubjects ss
                  JOIN subjects sub ON ss.subjectcode = sub.subjectcode
                  WHERE ltrim(ss.student_id) = '" . $db->real_escape_string($student_number) . "'
                  AND ss.semester_id <= " . (int)$up_to_semester
                  . " AND ss.grade IS NOT NULL AND ss.grade != ''";
        
        $result = $db->query($query);
        if ($result && $row = $result->fetch_assoc()) {
            return (float)$row['total_points'];
        }
        return 0;
    }
    
    /**
     * Get cumulative hours up to a specific semester
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $up_to_semester Maximum semester
     * @return float
     */
    public static function getCumulativeHours($db, $student_number, $up_to_semester) {
        $query = "SELECT SUM(sub.credit_hours) as total_hours
                  FROM studentsubjects ss
                  JOIN subjects sub ON ss.subjectcode = sub.subjectcode
                  WHERE ltrim(ss.student_id) = '" . $db->real_escape_string($student_number) . "'
                  AND ss.semester_id <= " . (int)$up_to_semester
                  . " AND ss.grade IS NOT NULL AND ss.grade != ''";
        
        $result = $db->query($query);
        if ($result && $row = $result->fetch_assoc()) {
            return (float)$row['total_hours'];
        }
        return 0;
    }
    
    /**
     * Get previous semester CGPA (semester - 1)
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $current_semester Current semester number
     * @return array ['prcgp' => float, 'prcgpr' => string, 'exists' => bool]
     */
    public static function getPreviousCGPA($db, $student_number, $current_semester) {
        if ($current_semester > 1) {
            $prx = self::getCumulativePoints($db, $student_number, $current_semester - 1);
            $pry = self::getCumulativeHours($db, $student_number, $current_semester - 1);
            
            if ($pry != 0) {
                $prcgp = $prx / $pry;
            } else {
                $prcgp = 0;
            }
            $exists = true;
        } else {
            $prcgp = 0;
            $exists = false;
        }
        
        $prcgpr = number_format($prcgp, 2, '.', '');
        
        return [
            'prcgp' => $prcgp,
            'prcgpr' => $prcgpr,
            'exists' => $exists,
            'points' => $prx ?? 0,
            'hours' => $pry ?? 0
        ];
    }
    
    /**
     * Get second previous semester CGPA (semester - 2)
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $current_semester Current semester number
     * @return array ['pprcgp' => float, 'pprcgpr' => string, 'exists' => bool]
     */
    public static function getSecondPreviousCGPA($db, $student_number, $current_semester) {
        if ($current_semester > 2) {
            $prxx = self::getCumulativePoints($db, $student_number, $current_semester - 2);
            $pryy = self::getCumulativeHours($db, $student_number, $current_semester - 2);
            
            if ($pryy != 0) {
                $pprcgp = $prxx / $pryy;
            } else {
                $pprcgp = 0;
            }
            $exists = true;
        } else {
            $pprcgp = 0;
            $exists = false;
        }
        
        $pprcgpr = number_format($pprcgp, 2, '.', '');
        
        return [
            'pprcgp' => $pprcgp,
            'pprcgpr' => $pprcgpr,
            'exists' => $exists,
            'points' => $prxx ?? 0,
            'hours' => $pryy ?? 0
        ];
    }
    
    /**
     * Get complete academic record for a student in a specific semester
     * @param mysqli $db Database connection
     * @param string $student_number Student ID
     * @param int $current_semester Current semester number
     * @return array Complete academic record
     */
    public static function getCompleteAcademicRecord($db, $student_number, $current_semester) {
        // Get current semester data
        $semester_points = self::getSemesterPoints($db, $student_number, $current_semester);
        $semester_hours = self::getSemesterHours($db, $student_number, $current_semester);
        
        // Calculate semester GPA
        $gpa_result = self::calculateGPA($semester_points, $semester_hours);
        
        // Get cumulative data up to current semester
        $cumulative_points = self::getCumulativePoints($db, $student_number, $current_semester);
        $cumulative_hours = self::getCumulativeHours($db, $student_number, $current_semester);
        
        // Calculate cumulative GPA (CGPA)
        $cgpa_result = self::calculateCGPA($cumulative_points, $cumulative_hours);
        
        // Get previous semester CGPA (if semester > 1)
        $previous_cgpa = self::getPreviousCGPA($db, $student_number, $current_semester);
        
        // Get second previous semester CGPA (if semester > 2)
        $second_previous_cgpa = self::getSecondPreviousCGPA($db, $student_number, $current_semester);
        
        return [
            'current_semester' => [
                'number' => $current_semester,
                'points' => $semester_points,
                'hours' => $semester_hours,
                'gpa' => $gpa_result['gp'],
                'gpa_formatted' => $gpa_result['gpr']
            ],
            'cumulative' => [
                'points' => $cumulative_points,
                'hours' => $cumulative_hours,
                'cgpa' => $cgpa_result['cgp'],
                'cgpa_formatted' => $cgpa_result['cgpr']
            ],
            'previous_semester' => [
                'exists' => $previous_cgpa['exists'],
                'cgpa' => $previous_cgpa['prcgp'],
                'cgpa_formatted' => $previous_cgpa['prcgpr'],
                'points' => $previous_cgpa['points'],
                'hours' => $previous_cgpa['hours']
            ],
            'second_previous_semester' => [
                'exists' => $second_previous_cgpa['exists'],
                'cgpa' => $second_previous_cgpa['pprcgp'],
                'cgpa_formatted' => $second_previous_cgpa['pprcgpr'],
                'points' => $second_previous_cgpa['points'],
                'hours' => $second_previous_cgpa['hours']
            ]
        ];
    }
}

// ============ DISPLAY FUNCTIONS ============

/**
 * Display academic summary for a student
 * @param array $academic_record The academic record from getCompleteAcademicRecord()
 */
function displayAcademicSummary($academic_record) {
    ?>
    <div class="academic-summary">
        <h4 class="text-center mb-3">الملخص الأكاديمي</h4>
        
        <!-- Current Semester -->
        <div class="summary-box" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <div class="row text-center">
                <div class="col-md-3">
                    <div class="summary-label">الفصل الدراسي الحالي</div>
                    <div class="summary-value">الفصل <?= $academic_record['current_semester']['number'] ?></div>
                </div>
                <div class="col-md-3">
                    <div class="summary-label">الساعات الفصلية</div>
                    <div class="summary-value"><?= number_format($academic_record['current_semester']['hours'], 1) ?></div>
                </div>
                <div class="col-md-3">
                    <div class="summary-label">النقاط الفصلية</div>
                    <div class="summary-value"><?= number_format($academic_record['current_semester']['points'], 2) ?></div>
                </div>
                <div class="col-md-3">
                    <div class="summary-label">المعدل الفصلي GPA</div>
                    <div class="summary-value"><?= $academic_record['current_semester']['gpa_formatted'] ?></div>
                </div>
            </div>
        </div>
        
        <!-- Cumulative -->
        <div class="summary-box" style="background: linear-gradient(135deg, #00b09b 0%, #96c93d 100%); margin-top: 10px;">
            <div class="row text-center">
                <div class="col-md-4">
                    <div class="summary-label">الساعات التراكمية</div>
                    <div class="summary-value"><?= number_format($academic_record['cumulative']['hours'], 1) ?></div>
                </div>
                <div class="col-md-4">
                    <div class="summary-label">النقاط التراكمية</div>
                    <div class="summary-value"><?= number_format($academic_record['cumulative']['points'], 2) ?></div>
                </div>
                <div class="col-md-4">
                    <div class="summary-label">المعدل التراكمي CGPA</div>
                    <div class="summary-value"><?= $academic_record['cumulative']['cgpa_formatted'] ?></div>
                </div>
            </div>
        </div>
        
        <!-- Previous Semesters -->
        <?php if ($academic_record['previous_semester']['exists']): ?>
        <div class="summary-box" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); margin-top: 10px;">
            <div class="row text-center">
                <div class="col-md-6">
                    <div class="summary-label">المعدل التراكمي السابق (حتى الفصل <?= $academic_record['current_semester']['number'] - 1 ?>)</div>
                    <div class="summary-value"><?= $academic_record['previous_semester']['cgpa_formatted'] ?></div>
                    <small>(الساعات: <?= number_format($academic_record['previous_semester']['hours'], 1) ?> | النقاط: <?= number_format($academic_record['previous_semester']['points'], 2) ?>)</small>
                </div>
                <?php if ($academic_record['second_previous_semester']['exists']): ?>
                <div class="col-md-6">
                    <div class="summary-label">المعدل التراكمي الأسبق (حتى الفصل <?= $academic_record['current_semester']['number'] - 2 ?>)</div>
                    <div class="summary-value"><?= $academic_record['second_previous_semester']['cgpa_formatted'] ?></div>
                    <small>(الساعات: <?= number_format($academic_record['second_previous_semester']['hours'], 1) ?> | النقاط: <?= number_format($academic_record['second_previous_semester']['points'], 2) ?>)</small>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <style>
        .academic-summary {
            margin: 20px 0;
        }
        .summary-box {
            border-radius: 15px;
            padding: 15px;
            color: white;
            margin-bottom: 10px;
        }
        .summary-label {
            font-size: 0.85rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }
        .summary-value {
            font-size: 1.5rem;
            font-weight: 700;
        }
        @media print {
            .summary-box {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>
    <?php
}

/**
 * Display academic summary in table format
 * @param array $academic_record The academic record from getCompleteAcademicRecord()
 */
function displayAcademicTable($academic_record) {
    ?>
    <table class="report-table" style="margin-top: 15px;">
        <thead>
            <tr>
                <th>البيان</th>
                <th>الفصل الحالي</th>
                <th>التراكمي</th>
                <?php if ($academic_record['previous_semester']['exists']): ?>
                <th>السابق (حتى فصل <?= $academic_record['current_semester']['number'] - 1 ?>)</th>
                <?php endif; ?>
                <?php if ($academic_record['second_previous_semester']['exists']): ?>
                <th>الأسبق (حتى فصل <?= $academic_record['current_semester']['number'] - 2 ?>)</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><strong>عدد الساعات</strong></td>
                <td><?= number_format($academic_record['current_semester']['hours'], 1) ?></td>
                <td><?= number_format($academic_record['cumulative']['hours'], 1) ?></td>
                <?php if ($academic_record['previous_semester']['exists']): ?>
                <td><?= number_format($academic_record['previous_semester']['hours'], 1) ?></td>
                <?php endif; ?>
                <?php if ($academic_record['second_previous_semester']['exists']): ?>
                <td><?= number_format($academic_record['second_previous_semester']['hours'], 1) ?></td>
                <?php endif; ?>
            </tr>
            <tr>
                <td><strong>النقاط</strong></td>
                <td><?= number_format($academic_record['current_semester']['points'], 2) ?></td>
                <td><?= number_format($academic_record['cumulative']['points'], 2) ?></td>
                <?php if ($academic_record['previous_semester']['exists']): ?>
                <td><?= number_format($academic_record['previous_semester']['points'], 2) ?></td>
                <?php endif; ?>
                <?php if ($academic_record['second_previous_semester']['exists']): ?>
                <td><?= number_format($academic_record['second_previous_semester']['points'], 2) ?></td>
                <?php endif; ?>
            </tr>
            <tr>
                <td><strong>المعدل GPA / CGPA</strong></td>
                <td><strong><?= $academic_record['current_semester']['gpa_formatted'] ?></strong></td>
                <td><strong><?= $academic_record['cumulative']['cgpa_formatted'] ?></strong></td>
                <?php if ($academic_record['previous_semester']['exists']): ?>
                <td><strong><?= $academic_record['previous_semester']['cgpa_formatted'] ?></strong></td>
                <?php endif; ?>
                <?php if ($academic_record['second_previous_semester']['exists']): ?>
                <td><strong><?= $academic_record['second_previous_semester']['cgpa_formatted'] ?></strong></td>
                <?php endif; ?>
            </tr>
        </tbody>
    </table>
    <?php
}

// ============ USAGE EXAMPLE ============
/*
require_once 'academic_calculations.php';

// For each student, calculate academic record
foreach ($students_data as &$student) {
    $academic_record = AcademicCalculator::getCompleteAcademicRecord(
        $mysqli1,
        $student['student_id'],
        $semester_id  // Current semester number
    );
    
    // Store in student data
    $student['academic_record'] = $academic_record;
}

// Display in your transcript
foreach ($students_data as $student) {
    // Display academic summary
    displayAcademicSummary($student['academic_record']);
    
    // OR display in table format
    displayAcademicTable($student['academic_record']);
}
*/
?>