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

//page(_($help_context = "Requisition Alocations"));

//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/purchase_requisitions_db.inc");
include_once($path_to_root . "/purchasing/includes/db/purchase_indents_db.inc");
include_once($path_to_root . "/inventory/includes/db/alternate_units_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.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 = "Purchase Indents Entry"), 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."));
//	}
//}

//$new_record_selection = false;
//if(strlen($selected_id) > 6){
//    $new_record_selection = true;
//}

//if(substr($selected_id, 0, 14) == "UpdatePrPoLine"){
//    $selected_id = substr($selected_id, 14);
//    $_POST["update_type"] = "update_pr_po_line";
//}
//
//if(substr($selected_id, 0, 7) == "NewLine"){
//    $selected_id = substr($selected_id, 7);
//    $_POST["update_type"] =  "new_line";
//}
//
//if(substr($selected_id, 0, 6) == "Delete"){
//    $selected_id = substr($selected_id, 6);
//    $_POST["update_type"] =  "delete_line";
//}

function validate_purchase_indent($supplier,$supplier_name,$supp_address,$location,$new_location,$delivery_required_date,$comment)
{
  
    
    
    if (!is_date($delivery_required_date)) 
    {
            display_error(_("The entered date for the purchase indent is invalid."));
            set_focus('delivery_required_date');
            return false;
    } 
    if ($supplier != null)
    {
        if($supplier_name != null)
        {
            display_error(_("Please select a supplier or add new supplier name."));
            set_focus('new_supplier_name');
            return false;
        }
        
    }
    
    if ($supplier_name == null && $supplier == null)
    {
        
        display_error(_("Please select a supplier or add new supplier name."));
	set_focus('new_supplier_name');
	return false;
    }
    
    if ($location == null && $new_location == null)
    {
        
        display_error(_("Please select a location or add new location."));
	set_focus('new_supplier_name');
	return false;
    }
    
      if ($location != null)
    {
        if($new_location != null)
        {
            display_error(_("Please select a location or add new locatio name."));
            set_focus('stock_location');
            return false;
        }
        
    }
    
    
    
//    $res_1 = validate_purchase_indent_header($supplier,$supplier_name,$supp_address,$location,$new_location,$delivery_required_date);
//    if($res_1 == true)
//    {
    $ind_result = get_open_requisition_details_for_indents();
    $updates_count_1 = 0;
    
    while ($a_row = db_fetch($ind_result))
    {

        if((isset($_POST["selected_".$a_row["pr_line_id"]])) &&
                ($_POST["selected_".$a_row["pr_line_id"]] == true))
        {
            
            $pr_line_id = $a_row["pr_line_id"];
            
            $res =validate_purchase_indent_details($_POST["tran_unit_".$a_row["pr_line_id"]], input_num("order_unit_qty_".$a_row["pr_line_id"]), 
                                                   $_POST["item_description_$pr_line_id"], $a_row["editable"], $pr_line_id);
            
            if($res == true)
            {
                $updates_count_1++;
            }
            else{
                return false;
            }
            

        }
   
    }
  
    if($updates_count_1 == 0)
    {
        display_error(_("There are no lines with quantities selected."));
        return false;
    }
    
    return true;
    
}

function validate_purchase_indent_details($tran_unit_,$order_unit_qty_, $item_description, $editable, $pr_line_id) {
    if ($editable == 1) {
	if (! (strlen($item_description) > 0)) {
            display_error(_("Record #$pr_line_id item description cannot empty."));
            set_focus('item_description_');
            return false;
	} 
    }
    
    if (!($order_unit_qty_ > 0)) {
        display_error(_("Record #$pr_line_id Order quantity entered is negative or invalid."));
        set_focus('order_unit_qty_');
        return false;
    }
    
    if ($order_unit_qty_ == 0) {
        display_error(_("Record #$pr_line_id Order quantity can not be zero."));
        set_focus('order_unit_qty_');
        return false;
    }
        
    if ($tran_unit_ == null) {
        display_error(_("Record #$pr_line_id Please select a unit."));
        set_focus('tran_unit_');
        return false;
    } 
    
        return true;
}





