<?php

function check_benefit_record($tran_reference)
{
    $br_row = get_benefit_record($tran_reference);
    if($br_row == null){
        return false;
    }
    else{
        return true;
    }
}

function validate_benefit_data($benefit)
{
    if($benefit['points'] <= 0 && $benefit['discount'] <=0)
        return array("passed" => false, "message" => _("No benefits."));
            
    return array("passed" => true, "message" => _(""));
}


function get_member_no($invoice){
    
    $member_no = $invoice['member_no'];
    
    if(strlen($member_no) > 0){
        return $member_no;
    }  
    
    return "General";
    
}

function load_benefit_data($invoice,$pos_benefit)
{
    $benefit['tran_reference'] = $invoice['reference']."_".$pos_benefit['promotion_code'];
    $benefit['member_no'] = get_member_no($invoice);
    $benefit['promotion_code'] = $pos_benefit['promotion_code'];
    
    $formatted_date = change_date_format("YYYYMMDD", $invoice['order_date'], "YYYYMMDD");
    $benefit['tran_date'] = $formatted_date;
    $benefit['tran_type_code'] = "P";
    $benefit['points'] = $pos_benefit['points'];
    $benefit['discount'] = $pos_benefit['discount'];
    $benefit['comment'] = "";
    
    $myrow = get_sales_invoice_id($invoice['reference']);
    if($myrow){
        $benefit['invoice_id'] = $myrow['trans_no'];
    }
    else{
        $benefit['invoice_id'] = 0;
    }
    return $benefit;
}

function benefit_add($invoice,$pos_benefit)
{
    $benefit = load_benefit_data($invoice,$pos_benefit);
    
    if(check_benefit_record($benefit['tran_reference']) == true){
        return array("passed" => false, "message" => _("Benefit record [".$benefit['tran_reference']."] exists"));
    }
    
    $validation_result = validate_benefit_data($benefit);
    
    if($validation_result["passed"] == false){
        return $validation_result;
    }
    
    $abt_result = add_benefit_transaction($benefit['tran_reference'], 
                                        $benefit['member_no'], 
                                        $benefit['promotion_code'],
                                        $benefit['tran_date'], $benefit['tran_type_code'],
                                        $benefit['points'], $benefit['discount'],
                                        $benefit['comment'], $benefit['invoice_id']);
    
    return $abt_result;
}
?>