<?php
/**
 * DMC Report API (Single Student)
 * Action: get_students, get_report
 */
header('Content-Type: application/json');
session_start();

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

$db = new App_DB(DBU::$dba_user);

// Handle both JSON and standard POST
$input_raw = file_get_contents('php://input');
$input = json_decode($input_raw, true);
if (!$input) {
    $input = $_POST;
}

$action = $_GET['action'] ?? $input['action'] ?? '';

// Debug log to a writable location
$debug_log = dirname(__DIR__) . '/dbBackup/dmc_api_debug.log';
file_put_contents($debug_log, date('Y-m-d H:i:s') . " Action: $action, Input: " . json_encode($input) . "\n", FILE_APPEND);

switch ($action) {
    case 'get_students':
        $darja = (int) ($input['darja'] ?? 0);
        if (!$darja) {
            echo json_encode(['success' => false, 'message' => 'Invalid Darja']);
            exit;
        }

        $sql = "SELECT DISTINCT r.sno, CONCAT(r.stdName, ' ولد ', r.fatherName) as stdName 
                FROM registrationinfo r
                JOIN stddarjaat std ON std.stdSno = r.sno 
                WHERE std.darja = :darja AND r.isActive = 1 
                ORDER BY r.stdName ASC";

        $students = $db->getRecordSet($sql, ['darja' => $darja]);
        echo json_encode(['success' => true, 'data' => $students]);
        break;

    case 'get_report':
        $regSno = (int) ($input['regSno'] ?? 0);
        $darja = (int) ($input['darja'] ?? 0);
        $year = (int) ($input['year'] ?? 0); // User's year input

        if (!$regSno || !$darja || !$year) {
            echo json_encode(['success' => false, 'message' => 'تمام خانے پر کریں (All fields are required)']);
            exit;
        }

        try {
            // Fetch student info
            $sqlStd = "SELECT r.stdName, r.fatherName, r.dob, d.darja as darjaName 
                       FROM registrationinfo r
                       JOIN stddarjaat st ON st.stdSno = r.sno
                       JOIN darjaat d ON d.derjaCode = st.darja
                       WHERE r.sno = :regSno AND st.darja = :darja AND r.isActive = 1
                       LIMIT 1";
            $stdInfo = $db->getRecordSet($sqlStd, ['regSno' => $regSno, 'darja' => $darja]);

            if (empty($stdInfo)) {
                echo json_encode(['success' => false, 'message' => 'طالب علم کا ریکارڈ نہیں ملا (Student not found)']);
                exit;
            }

            // Fetch marks (resultTerm = 3 for Annual)
            // Note: We use the year part from promotionDate or resultYear if exists. 
            // since resultYear is missing in DB, we'll try to match year with promotionDate
            $sqlMarks = "SELECT s.subjectName, s.totalMarks, r.obtmarks 
                         FROM subjects s
                         LEFT JOIN result r ON r.subjectsno = s.sno 
                            AND r.stdSno = :regSno 
                            AND r.resultTerm = 3 
                            AND r.darjasno = :darja
                            AND YEAR(r.promotionDate) = :year
                         WHERE s.darjaSno = :darja
                         ORDER BY s.sno ASC";

            $marks = $db->getRecordSet($sqlMarks, ['regSno' => $regSno, 'darja' => $darja, 'year' => $year]);

            if (empty($marks)) {
                echo json_encode(['success' => false, 'message' => 'اس درجہ کے مضامین نہیں ملے (No subjects found for this Darja)']);
                exit;
            }

            $totalObtained = 0;
            $totalPossible = 0;
            $hasData = false;

            foreach ($marks as &$m) {
                if ($m['obtmarks'] !== null) {
                    $totalObtained += (int) $m['obtmarks'];
                    $hasData = true;
                }
                $totalPossible += (int) $m['totalMarks'];
            }

            if (!$hasData) {
                echo json_encode(['success' => false, 'message' => 'اس طالب علم کا سالانہ رزلٹ اس سال کے لیے موجود نہیں ہے (No result found for this year)']);
                exit;
            }

            echo json_encode([
                'success' => true,
                'data' => [
                    'student' => $stdInfo[0],
                    'marks' => $marks,
                    'totals' => [
                        'obtained' => $totalObtained,
                        'possible' => $totalPossible
                    ],
                    'year' => $year,
                    'madrasa_name' => 'مدرسہ تعلیم القران باغ محلہ مینگورہ' // Following original page
                ]
            ]);

        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid Action']);
        break;
}
?>