<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PURCHASEORDER_GENERATE';
$path_to_root = "..";
include($path_to_root . "/includes/session.inc");
add_access_extensions();

//page(_($help_context = "Requisitions"));

//include_once($path_to_root . "/requisitions/includes/modules_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/ui_lists.inc");
include_once($path_to_root . "/purchasing/includes/db/generate_po_db.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/inventory/includes/db/alternate_units_db.inc");

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page(_($help_context = "Generate POs"), false, false, "", $js);

simple_page_mode(true);
//-----------------------------------------------------------------------------------
if(isset($_GET['po'])) {
	if($_GET['po'] == 'yes') {
		if (generate_po())
			display_notification(_("Purchase orders has been generated."));
		else
			display_error(_("Purchase orders generation failed."));
	}
}

if (isset($_GET['AddedID'])) 
{
	$order_no = $_GET['AddedID'];
	$trans_type = ST_PURCHORDER;	

	display_notification_centered(_("Purchase Order ").$order_no." has been entered");

	display_note(get_trans_view_str($trans_type, $order_no, _("&View this order")), 0, 1);

	display_note(print_document_link($order_no, _("&Print This Order"), true, $trans_type), 0, 1);

	display_note(print_document_link($order_no, _("&Email This Order"), true, $trans_type, false, "printlink", "", 1));

	hyperlink_params($path_to_root . "/purchasing/po_receive_items.php", _("&Receive Items on this Purchase Order"), "PONumber=$order_no");

	hyperlink_params($_SERVER['PHP_SELF'], _("Generate &Another Purchase Order"), "NewOrder=yes");
	
	hyperlink_no_params($path_to_root."/purchasing/inquiry/po_search.php", _("Select An &Outstanding Purchase Order"));
	
	display_footer_exit();	
        
        
}


if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') 
{

	//initialise no input errors assumed initially before we test
	$input_error = 0;

	if (!check_num('order_quantity',0))
	{
		display_error(_("Order quantity entered is negative or invalid."));
		set_focus('qty');
		return false;
	}
        
        if (strlen($_POST['order_quantity']) == 0) 
	{
		$input_error = 1;
		display_error(_("Order quantity can not be zero."));
		set_focus('quantity');
	}
        
	if (!check_num('order_price',0))
	{
		display_error(_("Order price entered is negative or invalid."));
		set_focus('qty');
		return false;
	}        

	if (strlen($_POST['order_price']) == 0) 
	{
		$input_error = 1;
		display_error(_("Order price can not be zero."));
		set_focus('price');
	}

	if ($input_error != 1) 
	{
            if ($selected_id != -1) 
            {
                    update_requisition_line($selected_id, $_POST['supplier_id'], $_POST['order_quantity'], 
                            input_num('order_price'));
                            display_notification(_('Selected requisition details has been updated.'));
            } 
    	
		$Mode = 'RESET';
	}
} 

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

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

function display_to_be_generated_po_details($project_id, $supplier_id, $po_user_id, &$location, &$required_date)
{
    
    $po_lines = build_po_lines($project_id, $supplier_id, $po_user_id);
    
    start_table(TABLESTYLE, "width=80%");

    $th = array(_("Project"),_("Location"),_("Item Code"),_("Item Description"),_("Units"), _("Quantity"),
                _("Order Price"), _("Dicount"), _("Required Date"), "Job", _("Req. No."));

    table_header($th);
    $k = 0;
    foreach ($po_lines as $po_line)
    {
            alt_table_row_color($k);	

            label_cell($po_line["project_description"]);
            label_cell($po_line["location_name"]);
            label_cell($po_line["item_code"]);
            label_cell($po_line["description"]);
            label_cell($po_line["order_unit_name"]);
            amount_cell($po_line["order_unit_qty"]);
            amount_cell($po_line["order_unit_price"]);
            amount_cell($po_line["order_unit_price_discount"]);
            label_cell(sql2date($po_line["required_date"]), "align=center");
            label_cell($po_line["project_site_name"]);
            
            $pr_ids_string = get_pr_ids_string($po_line["pr_ids"]);
            label_cell(get_supplier_trans_view_str(ST_PURCH_REQ,$pr_ids_string, $pr_ids_string),"align=center");

            //edit_button_cell("Edit".$myrow['pr_line_id'], _("Edit"));

            end_row();
            
            $location = $po_line["location"];
            if($required_date > $po_line["required_date"]){
                $required_date = $po_line["required_date"];
            }
    }
    end_table(1);
    
    
}


