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

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';

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

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
$postdata = json_decode(file_get_contents("php://input"), true);
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  !checkIfIssetAndNotEmpty($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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['teacher'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
$academic_id = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific,$version, $updated_time, $userid, $institution_id);

// Function to create a new activity
function createActivityPlanner($conn, $data, $created_by, $institution_id, $branch_id) {
    global $userid;
    global $conn_rjllearning;

    $function_type = "create_activity";
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles    = $teacher_data['class_incharge_roles'];
    $staff_access_modules    = $teacher_data['staff_access_modules'];

    $scheduleDetailsJson = json_encode($data['schedule_details']);
    $createdIds = [];

    $class_id   = $data['class_id'];
    $section_id = $data['section_id'];
    $faculty_id = $data['faculty_id'];

    // Check permission
    $check_faculty_status = checkFacultyModuleGranted(
        $function_type,
        $class_section_subjects,
        $class_incharge_roles,
        $staff_access_modules,
        $class_id,
        $section_id,
        null,
        $conn_rjllearning
    );

    if (!$check_faculty_status) {
        errorreturn("Access denied: You do not have the required permissions.");
    }

    // Insert into activity_planner
    $stmt = $conn->prepare("INSERT INTO activity_planner (
        institution_id, activity_name, activity_type,
        branch_id, class_id, section_id, faculty_id,
        description, from_date, to_date, schedule_details,
        status, created_by, date_created, last_modified_by, last_modified_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $stmt->execute([
        $institution_id,
        $data['activity_name'],
        $data['activity_type'],
        $branch_id,
        $class_id,
        $section_id,
        $faculty_id,
        $data['description'],
        $data['from_date'],
        $data['to_date'],
        $scheduleDetailsJson,
        1,
        $created_by,
        date('Y-m-d H:i:s'),
        $created_by,
        date('Y-m-d H:i:s')
    ]);

    $createdIds[] = $conn->lastInsertId();

    successreturn([
        'message' => 'Activity created successfully.',
        'activity_ids' => $createdIds
    ]);
}


// Function to update an existing activity
function updateActivityPlanner($conn, $data, $modified_by) {
    $sql = "UPDATE activity_planner SET activity_name = ?, activity_type = ?, branch_id = ?, class_id = ?, section_id = ?, faculty_id = ?, description = ?, from_date = ?, to_date = ?, schedule_details = ?, status = ?, last_modified_by = ?, last_modified_at = NOW()
            WHERE id = ? AND institution_id = ?";

    $stmt = $conn->prepare($sql);
    $stmt->execute([
        $data['activity_name'], 
        $data['activity_type'], 
        $branch_id, 
        $data['class_id'], 
        $data['section_id'], 
        $data['faculty_id'], 
        $data['description'], 
        $data['from_date'], 
        $data['to_date'], 
        json_encode($data['schedule_details']), 
        1, 
        $modified_by, 
        $data['activty_planner_id'], 
        $data['institution_id']
    ]);

    return ['message' => 'Activity Updated Successfully', 'activity_id' => $data['activty_planner_id']];
}

// Handle API function types
if ($postdata['function_type'] == "create_activity") {
    if (
        !isset($postdata['activity_name']) or !checkIfIssetAndNotEmpty($postdata['activity_name']) or
        !isset($postdata['activity_type']) or !checkIfIssetAndNotEmpty($postdata['activity_type']) or
        !isset($postdata['from_date']) or !checkIfIssetAndNotEmpty($postdata['from_date'])
    ) {
        errorreturn("Missing required fields.");
    }

    $response = createActivityPlanner($conn_rjllearning_specific, $postdata, $username, $institution_id, $branch_id);
    successreturn($response);

} elseif ($postdata['function_type'] == "update_activity") {
    if (
        !isset($postdata['activty_planner_id']) or !checkIfIssetAndNotEmpty($postdata['activty_planner_id']) or
        !isset($postdata['activity_name']) or !checkIfIssetAndNotEmpty($postdata['activity_name']) or
        !isset($postdata['activity_type']) or !checkIfIssetAndNotEmpty($postdata['activity_type']) or
        !isset($postdata['from_date']) or !checkIfIssetAndNotEmpty($postdata['from_date'])
    ) {
        errorreturn("Missing required fields.");
    }

    $response = updateActivityPlanner($conn_rjllearning_specific, $postdata, $username,$institution_id,$branch_id);
    successreturn($response);

} else {
    errorreturn("Invalid function_type.");
}
