<?php
header('Content-Type: application/json');
require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');

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

$response = [
    'success' => false,
    'message' => ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (!$data) {
        $response['message'] = 'غلط ڈیٹا فارمیٹ';
        echo json_encode($response);
        exit;
    }

    $darjaSno = $data['darjaSno'] ?? '';
    $yearFromDate = $data['promotionDates'] ?? '';
    $endYear = $data['dateEnds'] ?? '';
    $startFrom = $data['startFrom'] ?? 0;

    if (empty($darjaSno) || empty($yearFromDate) || empty($endYear)) {
        $response['message'] = 'درجہ اور سال فراہم کریں';
        echo json_encode($response);
        exit;
    }

    try {
        $sqlSearch = "SELECT n.registrationNo, n.regSno
                      FROM registrationinfo r
                      INNER JOIN regnumbers n ON r.sno = n.regSno
                      INNER JOIN stddarjaat std ON r.sno = std.stdSno
                      WHERE std.darja = :darja 
                        AND std.isCurrent = 1 
                        AND r.isActive = 1 
                        AND std.promotionDate = :pDate 
                        AND std.dateEnd = :eDate
                      ORDER BY n.RollNumber ASC";

        $students = $db->getRecordSet($sqlSearch, [
            'darja' => $darjaSno,
            'pDate' => $yearFromDate,
            'eDate' => $endYear
        ]);

        error_log("DEBUG updateRollNumbers: Found " . count($students) . " students to update.");

        $db->beginTransactions();
        $rollNumber = (int)$startFrom;
        $counter = 0;
        $totalFound = count($students);

        foreach ($students as $row) {
            // $rollNumber++;
            // Update by regSno which is unique per student record in regnumbers
            $success = $db->dbQueryTrans("UPDATE regnumbers SET RollNumber = :roll WHERE regSno = :id", [
                'roll' => $rollNumber,
                'id' => $row['regSno']
            ]);

            if ($success) {
                $counter++;
            }
            else {
                error_log("DEBUG updateRollNumbers: Failed to update regSno " . $row['regSno']);
            }
            $rollNumber++;
        }

        $db->commitTransaction();
        error_log("DEBUG updateRollNumbers: Updated $counter out of $totalFound students.");

        if ($counter > 0) {
            $response['success'] = true;
            $response['message'] = $counter . ' طلباء کے رول نمبرز کامیابی سے اپ ڈیٹ ہو گئے۔';
        }
        else {
            $response['message'] = 'کوئی رول نمبر تبدیل نہیں ہوا (ممکن ہے وہ پہلے ہی درست ہوں یا طالب علم نہ ملیں)۔';
        }
    }
    catch (Exception $e) {
        $db->rollBackTransaction();
        error_log("DEBUG updateRollNumbers Error: " . $e->getMessage());
        $response['message'] = 'ڈیٹابیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);