function add_to_po_lines(&$po_lines, $myrow)
{

//        foreach ($po_lines as &$po_line) {
//            if(isset($po_line["location"]) && $po_line["location"] == $myrow["line_loc_code"]){ 
//                if(isset($po_line["item_code"]) && $po_line["item_code"] == $myrow["item_code"]){
//                    if(isset($po_line["description"]) && $po_line["description"] == $myrow["pr_po_item_description"]){
//                        if(isset($po_line["order_unit"]) && $po_line["order_unit"] == $myrow["order_unit"]){
//                            if(isset($po_line["order_unit_price"]) && $po_line["order_unit_price"] == $myrow["order_unit_price"]){
//                                if(isset($po_line["order_unit_price_discount"]) && $po_line["order_unit_price_discount"] == $myrow["order_unit_price_discount"]){
//                                    if(isset($po_line["project_site_name"]) && $po_line["project_site_name"] == $myrow["project_site_name"])
//                                    {
//
//                                        $po_line['order_unit_qty'] += $myrow['order_unit_qty'];
//                                        $po_line['order_quantity'] += $myrow['order_quantity'];                                         
//
//                                        $x = "";
//                                        if(isset($po_line['pr_ids'])){
//                                            $x = $po_line['pr_ids'];
//                                        }
//                                        $x[] = $myrow['pr_no'];
//                                        $po_line['pr_ids'] = $x;
//
//                                        $y = "";
//                                        if(isset($po_line['pr_po_lines'])){
//                                            $y = $po_line['pr_po_lines'];
//                                        }
//                                        $y[] = array("line_id" => $myrow['pr_po_line_id'], "row_state" => $myrow['pr_po_row_state']);
//                                        $po_line['pr_po_lines'] = $y;
//
//                                        return;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }        
//        }
            
        $pr_nos[] = $myrow['pr_no'];
        $pr_po_line[] = array("line_id" => $myrow['pr_po_line_id'], "row_state" => $myrow['pr_po_row_state']);
        
        if(isset($myrow['pr_po_item_description']) && strlen($myrow['pr_po_item_description']) > 0){
            $item_description = $myrow['pr_po_item_description'];
        }
        else{
            $item_description = $myrow['description'];
        }
        $new_po_line = array("pr_id" => $myrow['pr_no'],
                        "location" => $myrow['line_loc_code'],
                        "location_name" => $myrow['line_location_name'],
                        "created_on" => $myrow['created_on'],
                        "item_code" => $myrow['item_code'],
                        "description" => $item_description,
                        "pr_line_id" => $myrow['pr_line_id'],
                        "line_comment" => $myrow['line_comment'],
                        "quantity" => $myrow['quantity'],
                        "units" => $myrow['units'],
                        "supplier_id" => $myrow['supplier_id'],
                        "required_date" => $myrow['required_date'],
                        "order_unit_qty" => $myrow['order_unit_qty'],
                        "order_unit_price" => $myrow['order_unit_price'],
                        "order_unit_price_discount" => $myrow['order_unit_price_discount'],
                        "order_unit_conversion_factor" => $myrow['order_unit_conversion_factor'],
                        "supp_name" => $myrow['supp_name'],
                        "pr_ids" => $pr_nos,
                        "pr_po_lines" => $pr_po_line, 
                        "order_unit" => $myrow['order_unit'],
                        "order_quantity" => $myrow['order_quantity'], 
                        "order_price" => $myrow['order_price'], 
                        "order_unit_name" => $myrow['order_unit_name'],
                        "project_id" => $myrow['project_id'], 
                        "project_description" => $myrow['project_description'], 
                        "project_site_id" => $myrow['project_site_id'],
                        "minimum_price" => $myrow['minimum_price'], 
                        "minimum_price_discount" => $myrow['minimum_price_discount'], 
                        "min_price_supp_id" => $myrow['min_price_supp_id'],
                        "project_site_name" => $myrow['project_site_name']
                
                );
            
        $po_lines[] = $new_po_line;

}
//---------------------------------------------------------------------------------------------------
function build_po_lines($project_id, $supplier_id, $po_user_id)
{
    $po_lines = array();
    
    $result = get_pr_allocation_lines_for_po_generation($project_id, $supplier_id, $po_user_id);
    
    while ($myrow = db_fetch($result)) 
    {       
        add_to_po_lines($po_lines, $myrow);
    }
    return $po_lines;
}
//---------------------------------------------------------------------------------------------------
function get_pr_ids_string($pr_ids)
{
    $pr_ids_string = "";
    $pr_ids = array_unique($pr_ids);
    foreach ($pr_ids as $pr_id)
    {
        $pr_ids_string .= $pr_id." ";
    }
    $pr_ids_string = trim($pr_ids_string);
    return $pr_ids_string;
}


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


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

