<?php
/**********************************************************************
***********************************************************************/

//$page_security = 'SA_PROJECT_BOQ_ITEMS';

$path_to_root = "../..";

//include_once($path_to_root . "/includes/ui.inc");
//include_once($path_to_root . "/payroll/includes/db/nopay_references_db.inc");
//include_once($path_to_root . "/includes/ui/ui_input.inc");
//include_once($path_to_root . "/projects/includes/db/project_boq_items_db.inc");
//include_once($path_to_root . "/includes/session.inc");

//simple_page_mode(true);
//
//if(!isset($selected_id)){
//    global $selected_id;
//}


function display_petty_cash_item_receiving_location($source_type_id, $source_detail_id)
{
    $myrow = get_petty_cash_item_receive_location_by_source_type($source_type_id, $source_detail_id);
    
    	start_table(TABLESTYLE, "width=25%");
        if(is_array($myrow)){
            label_row("Location :", $myrow["location_name"]);
            hidden('location', $myrow["location"]);
        }else{
            locations_list_row("Location", 'location', null, '', false);               
        }
                                                         
        end_table(2);
}

function display_petty_cash_item_receiving_items($source_type_id, $source_detail_id)
{
        $result = get_petty_cash_item_receive_items_by_source_type($source_type_id, $source_detail_id);

        $n = db_num_rows($result);    
        if($n == 0){
            display_note("No item receipts found.");
            return;
        }    

	start_table(TABLESTYLE, "width=90%");
	$th = array( _("Tran. #"), _("Location"), _("Date"), _("Itemcode"),_("Description") ,_("Unit"), _("Unit Cost"), 
                    _("Quantity"),"Line Total", "Comment",'','');
	table_header($th);

	$k = 0;
        $j = "";
        $total_cost = 0;                  
        $stock_id = 0;
       
                
	while ($myrow = db_fetch($result))
	{                       
            alt_table_row_color($k);            

            label_cell($myrow["trans_no"], "align=center");
            label_cell($myrow["location_name"]);
            label_cell(sql2date($myrow["tran_date"]), "align=center");
            label_cell($myrow["stock_id"]);
            label_cell($myrow["item_description"]);
            label_cell($myrow["tran_unit"]);
            label_cell(number_format($myrow["tran_unit_cost"], 2), "align=right");
            label_cell(number_format($myrow["tran_qty"], 2), "align=right");   
            $line_total = $myrow["tran_unit_cost"] * $myrow["tran_qty"];
            label_cell(number_format($line_total, 2), "align=right"); 
            label_cell($myrow["comment"]);          

            if($myrow["approved_by"] == 0){
                edit_button_cell("Edit".$myrow['id'], _("Edit"));            
                delete_button_cell("Delete_petty_cash_item".$myrow['id'], _("Delete"));
            }
            else{
                label_cell("Processed", "colspan=2 align=center");
            }
            end_row();          

            $j++;

            $total_cost += $line_total ;                
	} 
        
        start_row();
            label_cell(text_bold("Total :"), "colspan=8 align=right");
            amount_cell($total_cost, true);
            label_cell("", "colspan=2");
        end_row();
                                                 
    end_table(2);
    
    submit_center_first('PROCESS_ALL_ITEMS', _("Process Item Receive"), '', 'default');

}

