<?php

function can_delete_payroll_details($payroll_run_id, $editable_payroll_run_status_array) {
    $pay_run_row = get_payroll_run_details($payroll_run_id);
        if (! is_array($pay_run_row)) {
            return array('success' => false, 'message' => "Could not find Payroll Run record #$payroll_run_id.");
        }
    
        if (! in_array($pay_run_row['status'], $editable_payroll_run_status_array)) {
            $payroll_name = get_payroll_run_formatted_name($payroll_run_id);
            return array('success' => false, 'message' => "Payroll $payroll_name is already processed. Not possible to delete Payroll Run Details.");
        }
        
        return array('success' => true, 'message' => '');
}

function check_and_delete_payroll_run_details($payroll_run_id) {
    global $editable_payroll_run_status_array;
    
    $msg = can_delete_payroll_details($payroll_run_id, $editable_payroll_run_status_array);
        if ($msg['success'] === false) {
            return $msg;
        }
    
    $payroll_name = get_payroll_run_formatted_name($payroll_run_id); 
    $result = get_payroll_run_details_records_by_filters(0, $payroll_run_id);
        $num_payroll_details_rows = db_num_rows($result);
        
        if ($num_payroll_details_rows > 0) {
            begin_transaction();
            
                $num_pay_run_af_rows = delete_payroll_run_details($payroll_run_id);
                    if ($num_payroll_details_rows != $num_pay_run_af_rows) {
                        cancel_transaction();

                        return array('success' => false, 'message' => "Another user has updated $payroll_name Payroll Run details.");
                    }

            commit_transaction();
        }
        
        return array('success' => true, 'message' => "$payroll_name Payroll Run details have been deleted.");
}