function handle_commit_order($cart)
{

            $apo_msg = add_po($cart);
            if($apo_msg['success'] != true){
                    cancel_transaction();
                    display_error($apo_msg['message']);
                    return;
            }
            else{
                    $order_no = $apo_msg['tran_no'];
            }


            if ($cart->trans_type == ST_PURCHORDER) {
                    unset($_SESSION['PO']);
            meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no");
    }

}
//-----------------------------------------------------------------------------------

                
function generate_selected_po($prefix, $po_user_id)
{
    global $path_to_root;
    
    include_once($path_to_root . "/purchasing/includes/validate_po.inc");
//    $prefix = $project_row['project_id']."|".$supp_row['supplier_id'];
    
    $tran_type = ST_PURCHORDER;
    $order_date = $_POST[$prefix.'_po_date'];
    $po_location = $_POST[$prefix.'_po_location'];
    
    $sep_pos = strpos($prefix, "|");
    $project_id = substr($prefix, 0, $sep_pos);
    $supplier_id = substr($prefix, $sep_pos + 1);


    build_new_po_header($tran_type, 0, $supplier_id, $order_date, $po_location, $project_id);
    
    $cart = $_SESSION['PO'];
    
    $po_lines_array = build_po_lines($project_id, $supplier_id, $po_user_id);

    foreach ($po_lines_array as $array) 
    {
            //label_cell($myrow["supp_name"]);
            $stock_id = $array["item_code"];
            $description = $array["description"];
            $project_site_id = $array["project_site_id"];
            $order_quantity = $array["order_quantity"];
            $order_price = $array["order_price"];
            $req_del_date = sql2date($array["required_date"]);
            $pr_po_lines = $array["pr_po_lines"];
            $order_unit = ($array["order_unit"]);
            $order_unit_qty = ($array["order_unit_qty"]);
            $order_unit_price = ($array["order_unit_price"]);
            $order_unit_price_discount = ($array["order_unit_price_discount"]);
            $conv_factor = ($array["order_unit_conversion_factor"]);
            $minimum_price = $array["minimum_price"];
            $minimum_price_discount = $array["minimum_price_discount"];
            $min_price_supp_id = ($array["min_price_supp_id"]);
            $tax_group_id = $cart->tax_group_id;
            $tax_included = $cart->tax_included;
            
            
            $vpld_msg = validate_po_line_data($stock_id, $project_site_id, $order_quantity, $order_price, $req_del_date);
            if($vpld_msg["success"] !== true){
                return $vpld_msg;
            }
            
            add_built_po_line_to_cart($cart, $stock_id, $description, $order_quantity, $order_price,$req_del_date, $pr_po_lines, $order_unit, 
                                $order_unit_qty, $conv_factor, $minimum_price, $minimum_price_discount, $min_price_supp_id, 
                                $order_unit_price, $order_unit_price_discount, $project_site_id, $tax_group_id, $tax_included);
            //$cart->line_items[$cart->lines_on_order - 1]->pr_line_ids = $array['pr_line_ids'];
    
    }
    
    $ccp_msg = can_commit_po($cart);
    if($ccp_msg['success'] !== true){
            return $ccp_msg;
    }
//    return;
    begin_transaction();
    $cart->taxes = $cart->get_taxes(0);
    $apo_msg = add_po($cart);
    if($apo_msg['success'] !== true){
            cancel_transaction();
            return array("success" => false, "message" => $apo_msg['message']);
    }
    else{
            $order_no = $apo_msg['tran_no'];
    }
    if($order_no <= 0){
        cancel_transaction();
        return array("success" => false, "message" => "Could not generate the selected PO.");
    }
    else{
        $upl_msg = update_po_source_records($cart->line_items);
        if($upl_msg['success'] === true){
            commit_transaction();
        }
        else{
            cancel_transaction();
        }
    }

    unset($_SESSION['PO']);
    
    return array("success" => true, "tran_no" => $order_no,"message" => "");
    
    //meta_forward($_SERVER['PHP_SELF'], "AddedID=$order_no");

}
//-----------------------------------------------------------------------------------


