<?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;
    }

    $toDarja = $data['toDarja'] ?? '';
    $promotionDate = $data['promotionDate'] ?? '';
    $dateEnd = $data['dateEnd'] ?? '';
    $studentIds = $data['studentIds'] ?? []; // Array of student (reginfo) snos

    if (empty($toDarja) || empty($promotionDate) || empty($dateEnd) || empty($studentIds)) {
        $response['message'] = 'تمام معلومات فراہم کریں';
        echo json_encode($response);
        exit;
    }

    try {
        $db->beginTransactions();

        // Get shoba_sno for the destination darja
        $shobaSno = $db->getValueTrans("SELECT shoba_sno FROM darjaat WHERE derjaCode = :darja", ['darja' => $toDarja], 'shoba_sno');

        foreach ($studentIds as $id) {
            // 1. Set current record as non-current
            $db->dbQueryTrans("UPDATE stddarjaat SET isCurrent = 0 WHERE stdSno = :id", ['id' => $id]);

            // 2. Insert new promotion record
            $sqlInsert = "INSERT INTO stddarjaat (darja, stdSno, isCurrent, promotionDate, dateEnd, shoba_sno) 
                          VALUES (:darja, :id, 1, :pDate, :eDate, :sNo)";
            $db->dbQueryTrans($sqlInsert, [
                'darja' => $toDarja,
                'id' => $id,
                'pDate' => $promotionDate,
                'eDate' => $dateEnd,
                'sNo' => $shobaSno
            ]);

            // 3. Cleanup future/redundant records (Legacy logic)
            $db->dbQueryTrans("DELETE FROM stddarjaat WHERE stdSno = :id AND darja > :toDarja AND isCurrent = 0", ['id' => $id, 'toDarja' => $toDarja]);
            $db->dbQueryTrans("DELETE FROM stddarjaat WHERE stdSno = :id AND darja = :toDarja AND isCurrent = 0", ['id' => $id, 'toDarja' => $toDarja]);
        }

        $db->commitTransaction();
        $response['success'] = true;
        $response['message'] = count($studentIds) . ' طلباء کامیابی کے ساتھ منتقل کر دیئے گئے۔';
    } catch (Exception $e) {
        $db->rollBackTransaction();
        $response['message'] = 'ڈیٹابیس کی خرابی: ' . $e->getMessage();
    }
}

echo json_encode($response);