//--------------------------------------------------------------------------------------------------

 
function can_process_petty_cash_item_receiving($stype, $strn_no, $sd_id, $type)
{ 
    $expence_line = get_i_owe_you_expence_line($sd_id);
    $expence_line_amount = $expence_line['amount'];
    $items_total = (float) get_petty_cash_stock_items_total_cost_by_source($stype, $sd_id, -1);
    if(floatcmp($expence_line_amount, $items_total))
    {     
        display_error("Total value of entered stock items Rs.". number_format($items_total,2)." should be equal to the related expense line value of Rs.". number_format($expence_line_amount,2).".");
        set_focus('amount');
        return false;
    }
    return true;
}
          

 
function can_commit_petty_cash_item_receiving_item($selected_id, $stype, $strn_no, $sd_id)
{
    global $project_boq_item_component_primary_types;
    
    if(!(strlen($_POST['location']) > 0))
    {
        display_error( _("Location has to be selected."));
        set_focus('location');
        return false;
    }
    
    if(!(is_date($_POST['tran_date']) > 0))
    {
        display_error( _("Entered date is not in valid format."));
        set_focus('tran_date');
        return false;
    }  
    
    if (!is_date_in_fiscalyear($_POST['tran_date'])) 
    {
        display_error(_("The entered date is not in fiscal year."));
        set_focus('tran_date');
        return false;
    } 
    
    $msg = is_accounting_period_open($_POST['tran_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('tran_date');
        return false;
    }
    
    if(!(strlen($_POST['stock_id']) > 0))
    {
        display_error( _("Item can not be empty."));
        set_focus('stock_id');
        return false;
    }  
    
//    $component = get_boq_item_component_record($boq_item_id, $detail_type_code);
//    if(isset($component['id']) && $component['id'] > 0){
//        if($component['primary_type'] != $primary_type){
//            display_error("There are already created ".$project_boq_item_component_primary_types[$component['primary_type']]." entries for this BOQ component. 
//                            Please delete those before creating entries for new primary type.");
//            set_focus('primary_type');
//            return false;
//        }
//    }
    
    
    if(!(strlen($_POST['tran_unit']) > 0)){
            display_error("Transaction unit can not be empty.");
            set_focus('tran_unit');
            return false;
    }
    
    if(!(check_num('tran_unit_cost',0))){
            display_error("Unit cost has to be numeric and can not be negative.");
            set_focus('tran_unit_cost');
            return false;
    }
    
    if(!(check_num('tran_qty',0.000001))){
            display_error("Quantity has to be numeric and positive.");
            set_focus('tran_qty');
            return false;
    }
    
    $total_cost = (float)get_petty_cash_stock_items_total_cost_by_source($stype, $sd_id, $selected_id);
    $total_cost += input_num('tran_qty') * input_num('tran_unit_cost');
    $myrow = get_i_owe_you_expence_line($sd_id);
    $approved_amount = (float)$myrow['approved_amount'];
    if($total_cost > $approved_amount){
            $msg = "Total value of all receiving items Rs.".number_format($total_cost,2)." will exceed the expense detail line value of Rs.".number_format($approved_amount,2);
            display_error($msg);
            set_focus('tran_unit_cost');
            return false;
    }
    
    return true;
}
          

function display_petty_cash_item_receiving_edit_controls($selected_id)
{ 
    global $Ajax, $Refs;    

    start_table(TABLESTYLE);    
    
    br(2);    

    if($selected_id > 0){        
        $myrow = get_petty_cash_item_receive_item_details($selected_id);

        $_POST['id'] = $myrow["id"];     
        $_POST['stock_id'] = $myrow["stock_id"];        

        $stock_item = get_stock_item_edit_info($myrow["stock_id"]);
        if($stock_item["editable"] == 1){
            $_POST['item_description'] = $myrow["item_description"];  
        }
        else{
           $_POST['item_description'] = $stock_item["description"];  
        }
        
        $_POST['tran_unit_cost'] = $myrow["tran_unit_cost"];        
        $_POST['tran_qty']  = $myrow["tran_qty"];
        $_POST['tran_unit'] = $myrow["tran_unit"];     
        $_POST['location']  = $myrow["location"];
        $_POST['comment']  = $myrow["comment"];
        $_POST['tran_date']  = sql2date($myrow["tran_date"]);
    }
    else{
        
    }
   
    
    hidden('selected_id', $selected_id);
    
    date_cells("Date", "tran_date");
    
    if($selected_id > 0){// Update
        
        
        label_row("Itemcode :", $_POST['stock_id']." - ".$_POST['item_description']);     
        $stock_item = get_stock_item_edit_info($_POST['stock_id']);
        if($stock_item["editable"] == 1){
            text_row("Item Description:", 'item_description', null, 50, 200);
        }
        else{
            hidden('item_description', $stock_item["description"]);
        }
        
        units_list_row("Unit :", 'tran_unit', $_POST['stock_id'], null, false, false); 

        
        hidden('stock_id', $_POST['stock_id']);
        
    }
    else{// New    
        sales_local_items_list_row(_("Itemcode:"),'stock_id', null, false, true);
        $stock_item = get_stock_item_edit_info($_POST['stock_id']);
        if($stock_item["editable"]){
            text_row("Item Description:", 'item_description', null, 50, 200);
        }
        else{
            hidden('item_description', $stock_item["description"]);
        }

        units_list_row("Unit :", 'tran_unit', $_POST['stock_id'], null, false, false); 

    }

        


    amount_row("Unit Cost :", 'tran_unit_cost' /*number_format($display_cost,2)*/);	
    amount_row(_("Quantity :"), 'tran_qty', null, null, null);
    textarea_row("Comment :", 'comment', null, 35, 2);

    end_table(1);
       
    hidden("stype",$_POST["stype"]);
    hidden("strn_no",$_POST["strn_no"]);
    hidden("sd_id",$_POST["sd_id"]);




        
    if($selected_id > 0){        
        submit_center_first('UPDATE_BOQ_ITEM_MATERIAL', _("Update Item"), '', 'default');
        submit_center_last('Cancel_Edit', _("Cancel"), '', 'default');
    }
    else{
        submit_center_first('ADD_BOQ_ITEM_MATERIAL', _("Add Item"), '', 'default');
    }
    
} 
 
function clear_boq_item_material_data()
{
    unset($_POST['boq_material_stock_id']);
    unset($_POST['boq_material_tran_qty']);
    unset($_POST['boq_material_unit_cost']);
}
 
 //---------------------------------------------------------------------------------------------------
 
function handle_process_petty_cash_item_receive($stype, $strn_no, $sd_id, $type)
{
    global $systypes_array;
    
    $batch_id = uniqid();
    $project_id = -1;
    
    if($stype == ST_I_OWE_YOU_BATCH){
        $batch = get_i_owe_you_batch_header_record($strn_no);
        $project_id = $batch['project_id'];
    }else{
        $s_msg = "Unknown source transaction type.";
        display_error($s_msg);
        return;
    }
    
    if(!($project_id > 0)){
        $p_msg = "UNEXPECTED : Unknown project_id.";
        display_error($p_msg);
        return;
    }
    
    if(can_process_petty_cash_item_receiving($stype, $strn_no, $sd_id, $type)){
        
        
        $iou_ex_line = get_i_owe_you_expence_line($sd_id);
        $task_id = $iou_ex_line['task_id'];
        
        $result = get_petty_cash_not_processed_stock_items_by_source($stype, $sd_id);
        
        if(db_num_rows($result) == 0){          
            display_error("All items of this ".$systypes_array[ST_PETTY_CASH_ITEM_RECEIPT]." have been processed already.");
            return;
        }
        
        begin_transaction();
        
        while ($myrow = db_fetch($result)){
                
                if(is_inventory_item($myrow["stock_id"])){
                    $stock_id = $myrow["stock_id"];
                    $conversion_factor = 1;
                    $tran_unit = $myrow["tran_unit"];
                    get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);
                    $tran_qty = $myrow["tran_qty"];
                    $quantity = $tran_qty * $conversion_factor;
                    $tran_unit_cost =$myrow["tran_unit_cost"]; 
                    $base_unit_cost = $tran_unit_cost / $conversion_factor;
                    $tran_date_ = sql2date($myrow["tran_date"]);

                    add_stock_adjustment_item($myrow["trans_no"], $stock_id, $myrow["location"], $tran_date_, 
                                                "", $quantity, $base_unit_cost, "", 
                                                $tran_unit, $tran_qty, $conversion_factor, $type, 
                                                0, 0, $myrow["id"]);
                    
                    $myrow = get_petty_cash_item_receive_item_details($myrow["id"]);
                    $qty = $tran_qty * $conversion_factor;

                    $upcsi_msg = update_petty_cash_stock_item($myrow["id"], $myrow["tran_date"], $myrow["item_description"], $tran_qty, 
                                $myrow['tran_unit_cost'], $myrow["comment"], $tran_unit, $qty, $conversion_factor); 
                    
                    if($upcsi_msg['success'] !== true){
                        display_error_cancel($upcsi_msg['message']);
                        return;
                    }
                }
                
                $dii_details_array = array();

                $qty_ = abs($tran_qty);
                $b['row_id'] = $myrow["id"];
                $b['stock_id'] = $stock_id;
                $b['task_id'] = $task_id;
                $b['requested_qty'] = $qty_;
                $b['high_value_item'] = 0;

                $standard_cost = $tran_unit_cost;
                $b['reference_cost'] = $standard_cost; 
                $b['standard_cost'] = $standard_cost;
                $b['charging_cost'] = $standard_cost;
                $b['total_issued_qty'] = $qty_;
                $b['qty'] = $qty_;

                $dii_details_array[] = $b;

                $trans_no = $myrow["trans_no"];

                $mi_tasks_summary = calculate_task_remaining_totals($dii_details_array);
                $created_by = $_SESSION['wa_current_user']->user;

                $mtrec_msg = remove_costs_from_tasks($type, $trans_no, $mi_tasks_summary, $created_by);
                if ($mtrec_msg['success'] !== true) {
                    cancel_transaction();
                    display_error($mtrec_msg['message']);
                    return;
                }
                
                $upcsip = update_petty_cash_stock_item_processed($myrow['id'], $batch_id);
                if ($upcsip['success'] !== true) {
                    cancel_transaction();
                    display_error($upcsip['message']);
                    return;
                }
                
        }
        
        commit_transaction();
                    
        display_notification("All items of this ".$systypes_array[ST_PETTY_CASH_ITEM_RECEIPT]." have been processed."); 
                   
    }
}
 
