<?php
function createLedgerDetails(
    $conn_rjllearning_specific,
    $conn_rjllearning,
    $institution_id, 
    $branch_id, 
    $class_admitted, 
    $section_admitted, 
    $student_id, 
    $name, 
    $ledgerhead, 
    $opening_balance, 
    $opening_balance_type,
    $current_balance, 
    $current_balance_type,
    $username, 
    $address, 
    $gst, 
    $pan
) {
    try {
        // Check required fields
        if (!checkIfIssetAndNotEmpty($name) || !checkIfIssetAndNotEmpty($ledgerhead)) {
            errorreturn("Name and ledgerhead are required and cannot be empty.", $conn_rjllearning_specific);
        }
        $ledgerheads = fetchLedgerheadDetails($conn_rjllearning);
        $ledgerhead_names = array_column($ledgerheads, 'ledgerhead_name');
        
        // Check if provided ledgerhead exists
        if (!in_array($ledgerhead, $ledgerhead_names)) {
            errorreturn("Provided ledgerhead does not exist.", $conn_rjllearning_specific);
        }

        // Validate optional fields
        if ($address !== null && !CheckAddressValidation($address)) {
            errorreturn("Invalid address.", $conn_rjllearning_specific);
        }
        if ($gst !== null && !BranchGstValidation($gst)) {
            errorreturn("Invalid GST number.", $conn_rjllearning_specific);
        }
        if ($pan !== null && !CheckCompanyPanValidation($pan)) {
            errorreturn("Invalid PAN number.", $conn_rjllearning_specific);
        }

        // Validate student-related fields if student_id is provided
        if ($student_id !== null) {
            if (!checkIfIssetAndNotEmpty($class_admitted) || !checkIfIssetAndNotEmpty($section_admitted) || !checkIfIssetAndNotEmpty($student_id)) {
                errorreturn("Class ID, Section ID, and Student ID are required when Student ID is provided.", $conn_rjllearning_specific);
            }

            // Fetch gender and father's name using student_id
            $sql_student = "SELECT gender, fathername FROM students WHERE id = ?";
            $stmt_student = $conn_rjllearning_specific->prepare($sql_student);
            $stmt_student->execute([$student_id]);
            $student_info = $stmt_student->fetch(PDO::FETCH_ASSOC);

            if ($student_info) {
                $gender = $student_info['gender'];
                var_dump($gender);
                die();
                $father_name = $student_info['fathername'];

                // Format the student's name based on gender
                $name = formatStudentName($name, $father_name, $gender);
            }
        }

        // Check for existing records
        $check_sql = "SELECT COUNT(*) FROM ledgerdetails WHERE ledgerhead = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($check_sql);
        $stmt->execute([$ledgerhead, $institution_id]);
        if ($stmt->fetchColumn() > 0) {
            errorreturn("Record with the same ledgerhead already exists.", $conn_rjllearning_specific);
        }

        // Validate balances
        if (!is_numeric($opening_balance) || !is_numeric($current_balance)) {
            errorreturn("Opening balance and current balance must be numeric.", $conn_rjllearning_specific);
        }

        // Convert balances
        $opening_balance = convertTo_complexamount(['amount' => $opening_balance, 'type' => $opening_balance_type]);
        $current_balance = convertTo_complexamount(['amount' => $current_balance, 'type' => $current_balance_type]);

        // Insert record
        $sql = "INSERT INTO ledgerdetails (
                    institution_id, branch_id, class_id, section_id, student_id, name, ledgerhead, 
                    opening_balance, current_balance, date_created, time_created, created_by, status,
                    address, gst, pan
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([
            $institution_id, $branch_id, $class_admitted, $section_admitted, $student_id, $name, $ledgerhead, 
            $opening_balance, $current_balance, date('Y-m-d'), time(), $username, 1,
            $address, $gst, $pan
        ]);

        // Return success
         return true;
    } catch (Exception $e) {
        errorreturn($e->getMessage(), $conn_rjllearning_specific);
    }
}