if ($selected_id != -1) 
{
    if ($Mode == 'Edit') {
        //editing an existing status code

        $gspo_msg = generate_selected_po($selected_id, $_POST['po_user_id']);
        $_POST['selected_id'] = -1;
        if($gspo_msg['success'] === true){
            display_notification("PO ".$gspo_msg["tran_no"]." generated.");
        }
        else{
            display_error($gspo_msg["message"]);
        }
    }

   
} 




start_form();

$po_users_array = array();

$users_q = get_users_for_po_generation();
while ($po_user_row = db_fetch($users_q)){
    $po_users_array[$po_user_row['po_user_id']] = $po_user_row['po_user_name'];
}

if(!isset($_POST['po_user_id'])){
    $_POST['po_user_id'] = $_SESSION['wa_current_user']->user;
}
custom_values_list_row("Purchasing Officer :", "po_user_id", $po_users_array, null, "", true);

br(3);

$result_p = get_projects_for_po_generation($_POST['po_user_id']);
while ($project_row = db_fetch($result_p)) 
{
//    display_heading($project_row["project_description"]);
//    project_list_row("Project: ", 'project_'.$project_row['project_id'], $project_row['project_id'], "Select a Project");
    $project_text = "Project: ".$project_row['project_description']; //." ".$project_row['project_id'];
    display_heading($project_text);
    hidden('project_'.$project_row['project_id'], $project_row['project_id']);
    br(1);
    
    $result_s = get_suppliers_for_po_generation($project_row['project_id'], $_POST['po_user_id']);
    while ($supp_row = db_fetch($result_s)) 
    {
        $ppd_required_date = INFINITE_END_DATE;
        display_heading2($supp_row["supp_name"]);        
        
        display_to_be_generated_po_details($project_row['project_id'], $supp_row["supplier_id"], $_POST['po_user_id'], $ppd_location, $ppd_required_date);
        
        $prefix = $project_row['project_id']."|".$supp_row['supplier_id'];
        start_outer_table(TABLESTYLE2, "width=50%"); // outer table
        table_section(1, "50%");
        $_POST[$prefix.'_po_location'] = $ppd_location;
        locations_list_row(_("Requesting Location:"), $prefix.'_po_location', null, "Select a Location", false);

        table_section(2, "45%");
//        $_POST[$prefix.'_po_date'] = sql2date($ppd_required_date);
        $_POST[$prefix.'_po_date'] = Today();
        date_row(_("PO Date:"), $prefix.'_po_date', null);
        
        table_section(3, "5%");
        select_button_cell("Edit".$prefix, _("Select1"), _("Generate Above PO"));

        end_outer_table(1); // outer table

        

        br(2);
    }
}

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

end_form();

//echo "<div align='center'><a href='requisition_allocations.php?po=yes'>"._("Generate Purchase Orders")."</a></div>\n";
//------------------------------------------------------------------------------------

end_page();

?>