function handle_new_petty_cash_item_receive(&$selected_id, $type)
{
    if(can_commit_petty_cash_item_receiving_item($selected_id, $_POST["stype"], $_POST["strn_no"], $_POST["sd_id"])){
        
        begin_transaction();
        
        $exp_line = get_i_owe_you_expence_line($_POST["sd_id"]);
        $exp_header = get_i_owe_you_batch_header_record($exp_line['iou_batch_no']);
        
        $conversion_factor = 1;
        $tran_unit = $_POST["tran_unit"];
        $stock_id = $_POST["stock_id"];
        get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);
        $tran_qty = input_num('tran_qty');
        $qty = $tran_qty * $conversion_factor;
        
        $trans_no = get_next_trans_no($type);
        add_petty_cash_stock_item($type, $trans_no, 
                                $_POST["stype"], $_POST["strn_no"], $_POST["sd_id"],
                                $_POST["location"], date2sql($_POST["tran_date"]), 
                                $_POST["stock_id"], $_POST["item_description"], 
                                $_POST["tran_unit"], input_num('tran_qty'), 
                                input_num('tran_unit_cost'), $_POST["comment"],
                                $qty, $conversion_factor,
                                $exp_header['project_id'], $exp_line['task_id']);
                
        commit_transaction();

        $selected_id = -1;
                   
    }
}

