<?php
ini_set('display_errors', 1);

require_once '../../../resources/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';

// Validation files
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources .  'external_requests/finware_curl/student/curl_left_student_finware.php';

require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

// Decode JSON post data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

$required_fields = [
  'institution_id',
  'branch_id',
  'api_signature',
  'function_type',
  'jwt_token',
  'student_id'
];

foreach ($required_fields as $field) {
  if (!isset($postdata[$field]) || empty($postdata[$field])) {
    errorreturn("All * fields are required.$field");
  }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

if (!$jwt_validate) {
  errorreturn('Invalid JWT token.');
}

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);

if (!$specific_db_name) {
  errorreturn('Access denied.');
} else {
  $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$institution_id = trim($postdata['institution_id']);
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

if ($academic_id == false) {
  errorreturn("Access denied. Academic session not active.");
}

$branch_id = trim($postdata['branch_id']);
$student_id = trim($postdata['student_id']);



$student_id = trim($postdata['student_id']);

// verifying student
$verify_query = "SELECT id, admission_id, admission_number, nationality, caste, date_admission, dob , class_id , section_id FROM students WHERE institution_id = ? AND branch_id = ? AND  id = ?";
$verify_stmt = $conn_rjllearning_specific->prepare($verify_query);
$verify_stmt->execute([$institution_id, $branch_id, $student_id]);
$student_exists = $verify_stmt->fetchAll();

if (count($student_exists) != 1) {
    errorreturn("Student record not found.");
}
$date_admission = $student_exists[0]['date_admission'];
$dob = $student_exists[0]['dob'];
$class_id = $student_exists[0]['class_id'];
$section_id = $student_exists[0]['section_id'];

// Proceed with alumni creation or update

$class_in_words = isset($postdata['class_in_words']) ? $postdata['class_in_words'] : null;
$school_last_examination = trim($postdata['school_last_examination']);
$failed_same_class = trim($postdata['failed_same_class']);
$subject_studied = isset($postdata['subject_studied']) ? $postdata['subject_studied'] : null;

if ($subject_studied !== null) {
  // Iterate over the array of objects and access each item
  foreach ($subject_studied as $item) {
    // Access each property of the object
    $value = $item['value'];
    // Process $value as needed
  }
}
// $last_class = trim($postdata['last_class']);
$last_class = isset($postdata['last_class']) ? trim($postdata['last_class']) : null;

$promotion_higher_class = isset($postdata['promotion_higher_class']) ? trim($postdata['promotion_higher_class']) : null;
$paid = isset($postdata['paid']) ? trim($postdata['paid']) : null;
$fee_concession = isset($postdata['fee_concession']) ? trim($postdata['fee_concession']) : null;
$working_days = trim($postdata['working_days']);
$details_guide = isset($postdata['details_guide']) ? trim($postdata['details_guide']) : null;
$present_days = isset($postdata['present_days']) ? trim($postdata['present_days']) : null;
$board = isset($postdata['board']) ? trim($postdata['board']) : null;
$ncc = isset($postdata['ncc']) ? trim($postdata['ncc']) : null;
$nationality = trim($postdata['nationality']);
$caste = trim($postdata['caste']);
$conduct = isset($postdata['conduct']) ? trim($postdata['conduct']) : null;
$class_in_figure = isset($postdata['class_in_figure']) ? trim($postdata['class_in_figure']) : null;
// $extra_curricular_activities = isset($_FILES['extra_curricular_activities']) ? $_FILES['extra_curricular_activities'] : null;
$extra_curricular_activities = trim($postdata['extra_curricular_activities']);
$date_application_certificate = $postdata['date_application_certificate'];
$date_issue_certificate = $postdata['date_issue_certificate'];
// $date_application_certificate = isset($postdata['date_application_certificate']) ? $postdata['date_application_certificate'] : null;
// $date_issue_certificate = isset($postdata['date_issue_certificate']) ? $postdata['date_issue_certificate'] : null;
$reasons_leaving_school = trim($postdata['reasons_leaving_school']);
$remarks = trim($postdata['remarks']);

$conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
$conn_rjllearning_specific->beginTransaction();
if ($postdata['function_type'] == "create_manage_alumni") {
  $res = $conn_rjllearning_specific->prepare("SELECT id FROM left_students WHERE institution_id = ? AND branch_id=? AND class_id = ? AND section_id = ? AND student_id  = ?");
  $res->execute([$institution_id, $branch_id, $class_id, $section_id, $student_id]);
  $result1 = $res->fetchAll();

  if (count($result1) >= 1) {
    errorreturn("Alumni already exists.");
  } else {

    $sql = "SELECT user_id, admission_number  from students where institution_id = ? and id = ?";
    $fetch = $conn_rjllearning_specific->prepare($sql);
    $fetch->execute(array($institution_id, $student_id));
    $result = $fetch->fetchAll();
    if (count($result) != 1) {
      $conn_rjllearning_specific->rollBack();
    } else {
      $student_userid = $result[0]['user_id'];
      $admission_number = $result[0]['admission_number'];
      // $sibling_str = $result[0]['sibling'];
      // $sibling_bool = $result[0]['sibling_bool'];

      // // Only set this variable if sibling_bool is 1
      // $sibling_list = null;
      // if ((int)$sibling_bool === 1) {
      //     $sibling_list = $sibling_str;
      // }
    }

    $insert_query = "INSERT INTO left_students (
    institution_id, branch_id, class_id, class_in_words, section_id, student_id, nationality, caste, date_admission, dob, school_last_examination, 
    failed_same_class, subject_studied, last_class, promotion_higher_class, paid, fee_concession, 
    working_days, board, ncc, conduct, present_days, class_in_figure, extra_curricular_activities, date_application_certificate, 
    date_issue_certificate, reasons_leaving_school, remarks, added_by, admission_number
) VALUES (
    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";

    $stmt = $conn_rjllearning_specific->prepare($insert_query);

    $subject_studied_json = json_encode($subject_studied);
    $stmt->execute([
      $institution_id,
      $branch_id,
      $class_id,
      $class_in_words,
      $section_id,
      $student_id,
      $nationality,
      $caste,
      $date_admission,
      $dob,
      $school_last_examination,
      $failed_same_class,
      $subject_studied_json,
      $last_class,
      $promotion_higher_class,
      $paid,
      $fee_concession,
      $working_days,
      $board,
      $ncc,
      $conduct,
      $present_days,
      $class_in_figure,
      $extra_curricular_activities,
      $date_application_certificate,
      $date_issue_certificate,
      $reasons_leaving_school,
      $remarks,
      $username,
      $admission_number
    ]);

    $id = $conn_rjllearning_specific->lastInsertId();


    // Fetch all student_admission records with non-empty sibling fields
    $admn_to_remove = $admission_number; // the admission number of the student being marked as left

    // Fetch all student_admission records with non-empty sibling fields
    // Assuming $institution_id and $branch_id are already set

    $sql = "SELECT id, sibling 
                FROM students
                WHERE institution_id = ? 
                AND branch_id = ? 
                AND sibling LIKE ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $array_params = [$institution_id, $branch_id, "%'" . $admission_number . "%'"];
    $stmt->execute($array_params);
    $students_with_siblings = $stmt->fetchAll();


    foreach ($students_with_siblings as $row) {

      $current_id = $row['id'];
      $sibling_str = $row['sibling'];

      // Remove quotes and whitespace from sibling admission numbers
      $siblings = array_map('trim', explode(",", str_replace("'", "", $sibling_str)));

      // Check if the current student's siblings include the one being removed
      if (in_array($admn_to_remove, $siblings)) {

        // Remove the sibling to be removed
        $updated_siblings = array_filter($siblings, function ($s) use ($admn_to_remove) {
          return $s !== $admn_to_remove;
        });
        $final_sibling_str = count($updated_siblings) > 0 ? "'" . implode("','", $updated_siblings) . "'" : '';

        $update_left_sibling = "UPDATE left_students SET left_siblings_id = ? WHERE $id = ? AND institution_id = ?";
        $conn_rjllearning_specific->prepare($update_left_sibling)->execute([$final_sibling_str, $id, $institution_id]);


        // If no siblings are left after removal, reset both sibling fields
        if (count($updated_siblings) === 0) {
          $update = "UPDATE students SET sibling = '', sibling_bool = 0 WHERE id = ?";
          $conn_rjllearning_specific->prepare($update)->execute([$current_id]);
        } else {
          // If there are more than one sibling left, update the sibling list
          $updated_str = "'" . implode("','", $updated_siblings) . "'";
          $update = "UPDATE students SET sibling = ? WHERE id = ?";
          $conn_rjllearning_specific->prepare($update)->execute([$updated_str, $current_id]);
        }
      }
    }

    // set can_activate to 0 in users
    // set can_activate to 0 in students, status to -1 that means left
        $sql = "UPDATE students SET can_activate = ?, status = ?, date_left = ? WHERE institution_id = ? AND id = ?";
        $conn_rjllearning_specific->prepare($sql)->execute([0, 0, $date_issue_certificate, $institution_id, $student_id]);
        
        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        
        $ledger_message = '';
        if (!empty($branch)) {
            $student_data = [
                "workspace_id" => $workspace_id,
                "branch" => $branch,
                "student" => $student_id
            ];
            
            // Call and capture any message
            $ledger_result = curlLeftStudentFinware($student_data);
            if ($ledger_result !== true) {
                $ledger_message = $ledger_result; // e.g., "Student ledger not found. Please create it manually in Finware."
            }
        }
        
        $conn_rjllearning_specific->commit();
        
        $sql = "UPDATE users SET can_activate = ?, status = ? WHERE workspace_id = ? AND institution_id = ? AND id = ?";
        $conn_rjllearning->prepare($sql)->execute([0, 0, $workspace_id, $institution_id, $student_userid]);
        
        // Final message
        $success_msg = "Successfully alumni added.";
        if (!empty($ledger_message)) {
            $success_msg .= " Note: " . $ledger_message;
        }
        
        // Return success response
        successreturn(['id' => $id, 'successmsg' => $success_msg]);


  }
}