function create_indent($close = false, $close_only = false)
{
    $supplier = $_POST['supplier_id'];
    $supplier_name= $_POST['new_supplier_name'];
    $supp_address = $_POST['new_supplier_addr'];
    $location = $_POST['stock_location'];
    $new_location = $_POST['new_location_addr'];
    $comment = $_POST['comment'];
    $delivery_required_date = $_POST['delivery_required_date'];
    
    if(!$close_only){
        if(!validate_purchase_indent($supplier,$supplier_name,$supp_address,$location,$new_location,$delivery_required_date,$comment)){
            return;
        }
        

        $indent_id = create_prchase_indent_header($supplier, $supplier_name, $supp_address,
                                                    $location, $new_location, date2sql($delivery_required_date),
                                                    $comment);
        
        $ind_result = get_open_requisition_details_for_indents();


        while ($a_row = db_fetch($ind_result))
        {

            if((isset($_POST["selected_".$a_row["pr_line_id"]])) && ($_POST["selected_".$a_row["pr_line_id"]] == true))
            {
//                $any_selected = true;
                $tran_unit = $_POST['tran_unit_'.$a_row["pr_line_id"]];
                $tran_qty = $_POST['order_unit_qty_'.$a_row["pr_line_id"]];
                $line_comment = $_POST['line_comment'.$a_row["pr_line_id"]];
                $item_description = $_POST['item_description_'.$a_row["pr_line_id"]];
                
                $item_code = $a_row["item_code"];
                //$tran_unit = $a_row['order_unit'];
                get_convertion_factor2($item_code, $tran_unit, $convesion_factor);

                create_purchase_indent_details($indent_id, $a_row["pr_line_id"], $tran_unit,
                                                $tran_qty, $line_comment, $convesion_factor, 
                                                $close, $close_only, $item_description);

            }
   
        }
   
        
    }
    else
    {
        $ind_result_close = get_open_requisition_details_for_indents();
        while ($a_row = db_fetch($ind_result_close))
        {

            if((isset($_POST["selected_".$a_row["pr_line_id"]])) &&
                    ($_POST["selected_".$a_row["pr_line_id"]] == true))
            {

                close_purchase_requisition_lines_for_indents($a_row["pr_line_id"]);

            }
   
        }
        
    }

    if($close_only == true && $close == false){
        display_notification("Selected PR lines if any have been closed for indents");
    }
    elseif($close_only == false && $close == true){
        display_notification("Indent No.".$indent_id."created and the PR lines have been closed.");
        $_POST['new_indent_no'] = $indent_id;
    }
    else{
        display_notification("Indent No ".$indent_id." has been created.");
//        $l = print_document_link($indent_id, _("&Print this Material Requisition"), true, ST_PURCH_INDENTS);
//        display_note($l, 0, 0);
        
        $_POST['new_indent_no'] = $indent_id;
    }

}

function display_purchase_requisition_indents_filters() {
    start_table(TABLESTYLE_NOBORDER);
        date_cells('From Date:', 'from_date', 'from date', null, 0, -2, 0, null, true);
        date_cells('To Date:', 'to_date', 'to date', null, 0, 0, 0, null, true);
        
        submit_cells('Search', _("Search"),'',_('Search'), 'default');
    end_table(2);
}