function handle_update_petty_cash_item_receive(&$selected_id)
{
    if(can_commit_petty_cash_item_receiving_item($selected_id, $_POST["stype"], $_POST["strn_no"], $_POST["sd_id"])){
        
        begin_transaction();
        
        $myrow = get_petty_cash_item_receive_item_details($selected_id);
        $tran_unit = $_POST['tran_unit'];
        $conversion_factor = 1;
        get_convertion_factor2($myrow['stock_id'], $tran_unit, $conversion_factor);
        $tran_qty = input_num('tran_qty');
        $qty = $tran_qty * $conversion_factor;
        
        $uboqm = update_petty_cash_stock_item($selected_id, date2sql($_POST["tran_date"]), $_POST["item_description"], $tran_qty, 
                                input_num('tran_unit_cost'), $_POST["comment"], $tran_unit, $qty, $conversion_factor); 
        
        commit_transaction();
        
        if($uboqm['success'] === true){
            commit_transaction();
            clear_boq_item_material_data();
//            $Mode = 'RESET';
            $selected_id = -1;
            
            display_notification("Selected BOQ Item Material has been updated");
        }
        else{
            cancel_transaction();
        } 
    }   
}
 

//--------------------------------------------------------------------------------------------------

function handle_delete_petty_cash_stock_item(&$selected_id, $delete_petty_cash_item_id){
    
    begin_transaction();
    
    delete_petty_cash_stock_item($delete_petty_cash_item_id);
    
    if(db_num_affected_rows() != 1){
        cancel_transaction();
    }
    else{
        commit_transaction();
        $selected_id = -1;
        display_notification(_('Selected item has been deleted'));
    }
}
//------------------------------------------------------------------------------------------



//if ($Mode == 'RESET')
//{
//    $selected_id = -1;
////    $sav = get_post('show_inactive');
////    unset($_POST);
////    $_POST['show_inactive'] = $sav;
//}
//-------------------------------------------------------------------------------------------

if (isset($_POST['_selected_id_update']) )
{
    $selected_id = $_POST['selected_id'];
    $Ajax->activate('_page_body');
}




