<?php
//base path learning to resources
require_once '../../../base_path_include.php';

require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning_resources.'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';

// Receiving and processing data
$data = json_decode(file_get_contents('php://input'), true);

// Check if data is properly decoded and signature is present
if (!$data || !isset($data['api_signature'])) {
    echo json_encode(['error' => true, 'message' => 'Missing or invalid API signature.']);
    die();
}

// Validate signature
validateCurlSignature($data['api_signature']);

// Ensure required keys exist
$required_keys = ['data'];
foreach ($required_keys as $key) {
    if (!isset($data[$key])) {
        echo json_encode(['error' => true, 'message' => "Missing parameter: $key"]);
        die();
    }
}

// Extract student data
$branch_students = $data['data'];

$workspace_id = $branch_students['workspace_id'];
$branch_id = $branch_students['learning_branch_id'];
$admission_number = $branch_students['admission_number'];

// Now you can proceed with these values
$sql = $conn_rjllearning->prepare("SELECT db_name FROM workspace_database_info WHERE workspace_id = ? and status  = ? ");
$sql->execute(array($workspace_id, 1));
$get_db = $sql->fetchAll();
// print_r($get_db);die();
if (count($get_db) != 1) {
  echo json_encode([
    'error' => true,
    'message' => 'Database not exists for this workspace.'
  ]);
  die();
}
$learning_db_name  = $get_db[0]['db_name'];

$conn_rjllearning_specific = dynamicDbConnection($learning_db_name);

// Fetch branch details
$sqlbranch = $conn_rjllearning_specific->prepare("SELECT * FROM branch WHERE id = ? AND status = ?");
$sqlbranch->execute(array($branch_id, '1'));
$result_branch = $sqlbranch->fetchAll();

// Return error if no branch found
if (count($result_branch) < 1) {
     echo json_encode([
          'error' => true,
          'message' => "Branch Not Found."
    ]);
    die();
}

$institution_id = $result_branch[0]['institution_id'];

//active academic session
$sqlacademicsession = $conn_rjllearning_specific->prepare("SELECT id, name FROM academic_session WHERE institution_id = ? AND active_academic_session = ?");
$sqlacademicsession->execute(array($institution_id, '1'));
$result_academic_session = $sqlacademicsession->fetch();
if (!$result_academic_session) {
    echo json_encode([
          'error' => true,
          'message' => "Academic Session Not Found."
    ]);
    die();
}

// Get student using admission_no
$sqlStudents = $conn_rjllearning_specific->prepare("SELECT id, name, admission_number, class_id, section_id, fathername, mothername, gender, mobile, email, address_line_1 FROM students WHERE institution_id = ? AND branch_id = ? AND admission_number = ?");
$sqlStudents->execute([$institution_id, $branch_id, $admission_number]);
$result_students = $sqlStudents->fetch(PDO::FETCH_ASSOC);

if (!$result_students) {
    echo json_encode([
        'error' => true,
        'message' => "Student Not Found."
    ]);
    die();
}

$name = $result_students['name'];
$father_name = $result_students['fathername'];
$mother_name = $result_students['mothername'];
$gender = $result_students['gender'];
$admission_number = $result_students['admission_number'];

// Generate ledger name
if (!empty($father_name)) {
    $relation = ($gender === 'M') ? 'S/o' : 'D/o';
    $ledger_name = "$name $relation $father_name - $admission_number";
} elseif (!empty($mother_name)) {
    $relation = ($gender === 'M') ? 'S/o' : 'D/o';
    $ledger_name = "$name $relation $mother_name - $admission_number";
} else {
    $ledger_name = "$name - $admission_number";
}

// Get class and section info
$class_info = getClass($conn_rjllearning_specific, $institution_id, $result_students['class_id']);
$section_data = getSection($conn_rjllearning_specific, $institution_id, $result_students['section_id']);
$class_name = $class_info['class_name'];
$section_name = $section_data['section_name'];

$class_section = $class_name . ' ' . $section_name;
// Prepare the student data
$studentdata = [
    'id' => $result_students['id'],
    'ledger_name' => $ledger_name,
    'ledger_main_ledgerhead' => 'Sundry Debtors',
    'mobile' => $result_students['mobile'],
    'email' => $result_students['email'],
    'class_section' => $class_section,
    'ledger_address' => $result_students['address_line_1'],
    'admission_number' => $admission_number
];

echo json_encode($studentdata);
die();

die();