function display_open_requisition_details_for_indents($from_date_, $to_date_) {
    $from_date = date2sql($from_date_);
    $to_date = date2sql($to_date_);
    
    if(isset($_POST['new_indent_no'])){
        $l = print_document_link($_POST['new_indent_no'], _("&Print indent No. ".$_POST['new_indent_no']), true, ST_PURCH_INDENTS);
        display_note($l, 0, 0);
        br();
        unset($_POST['new_indent_no']);
    }
        
    $result = get_open_requisition_details_for_indents($from_date, $to_date);

    start_table(TABLESTYLE, "width=99%");

    $th = array(_("Id"), _("PR#"), _("Project"), _("Location"), _("Item Code"), _("Item Description"), _("Qty"), _("Units"), _("Estd. Price"), 
                _("Required Date"), _("Unit"), _("Qty"),("Comment"), "");

    table_header($th);
    $k = 0;
    $previuos_stock_id = "";
    $previuos_pr_line_id = 0;

    while ($myrow = db_fetch($result)) 
    {
        if($previuos_stock_id == $myrow["item_code"] && $previuos_pr_line_id == $myrow["pr_line_id"]){
            $k++;
        }

        $previuos_stock_id = $myrow["item_code"];
        $previuos_pr_line_id = $myrow["pr_line_id"];


        alt_table_row_color($k);
    
        $pr_line_id = $myrow["pr_line_id"];
        label_cell($pr_line_id, "align=center");
        label_cell(get_supplier_trans_view_str(ST_PURCH_REQ,$myrow["pr_no"], $myrow["pr_no"]),"align=right");
        label_cell($myrow["project_description"]);
        label_cell($myrow["location"]);
        label_cell($myrow["item_code"]);
        
        
        if ($myrow['editable'] == 1) {
            if (! isset($_POST["item_description_$pr_line_id"]) || ! (strlen($_POST["item_description_$pr_line_id"]) > 0)) {
                if (strlen($myrow['item_pr_description']) > 0) {
                    $_POST["item_description_$pr_line_id"] = $myrow['item_pr_description'];
                } else {
                    $_POST["item_description_$pr_line_id"] = $myrow['sm_item_description'];
                }
            }
            
            text_cells(null, "item_description_$pr_line_id", null, 30, 500);
        } else {
            label_cell($myrow["description"]);
            hidden("item_description_$pr_line_id", '');
        }
        
        label_cell(get_supplier_trans_view_str(ST_PR_DETAIL_INDENTS,$myrow["pr_line_id"], number_format($myrow["requested_unit_qty"],2)),"align=right");

        label_cell($myrow["requested_unit"]);
        amount_cell($myrow["estimate_price"]);
        label_cell(sql2date($myrow["required_date"]), "align=center");

        $dec = 2;    
        units_list_cells(null, 'tran_unit_'.$myrow["pr_line_id"], $myrow["item_code"], null, false, true);

        $item_code = $myrow["item_code"];
        $tran_unit =  $_POST['tran_unit_'.$myrow["pr_line_id"]];
        if(list_updated('tran_unit_'.$myrow["pr_line_id"])){
            get_convertion_factor2($item_code, $tran_unit, $convesion_factor);
            $order_unit_qty = $myrow["quantity"] / $convesion_factor;
        }
        else{
            if(isset($_POST['order_unit_qty_'.$myrow["pr_line_id"]])){
                $order_unit_qty = $_POST['order_unit_qty_'.$myrow["pr_line_id"]];
            }
            else{
                $order_unit_qty = $myrow["requested_unit_qty"];
            }
        }

        $_POST['order_unit_qty_'.$myrow["pr_line_id"]] = $order_unit_qty;
        qty_cells(null, 'order_unit_qty_'.$myrow["pr_line_id"], number_format2($order_unit_qty, $dec), '', null, $dec);
        text_cells(null, 'line_comment'.$myrow["pr_line_id"], null, 30, 100);
        if(isset($_POST['selected_'.$myrow['pr_line_id']])){
            $selected = 1;
        }
        else{
            $selected = 0;
        }
        check_cells(null, 'selected_'.$myrow['pr_line_id'], $selected, false);

//        label_cell($myrow["pr_line_id"]);
        
        end_row();
    }
    end_table(1);
}

//if(isset($_POST['Delete'.$selected_id])){
//    delete_requisition_allocation_line($selected_id);
//}

//if(isset($_POST['close_indents'])){
//    close_indents($selected_id);
//}
//-----------------------------------------------------------------------------------

//if ($Mode == 'RESET')
//{
//	$selected_id = -1;
//	$sav = get_post('show_inactive');
//	unset($_POST);
//}
//-----------------------------------------------------------------------------------
if (isset($_POST['close_pr_lines']))
{
    create_indent(false, true);

}

