<?php
require_once '../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

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

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);
checkIfNoPhpContentsReceive();

if (
    
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;

$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);



require_once $base_path_to_learning . 'functions/get_branch_functions.php';



if ($postdata['function_type'] == "fetch_apply_leaves") {

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if (isset($postdata['subject_id']) and !empty($postdata['subject_id'])) {
        $subject_id = trim($postdata['subject_id']);
    } else {
        $subject_id = null;
       
    }

    // $section_id = trim($postdata['section_id']) ;
    // $search_string = isset($postdata['search_string']) ? trim($postdata['search_string']) : null;
      if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }
    
    // $subject_leave = isset($postdata['subject_leave']) ? trim($postdata['subject_leave']) : null;
    if (isset($postdata['subject_leave']) and !empty($postdata['subject_leave'])) {
        $subject_leave = trim($postdata['subject_leave']);
    } else {
        $subject_leave = null;
    }
    // $description = isset($postdata['description']) ? trim($postdata['description']) : null;
      if (isset($postdata['description']) and !empty($postdata['description'])) {
        $description = trim($postdata['description']);
    } else {
        $description = null;
    }
    
    // $start_date = isset($postdata['start_date']) ? trim($postdata['start_date']) : null;
      if (isset($postdata['from_date']) and !empty($postdata['from_date'])) {
        $start_date = trim($postdata['from_date']);
    } else {
        $start_date = null;
    }
    // $end_date = isset($postdata['end_date']) ? trim($postdata['end_date']) : null;
    
        if (isset($postdata['to_date']) and !empty($postdata['to_date'])) {
        $end_date = trim($postdata['to_date']);
    } else {
        $end_date = null;
    }
    
    // $date_created = isset($postdata['date_created']) ? trim($postdata['date_created']) : null;
        if (isset($postdata['date_created']) and !empty($postdata['date_created'])) {
        $date_created = trim($postdata['date_created']);
    } else {
        $date_created = null;
    }
    
    // $time_created = isset($postdata['time_created']) ? trim($postdata['time_created']) : null;
         if (isset($postdata['time_created']) and !empty($postdata['time_created'])) {
        $time_created = trim($postdata['time_created']);
    } else {
        $time_created = null;
    }
    
    // $name = isset($postdata['name']) ? trim($postdata['name']) : null;
        if (isset($postdata['name']) and !empty($postdata['name'])) {
        $name = trim($postdata['name']);
    } else {
        $name = null;
    }
    
    $status = isset($postdata['status']) ? trim($postdata['status']) : null;

    // Validate dates
    if ($start_date != null && $end_date != null && strtotime($start_date) > strtotime($end_date)) {
        errorreturn('Invalid Date format');
    }

    // Call the function to get apply leaves
    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;

        $apply_leaves_data = getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $subject_leave, $description, $start_date, $end_date, $date_created, $time_created,$userid, $status, $limit, $offset);
    } else {
        $apply_leaves_data = getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $subject_leave, $description, $start_date, $end_date, $date_created, $time_created,$userid, $status, $limit, null);
    }
    successreturn($apply_leaves_data);
}

function getapplyleaves($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $subject_leave, $description, $start_date, $end_date, $date_created, $time_created,$userid, $status, $limit, $offset)
{

    $sql = "SELECT  count(*) as total_rows FROM  apply_leaves  where institution_id =? ";
    $array_params = [$institution_id];
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];


    // $sql = "SELECT * FROM apply_leaves WHERE institution_id = ?";
    // $array_params = array($institution_id);

    // // Append conditions based on filters
    // if ($branch_id != null && $branch_id != 'all') {
    //     $sql .= " AND branch_id = ?";
    //     $array_params[] = $branch_id;
    // }

    // if ($class_id != null && $class_id != 'all') {
    //     $sql .= " AND class_id = ?";
    //     $array_params[] = $class_id;
    // }

    // if ($subject_id != null && $subject_id != 'all') {
    //     $sql .= " AND subject_id = ?";
    //     $array_params[] = $subject_id;
    // }

    // if ($section_id != null && $section_id != 'all') {
    //     $sql .= " AND section_id = ?";
    //     $array_params[] = $section_id;
    // }

    // if ($date_created != null) {
    //     $sql .= " AND date_created = ?";
    //     $array_params[] = $date_created;
    // }

    // if ($start_date != null && $end_date != null) {
    //     $sql .= " AND date_created BETWEEN ? AND ?";
    //     $array_params[] = $start_date;
    //     $array_params[] = $end_date;
    // }

    // if ($search_string != null) {
    //     $sql .= " AND (subject_leave LIKE ? OR description LIKE ?)";
    //     $array_params[] = '%' . $search_string . '%';
    //     $array_params[] = '%' . $search_string . '%';
    // }


    // $sql .= " ORDER BY date_created DESC ";

    // $sql .= " LIMIT " . $offset . ", " . $limit;


    // // Prepare and execute the SQL query
    // $stmt = $conn_rjllearning_specific->prepare($sql);


    // $stmt->execute($array_params);
    // $result = $stmt->fetchAll();