function fetchLedgerheadDetails($conn_rjllearning) {
    $sql = "SELECT * FROM ledgerheads";
    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute();
    $ledgerheadDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    return $ledgerheadDetails;
}


function formatStudentName($student_name, $father_name, $gender) {
    // Check the gender and format the name accordingly
    if ($gender === 'm') {
        // Male student
        return "{$student_name} son of {$father_name}";
    } elseif ($gender === 'f') {
        // Female student
        return "{$student_name} daughter of {$father_name}";
    } else {
        // Handle unknown gender or invalid input
        return "Unknown gender for {$student_name}";
    }
}





function updateLedgerDetails($conn_rjllearning, $institution_id, $student_id, $branch_id, $class_id, $section_id, $name, $ledgerhead, $current_balance) {
    // Validate the input data
    if (!checkIfIssetAndNotEmpty($name) || !checkIfIssetAndNotEmpty($ledgerhead)) {
        errorreturn("Name and ledgerhead are required and cannot be empty.", $conn_rjllearning);
    }
    if (!is_numeric($current_balance)) {
        errorreturn("Current balance must be numeric.", $conn_rjllearning);
    }

    // Convert balance to display format
    $balance_in_words = convertToDisplayAmount($current_balance);

    // Start transaction
    $conn_rjllearning->beginTransaction();

    try {
        // Prepare the SQL statement for updating
        $sql_update = "UPDATE ledgerdetails 
                        SET branch_id = ?, 
                            class_id = ?, 
                            section_id = ?, 
                            name = ?, 
                            ledgerhead = ?, 
                            current_balance = ?, 
                            date_modified = ?, 
                            time_modified = ?, 
                            status = 1
                        WHERE institution_id = ? AND student_id = ?";
    
        $stmt_update = $conn_rjllearning->prepare($sql_update);
        $stmt_update->execute(array(
            $branch_id, 
            $class_id, 
            $section_id, 
            $name, 
            $ledgerhead, 
            $balance_in_words,
            date('Y-m-d'), 
            time(), 
            $institution_id, 
            $student_id
        ));

        // Commit transaction
        $conn_rjllearning->commit();
        return $stmt_update->rowCount() > 0;
    } catch (Exception $e) {
        // Rollback transaction and handle error
        errorreturn($e->getMessage(), $conn_rjllearning);
    }
}




function checkLedgerParentGroup($conn, $ledger_parent_group, $ledgerhead) {
    // Fetch ledgerhead details
    $ledgerheads = fetchLedgerheadDetails($conn);
    
    // Create an array of ledgerhead names and parent groups
    $ledgerhead_names = array_column($ledgerheads, 'ledgerhead_name');
    $ledgerhead_parent_groups = array_column($ledgerheads, 'ledger_parent_group');
    
    // Check if the provided ledgerhead exists
    if (!in_array($ledgerhead, $ledgerhead_names)) {
        return ["status" => "error", "message" => "Provided ledgerhead does not exist."];
    }

    // Check if the ledger_parent_group matches with the ledgerhead
    $parent_group_exists = in_array($ledger_parent_group, $ledgerhead_parent_groups);
    
    if (!$parent_group_exists) {
        errorreturn ( "Provided ledger parent group does not match with any ledgerhead.");
    }

    return true;
}


function checkLedgerParentGroupMatch($conn, $ledger_parent_group, $ledgerhead) {
    // SQL query to fetch ledger groups where ledgerhead matches
    $sql = "SELECT main_ledgerhead, group_name 
            FROM act_ledger_group 
            WHERE main_ledgerhead = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute([$ledgerhead]);
    
    // Fetch all matching rows
    $ledger_groups = $stmt->fetchAll(PDO::FETCH_ASSOC);

    
    // Check if any record matches the provided parent group
    foreach ($ledger_groups as $group) {
        if (trim($group['group_name']) === trim($ledger_parent_group)) {
            return true;
        }
    }

   errorreturn ( "Provided ledger parent group does not match with any ledgerhead.");
}