if (isset($_POST['Create_indent']))
{
    create_indent();
        
//    display_error(_("No records were updated."));
   
}


if (isset($_POST['Create_indent_close']))
{
    create_indent(true);
        
//    display_error(_("No records were updated."));
   
}


start_form();


$Ajax->activate('pr_indent_details');

div_start('pr_indent_details');

    display_purchase_requisition_indents_filters();
    display_open_requisition_details_for_indents($_POST['from_date'], $_POST['to_date']);
//hidden('update_type',get_post("update_type"));

br();

start_table();
    //submit_center('close_pr_lines', _("Close Selected Indents"), '', 'default');
    submit('close_pr_lines', _("Close Lines"), true, '', 'default');
end_table(2);


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

//start_table(TABLESTYLE2);
start_outer_table(TABLESTYLE2, "width=60%"); // outer table

if ($selected_id != -1) 
{
    $myrow = get_requisition_details(get_post('update_type'), $selected_id);

    $_POST['pr_line_id']  = $myrow["pr_line_id"];
    $_POST['project_description']  = $myrow["project_description"];
    $_POST['task_description']  = $myrow["task_description"];
    $_POST['item_code']  = $myrow["item_code"];
    $_POST['requested_quantity']  = $myrow["requested_quantity"];
    $_POST['base_unit']  = $myrow["base_unit"];
    $_POST['estimate_price']  = $myrow["estimate_price"];
    $_POST['description']  = $myrow["description"];
    $_POST['line_comment']  = $myrow["line_comment"];
    $_POST['requested_unit']  = $myrow["requested_unit"];
    $_POST['requested_unit_qty']  = $myrow["requested_unit_qty"];
    $_POST['required_date']  = $myrow["required_date"];
    $_POST['order_line_required_date']  = $myrow["order_line_required_date"];
    $_POST['req_unit_conversion_factor']  = $myrow["req_unit_conversion_factor"];
    $_POST['requested_quantity'] = $myrow['requested_quantity'];
    $_POST['quantity_ordered'] = $myrow['quantity_ordered'];

    if(get_post("update_type") == "update_pr_po_line" && !list_updated('supplier_id')){
        $_POST['supplier_id']  = $myrow["supplier_id"];
    }
    $_POST['order_quantity']  = $myrow["order_quantity"];

    if(!isset($_POST['order_unit'])){
        $_POST['order_unit']  = $myrow["order_unit"];
    }
    $_POST['order_unit_qty']  = $myrow["order_unit_qty"];
    $_POST['order_unit_price']  = $myrow["order_unit_price"];    
    $_POST['row_state']  = $myrow["row_state"];
	
    hidden('pr_line_id', $_POST['pr_line_id']);
    hidden('row_state', $_POST['row_state']);
    hidden('selected_id', $selected_id);
} 

$dec = 0;
$units = '';
$res = get_item_edit_info(get_post('item_code'));
if (isset($res["units"]) && strlen($res["units"]) > 0) {
    $dec =  $res["decimals"] == '' ? 0 : $res["decimals"];
    $units = $res["units"] == '' ? _('kits') : $res["units"];
}

table_section(1,"50%");


supplier_list_row(_("Supplier : "), 'supplier_id', get_post('supplier_id', 0), "Select a supplier", false);
textarea_row(_("New Supplier Name:"), 'new_supplier_name', null, 40, 2);
textarea_row(_("New Supplier Address:"), 'new_supplier_addr', null, 40, 2);



table_section(2, "50%");


locations_list_row(_("Location:"), 'stock_location', null);
textarea_row(_("New Location Address:"), 'new_location_addr', null, 40, 2);
date_row("Delivery Required By", 'delivery_required_date');
textarea_row(_("Comment:"), 'comment', null, 40, 2);


end_outer_table(1); // outer table
div_end();

br();
submit_center_first('Create_indent', _("Create Indent"), '', 'default');
submit('Create_indent_close', _("Create Indent and Close Lines"), true, '', 'default');


end_form(2);

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

end_page();

?>
