<?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 file
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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';


// Fetch and decode input data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// Check required fields
if (
     !isset($postdata['name']) || !checkIfIssetAndNotEmpty($postdata['name']) ||
    !isset($postdata['leave_type']) || !checkIfIssetAndNotEmpty($postdata['leave_type']) ||
    !isset($postdata['start_date']) || !checkIfIssetAndNotEmpty($postdata['start_date']) ||
     !isset($postdata['end_date']) || !checkIfIssetAndNotEmpty($postdata['end_date']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All required fields must be provided.");
}

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;

$name = ucwords($postdata['name']); 
$leave_type = $postdata['leave_type'];
$start_date = trim(date('Y-m-d', strtotime($postdata['start_date'])));
$end_date = trim(date('Y-m-d', strtotime($postdata['end_date'])));
$remarks = (isset($postdata['remarks']) and !empty($postdata['remarks'])) ? trim($postdata['remarks']) : null;
$created_by = $username; // Assuming the logged-in user is creating the record

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['principal'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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);

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

if (!CheckStartDate($start_date)) {
    errorreturn('Invalid Date Format');
}
if (!CheckStartDate($end_date)) {
    errorreturn('Invalid Date Format');
}
if ($start_date >= $end_date) {
    errorreturn('Invalid Date Range');
}

if ($postdata['function_type'] == 'create_extra_paid_leaves') {
    
    $sql = $conn_rjllearning_specific->prepare("SELECT name FROM extra_paid_leaves WHERE institution_id = ? AND name = ? AND leave_type = ?");
    $sql->execute([$institution_id, $name, $leave_type]);
    
    if ($sql->rowCount() > 0) {
        errorreturn("Extra Paid Leave already exists.");
    }

   $sql = "INSERT INTO extra_paid_leaves 
        (institution_id, branch_id, name, leave_type,start_date,end_date,remarks, status, created_by, created_on) 
        VALUES (?, ?, ?, ?, ?, ?, ?,?, ?, ?)";  

    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $name,
        $leave_type,
        $start_date,
        $end_date,
        $remarks,
        1,  // Status
        $created_by,
        date('Y-m-d H:i:s') // Timestamp
    ]);

    $leave_id = $conn_rjllearning_specific->lastInsertId();
    successreturn(['id' => $leave_id, 'successmsg' => "Extra paid leave successfully added."]);
}elseif($postdata['function_type'] == 'alter_extra_paid_leaves'){
     if (!isset($postdata['extra_paid_leave_id']) || !checkIfIssetAndNotEmpty($postdata['extra_paid_leave_id'])) {
        errorreturn('Error in updating the paid leaves.');
    } else {
        $extra_paid_leave_id = $postdata['extra_paid_leave_id'];
    }
    
    $sql = $conn_rjllearning_specific->prepare("SELECT name FROM extra_paid_leaves WHERE id != ? AND institution_id = ? AND name = ? AND leave_type = ?");
    $sql->execute([$extra_paid_leave_id,$institution_id, $name, $leave_type]);
    if ($sql->rowCount() > 0) {
        errorreturn("Extra Paid Leave already exists.");
    }
    
    $sql = "UPDATE extra_paid_leaves SET name = ?, leave_type = ?,start_date= ?, end_date = ?, remarks = ? WHERE id = ? AND 
            institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$name, $leave_type ,$start_date,$end_date,$remarks, $extra_paid_leave_id, $institution_id, $branch_id]);
      successreturn("Extra paid leave successfully updated.");
    
}