if ($limit == 'all') {
    $sql_session = "SELECT * FROM apply_leaves WHERE institution_id = ? ";
    $array_params = [$institution_id];

    // Branch ID
    if ($branch_id != 'all' && $branch_id != null) {
        $sql_session .= " AND branch_id = ? ";
        $array_params[] = $branch_id;
    }

    // Class ID
    if ($class_id != 'all' && $class_id != null) {
        $sql_session .= " AND class_id = ? ";
        $array_params[] = $class_id;
    }

    // Subject ID
    if ($subject_id != 'all' && $subject_id != null) {
        $sql_session .= "  AND (subject_id = ? or subject_id ='all')";
        $array_params[] = $subject_id;
    }

    // Section ID
    if ($section_id != 'all' && $section_id != null) {
        $sql_session .= " AND section_id = ? ";
        $array_params[] = $section_id;
    }

    // Search string
    if ($search_string != null) {
        $sql_session .= " AND (subject_leave LIKE ? OR description LIKE ?) ";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    // Date range
    if ($start_date != null && $end_date != null) {
        $sql_session .= " AND date_created BETWEEN ? AND ? ";
        $array_params[] = $start_date;
        $array_params[] = $end_date;
    }

    // Order by and limit
    $sql_session .= " ORDER BY date_created DESC, time_created DESC";
} else {
    $sql_session = "SELECT * FROM apply_leaves WHERE institution_id = ? ";
    $array_params = [$institution_id];

    // Branch ID
    if ($branch_id != 'all' && $branch_id != null) {
        $sql_session .= " AND branch_id = ? ";
        $array_params[] = $branch_id;
    }

    // Class ID
    if ($class_id != 'all' && $class_id != null) {
        $sql_session .= " AND class_id = ? ";
        $array_params[] = $class_id;
    }

    // Subject ID
    if ($subject_id != 'all' && $subject_id != null) {
        $sql_session .= "  AND (subject_id = ? or subject_id ='all')";
        $array_params[] = $subject_id;
    }

    // Section ID
    if ($section_id != 'all' && $section_id != null) {
        $sql_session .= " AND section_id = ? ";
        $array_params[] = $section_id;
    }

    // Search string
    if ($search_string != null) {
        $sql_session .= " AND (subject_leave LIKE ? OR description LIKE ?) ";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    // Date range
    if ($start_date != null && $end_date != null) {
        $sql_session .= " AND date_created BETWEEN ? AND ? ";
        $array_params[] = $start_date;
        $array_params[] = $end_date;
    }

    // Order by and limit
      $sql_session .= " order by date_created desc, time_created desc ";
      $sql_session .= "LIMIT " . $offset . " ," . $limit . "";
}

$stmt = $conn_rjllearning_specific->prepare($sql_session);
$stmt->execute($array_params);
$result = $stmt->fetchAll();

    
    

    // $newArray = [];
    // foreach ($result as $item) {
    //     $newArray[] = [
    //         'student_id' => $item['id'],
    //         'name' => $item['name'],
    //     ];
    // }     

    $student_sql = "SELECT id,name FROM students WHERE institution_id = ?  AND user_id= ? ";


    // $student_stmt = $conn_rjllearning_specific->prepare($student_sql);

    // $student_stmt->execute([$institution_id, $branch_id,$row['added_by']]);
    // $result = $student_stmt->fetchAll(PDO::FETCH_ASSOC);




    // Process the result and prepare the response
    $array_return = [];
    $branch_info_all = [];
    $class_info_all = [];
    $section_info_all = [];
    $subject_info_all = [];

    $leave_info = [];

    foreach ($result as $row) {

        $student_stmt = $conn_rjllearning_specific->prepare($student_sql);

        $student_stmt->execute([$institution_id, $userid]);
        $result = $student_stmt->fetchAll(PDO::FETCH_ASSOC);


        // Process attachment
        if (!empty($row[0]['attachment']) && !is_array($row[0]['attachment'])) {
            $data_attachment = json_decode($row[0]['attachment'], true);
            $filePath = $data_attachment['filepath'];
            $originalName = $data_attachment['original_name'];
            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
            $final_array_attachment = array("filepath" => $aws_attachment, "original_name" => $originalName);
        } else {
            $final_array_attachment = null;
        }

        // Branch Info
        $branch_id = $row['branch_id'];
        if ($branch_id == 'all') {
            $branch_info = array('branch_id' => $branch_id, 'name' => ucwords($branch_id));
        } else {
            // Fetch branch data from database
            $branch_sql = "SELECT * FROM branch WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($branch_sql);
            $stmt->execute([$institution_id, $branch_id]);
            $branch_data = $stmt->fetch();

            $branch_info = array('branch_id' => $branch_data['id'], 'name' => $branch_data['name']);
        }

        // Class Info
        $class_id = $row['class_id'];
        if ($class_id == 'all') {
            $class_info = array('class_id' => $class_id, 'classname' => ucwords($class_id));
        } else {
            // Fetch class data from database
            $class_sql = "SELECT * FROM class_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($class_sql);
            $stmt->execute([$institution_id, $class_id]);
            $class_data = $stmt->fetch();

            $class_info = array('class_id' => $class_data['id'], 'classname' => $class_data['classname']);
        }

        // Section Info
        $section_id = $row['section_id'];
        if ($section_id == 'all') {
            $section_info = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
        } else {
            // Fetch section data from database
            $section_sql = "SELECT * FROM section_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($section_sql);
            $stmt->execute([$institution_id, $section_id]);
            $section_data = $stmt->fetch();

            $section_info = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
        }

        // Merge branch, class, and section info arrays
        $branch_info_all = $branch_info;
        $class_info_all = $class_info;
        $section_info_all = $section_info;

        // Get subject info
        $subject_id = $row['subject_id'];
       
        if ($subject_id == 'all') {
            $subject_info = array('subject_id' => $subject_id, 'subject_name' => ucwords($subject_id));
        
        } else {
            // Fetch section data from database
            $section_sql = "SELECT * FROM subject_info WHERE institution_id = ? AND id = ?";
            $stmt = $conn_rjllearning_specific->prepare($section_sql);
            $stmt->execute([$institution_id, $subject_id]);
            $subject_data = $stmt->fetch();

            $subject_info = array('section_id' => $subject_data['id'], 'subject_name' => $subject_data['subject_name']);
        }

        // $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $row['subject_id']);

        // $subject_info_all = $subject_info;

        // Create the response array
        $array_return[] = [
            'student_id' => $result[0]['id'],
            'name' => $result[0]['name'],
            'branch_info' => $branch_info_all,
            'class_info' => $class_info_all,
            'section_info' => $section_info_all,
            'subject_info' => $subject_info,
            'apply_leave_id' => $row['id'],
            'attachment' => $final_array_attachment,
            'subject_leave' => $row['subject_leave'],
            'description' => $row['description'],
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date'],
            'date_created' => $row['date_created'],
            'time_created' => $row['time_created'],
            'status' => $row['status'],
          
        ];
    }



    // Return the array
    // return $array_return;

    if (count($result) < 50) {

        return array('total_rows' => $totalrows, 'leave_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'leave_info' => $array_return, 'maxreach' => 0);
    }
}
