<?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 . 'functions/common_functions.php';

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

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);
//then workspace_id is iin decodede data of jwt use from there
$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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['principal'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

if (
    !isset($postdata['holiday_name']) or !checkIfIssetAndNotEmpty($postdata['holiday_name']) or
    !isset($postdata['holiday_date']) or !checkIfIssetAndNotEmpty($postdata['holiday_date']) or
    !isset($postdata['holiday_type']) or !checkIfIssetAndNotEmpty($postdata['holiday_type']) or
    !isset($postdata['applicable_to']) or !checkIfIssetAndNotEmpty($postdata['applicable_to'])
) {
    errorreturn("All holiday fields are required.");
}

$holiday_name = ucwords(strtolower($postdata['holiday_name']));
$holiday_date = $postdata['holiday_date'];
$holiday_type = $postdata['holiday_type'];
if ($holiday_type != null) {
    if ((!in_array($holiday_type, ["Gazetted", "Non-Gazetted"]))) {
        errorreturn("$holiday_type is not a valid option for Holiday type.");
    }
}

$applicable_to = $postdata['applicable_to'];
if ($applicable_to != null) {
    if ((!in_array($applicable_to, ["students", "teachers", "both"]))) {
        errorreturn("$applicable_to is not a valid option for applicable to.");
    }
}
$date_now = date('Y-m-d');

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

    $check_duplicate_sql = "SELECT id FROM holiday_calendar 
                            WHERE (institution_id = ? AND branch_id = ? AND holiday_date = ?)
                            OR (institution_id = 'all' AND branch_id = 'all' AND holiday_date = ?)";
    $check_stmt = $conn_rjllearning_specific->prepare($check_duplicate_sql);
    $check_stmt->execute([$institution_id, $branch_id, $holiday_date, $holiday_date]);
    $existing_holiday = $check_stmt->fetch();

    if ($existing_holiday) {
        errorreturn("A holiday already exists on this date for the selected institution and branch, or as a global holiday.");
    }
    try {
        $sql = "INSERT INTO holiday_calendar (institution_id, branch_id, holiday_name, holiday_date, holiday_type, applicable_to, date_created, time_created, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([$institution_id, $branch_id, $holiday_name, $holiday_date, $holiday_type, $applicable_to, $date_now, time(), 1]);

        $id = $conn_rjllearning_specific->lastInsertId();
        successreturn("Holiday added successfully.");
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_holiday") {

    if (!isset($postdata['holiday_id']) or !checkIfIssetAndNotEmpty($postdata['holiday_id'])) {
        errorreturn('Error in updating the holiday.');
    } else {
        $id = $postdata['holiday_id'];
    }

    $res = $conn_rjllearning_specific->prepare("SELECT id FROM holiday_calendar WHERE id = ? and institution_id=? ");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("Holiday not exists. ");
    }

    $sql_hoilday = "UPDATE holiday_calendar SET holiday_name =?,holiday_date =?,holiday_type =?,applicable_to= ? WHERE id=? and institution_id=? and branch_id =?";
    $conn_rjllearning_specific->prepare($sql_hoilday)->execute(array($holiday_name, $holiday_date, $holiday_type, $applicable_to, $id, $institution_id, $branch_id));
    successreturn("Updated holiday Successfully");
}
