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

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

//valdation file
require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';
require_once $base_path . 'user_management/authenticate.php';

//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';
$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();


if (!isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name']) or  !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']);

//authenticate jwt token
$jwttoken = $postdata['jwt_token'];

$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$created_by = $jwt_validate->data->username;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$userid = $jwt_validate->data->id;

$function_code = 'create_files_categories';
$confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
if (!$confirmed_role_user){ 
        errorreturn('Access denied.');
}else{
        $specific_db_conn = dynamicDbConnection($confirmed_role_user);
         if ($role == null) {
            checkCompanyBranchFunctionAccess($specific_db_conn, $role, $userid, $workspace_id, null, null, null,  $function_code);
         }
}

$name = ucwords(trim($postdata['name'])); 


if ($postdata['function_type'] == 'create_files_categories') {

        //check ledger categries exists or not
        $sql = "Select name from   upload_categories where name = ? and workspace_id = ?";
        $fetch_category = $specific_db_conn->prepare($sql);
        $fetch_category->execute(array($name,$workspace_id));
        if (count($fetch_category->fetchAll()) > 0) {
            
            errorreturn('Upload categoires name already exists');
        }
        
    
        $sql = "Insert into  upload_categories(workspace_id,name,created_by, time_created) values (?, ?, ?, ?)";
        $insert_ledger = $specific_db_conn->prepare($sql);
        $insert_ledger->execute(array($workspace_id,$name, $created_by, time()));
        $ledgerid = $specific_db_conn->lastInsertId();
        successreturn(array('id' => $ledgerid, 'successmsg' => "Files categories added successfully."));
      
} if (!isset($postdata['category_id']) or !checkIfIssetAndNotEmpty($postdata['category_id'])) {
            errorreturn('Error in updating the company.');
        } else {
            $category_id = $postdata['category_id'];
        }

        if ($postdata['function_type'] == 'alter_upload_categories') {


            $sql = "Select name,workspace_id from upload_categories where  id != ? and workspace_id  = ?  and name = ? ";
            $fetch_categories = $specific_db_conn->prepare($sql);
            $fetch_categories->execute(array($category_id,$workspace_id,$name));
            $result_categories = $fetch_categories->fetchAll();
            if (count($result_categories) > 0) {
                errorreturn('Upload categories already exists.');
            }


            $sql = "Select name from  upload_categories where id =  ? and workspace_id = ?";
            $fetch_payment = $specific_db_conn->prepare($sql);
            $fetch_payment->execute(array($category_id,$workspace_id));
            $result_payment  = $fetch_payment->fetchAll();
            if (count($result_payment) >= 1) {
                if($result_payment[0]['name'] === 'Others' )
                errorreturn('Contact admin.');
            }
            
             
            $sql = "Select name from  upload_categories where  id = ? and workspace_id  = ?  ";
            $fetch_categories = $specific_db_conn->prepare($sql);
            $fetch_categories->execute(array($category_id,$workspace_id));
            $result_categories = $fetch_categories->fetchAll();
            if (count($result_categories) != 1) {
                errorreturn('Access denied. Upload categories could not be identified.');
            }

            $existing_ledger_name = $result_categories[0]['name'];
           

            if ($name != $existing_ledger_name) {
                $sql = "Update  upload_categories set name = ?, created_by = ?, time_created = ? where id = ? and workspace_id = ?";
                $insert_ledger = $specific_db_conn->prepare($sql);
                $insert_ledger->execute(array($name, $created_by, time(),$category_id, $workspace_id));
            }

            successreturn('Files categories updated successfully.');
        }
        errorreturn('Invalid request.');
