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

$page_security = 'SA_PROJECT_SALES_ORDER';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/approval_functions.inc");
include_once($path_to_root . "/projects/includes/db/project_payment_application_db.inc"); 
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_items_db.inc"); 
include_once($path_to_root . "/includes/common_functions.inc");
include_once($path_to_root . "/taxes/db/tax_groups_db.inc");
include_once($path_to_root . "/projects/includes/db/project_dispatch_request_db.inc");
include_once($path_to_root . "/projects/includes/db/project_sales_orders_db.inc");
include_once($path_to_root . "/includes/references.inc");


$js = '';
if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}
page(_($help_context = "Project Dispatch Request"));

//------------------------------------------------------------------------------------------------------
simple_page_mode(true);

//$pdr_no = get_session_variable('project_invoice_no'); 
//if(!($pdr_no > 0)){
//    set_session_variable('project_invoice_no', -1);
////    $pdr_no = -1;
//}

 
if (isset($_GET['PDRNo']))
{
    $_POST['PDRNo'] = $_GET['PDRNo'];
    set_session_variable("ST_PROJECT_DISPATCH_REQUEST_dr_no", $_POST['PDRNo']);
}

if (isset($_GET['NewOrder']))
{
    $_POST['PDRNo'] = -1;
    set_session_variable("ST_PROJECT_DISPATCH_REQUEST_dr_no", $_POST['PDRNo']);
}        
        
if (isset($_POST['PDRNo']) && $_POST['PDRNo'] > 0){
    set_session_variable("ST_PROJECT_DISPATCH_REQUEST_dr_no", $_POST['PDRNo']);
}
else{
    if(!isset($_POST['PDRNo'])){
        $_POST['PDRNo'] = -1;
        set_session_variable("ST_PROJECT_DISPATCH_REQUEST_dr_no", $_POST['PDRNo']);
    }
}

$pdr_no = get_session_variable('ST_PROJECT_DISPATCH_REQUEST_dr_no');




if(isset($_GET['PSONo'])){
    $_POST['PSONo'] = $_GET['PSONo'];
    set_session_variable("ST_PROJECT_DISPATCH_REQUEST_pso_no", $_POST['PSONo']);
}

$pso_no = get_session_variable("ST_PROJECT_DISPATCH_REQUEST_pso_no");
if(!($pso_no > 0)){
    $pdr = get_project_dispatch_request_header($pdr_no);
    $pso_no = $pdr['pso_id'];
}

$_POST['PSONo'] = $pso_no;

//if (isset($_GET['Released_ID'])) 
//{
//	//return;
//            
//    $trans_no = $_GET['Released_ID'];
//    $trans_type = ST_PROJECT_INVOICE;
//    $message = get_session_variable('project_invoice_messages');
//    clear_session_variable('project_invoice_messages');
//    
//	display_notification_centered($message);
//        
//	display_note(print_document_link($trans_no, _("&Print this Project Invoice"), true, $trans_type), 0, 0);
//
//	hyperlink_no_params("$path_to_root/projects/project_invoice.php", _("Create another &Project Invoice"));
//
////	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
//
//	display_footer_exit();
//}

function can_process_pdr_lines_pso($pdr_no)
{
    $header_msg = can_process_pdr_header($pdr_no);
    if($header_msg['success'] !== true){      
        return array("success" => false, "focus_to" => '', "message" => $header_msg['message']);
    }
    
    $result = get_project_sales_order_details($_POST['PSONo']);
    
    $pso_lines = 0;
    while($psod_row = db_fetch($result)){
        if((isset($_POST["selected_".$psod_row['id']])) && ($_POST["selected_".$psod_row['id']] == true)){
    
            $line_msg = can_process_selected_line($pdr_no, $psod_row['id']);
            if($line_msg['success'] !== true){
                $set_focus = 'quantity_psod'."_".$psod_row['id'];
                $message = "Project sales order Quantity should be greater than zero.";
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }            
            $pso_lines++;  
        }
        
    }   
      
           if($pso_lines == 0){           
            $message = "No Lines Selected";
            return array("success" => false, "focus_to" => '', "message" => $message);
        }
          
            return array("success" => true, "focus_to" => '', "message" => "");
        
}


function can_process_pdr_header($pdr_no)
{  
    $pdr_header = get_project_dispatch_request_header($pdr_no);
    $header_id = $pdr_header['id'];
      
    $ref_msg = reference_exists($_POST['reference'], ST_PROJECT_DISPATCH_REQUEST, $header_id);
    if($ref_msg)
    {
        $message = ($ref_msg);
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!($_POST['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if($_POST['location'] == '')
    {
        $message = "Please select a Location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if (!($_POST['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!($_POST['branch_code'] > 0))
    {
        $message = "Please select a customer branch.";
        $set_focus = 'branch_code';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }      

    if(!is_date($_POST['tran_date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
        
    return array("success" => true, "message" => "");    
}


function can_process_pdr_line_manual()
{
     if(!isset($_POST['Save_Project_Dispatch_Request_Header']) && (!isset($_POST['Save_PDR_Lines_PSO']))){
//        if(!($_POST['task_id'] > 0))
//        {
//            $message = "Please select a Budget.";
//            $set_focus = 'task_id';
//            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
//        }
        
        if(!($_POST['tran_unit_qty'] > 0))
        {
            $message = "Project manual line Quantity should be greater than zero.";
            $set_focus = 'tran_unit_qty';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
        
     
         return array("success" => true, "focus_to" => '', "message" => "");  
    }
}

function can_process_selected_line($pdr_no, $line_id)
{
    if(!(check_num('quantity_psod'."_".$line_id, 0)))
    {
        $message = "Project sales order Quantity should be greater than zero.";
        $set_focus = 'quantity_psod'."_".$line_id;
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    return array("success" => true, "message" => "");  
    
}


function save_pdr_header(&$pdr_no)
{
    $validate = can_process_pdr_header($pdr_no);   
    
    if($validate["success"] !== true) 
    {          
        if(isset($validate["focus_to"])){
            set_focus($validate["focus_to"]);
        }
        return array("success" => false, "message" => $validate["message"]);
    }
    
      
    $pdr_no = write_project_dispatch_request_header($pdr_no, $_POST['project_id'], $_POST['debtor_no'],
                                                    $_POST['branch_code'], $_POST['reference'], $_POST['tran_date'],
                                                    $_POST['site_id'], $_POST['location'], $_POST['PSONo'],
                                                    $_POST['tax_group_id']);  
                                    
    
    if($pdr_no > 0){
        set_session_variable("ST_PROJECT_DISPATCH_REQUEST_dr_no", $pdr_no);
        return array("success" => true, 'trans_no' => $pdr_no, "message" => "Project dispatch request $pdr_no has been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Project dispatch request.");
    }
}


function save_pdr_detail_manual(&$pdr_no, $selected_id)        
{    
    $conversion_factor = 1;
    
        if($_POST["type"] == 2){

            get_convertion_factor2($_POST['item_id'], $_POST['tran_unit'], $conversion_factor);       
            $quantity = $_POST['tran_unit_qty'] * $conversion_factor;
        }else{
            $quantity = $_POST['tran_unit_qty'] * $conversion_factor;
        }
      

        if($_POST['type'] == 0 || $_POST['type'] == 2){
            $tran_unit = $_POST['tran_unit'];
        }else{
            $boq_item = get_project_boq_item_details($_POST['item_id']);
            $tran_unit = $boq_item['unit'];
        }
        
   
//        $result = get_project_sales_order_details($_POST['PSONo']);
//        
//        while($pso_detail_row = db_fetch($result)){
//            if((isset($_POST["selected_".$pso_detail_row["id"]])) && ($_POST["selected_".$pso_detail_row["id"]] == true))
//                    $pso_detail_id = $pso_detail_row['id'];
//                    
//        }

    write_project_dispatch_request_line($pdr_no, $selected_id, $_POST['type'], get_post('description'), 
                                        get_post('item_id'), $tran_unit, input_num('tran_unit_rate'), input_num('tran_unit_qty'), 
                                        get_post('line_comment'), $_POST['task_id'], $conversion_factor, $quantity, $pso_detail_id = ''); 
           
                                  
    return array("success" => true, 'trans_no' => $pdr_no, "message" => "Manual line successfully saved.");
}


function save_pdr_manual(&$pdr_no, $selected_id)
{
    $header_msg = save_pdr_header($pdr_no);
        if($header_msg["success"] !== true){
            return $header_msg['message'];
        }

    $manual_line_msg = save_pdr_detail_manual($pdr_no, $selected_id);
        if($manual_line_msg['success'] !== true){
            return $manual_line_msg['success'];
        }

    return array("success" => true, 'trans_no' => $pdr_no, "message" => "Manual Project line successfully saved.");

}

function display_pdr_header($pdr_no)
{
    global $Refs;
    
    if($pdr_no>0){
        
        $pdr_header = get_project_dispatch_request_header($pdr_no);
        $_POST['project_id'] = $pdr_header['project_id'];
        $_POST['debtor_no'] = $pdr_header['debtor_no'];
        
        if(!isset($_POST['customer_branch'])){
            $_POST['customer_branch'] = $pdr_header['branch_code'];
        }
        
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $pdr_header['reference'];
        }
        
        if(!isset($_POST['location'])){
            $_POST['location'] = $pdr_header['location'];
        }

        if(!isset($_POST['tran_date'])){
            $_POST['tran_date'] = sql2date($pdr_header['tran_date']);
        }

        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $pdr_header['project_description'];
        }
        
        if(!isset($_POST['site_id'])){
            $_POST['site_id'] = $pdr_header['site_id'];
        }
        

        $_POST['tax_group_id'] = $pdr_header['tax_group_id'];

        if(!isset($_POST['tax_group_name'])){
            $_POST['tax_group_name'] = $pdr_header['tax_group_name'];
        }
        
    }

        
    start_outer_table(TABLESTYLE2, "width=50%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "50%");
        
        if($pdr_no > 0){
            $pd_request = get_project_dispatch_request_header($pdr_no);
            $reference = $pd_request['reference'];            
            text_row("Reference:", 'reference', $reference, null, null);            
        }else{            
            text_row("Reference:", 'reference', $Refs->get_next(ST_PROJECT_DISPATCH_REQUEST), null, null);   
        }
          
        
            if($pdr_no > 0){
                label_row("Project:", $_POST['project_description']);   
                hidden('project_id', $_POST['project_id']);
            }
            else{
                project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true); 
                hidden('PSONo', $_POST['PSONo']);              
            }  
          
            
            $project = get_project($_POST['project_id']);
            $_POST['customer_name'] = $project['customer_name']; 
            $_POST['customer_id'] = $project['customer_id']; 

            label_row("Customer:", $_POST['customer_name']);    
            hidden('debtor_no', $_POST['customer_id']);

            customer_branches_list_row("Branch:", $_POST['customer_id'], 'branch_code', null, false, false, false);        
                               
            date_row("Order Date:", 'tran_date');

        table_section(2, "50%");           

            locations_list_row("Location", 'location', null, 'Select Location', false);

            project_sites_list_row("Job:", "site_id", $_POST['project_id'], null, "Select a job" );
            
            if($pdr_no > 0){
                label_row("Tax Group :", $_POST['tax_group_name']);    
            }
            else{
                tax_groups_list_row("Tax Group :", "tax_group_id", null, "Please select a tax group", true);
            }
            
    end_table(1);

    end_outer_table(1); // outer table

}


function display_pdr_details_manual($pdr_no, $selected_id, &$total_manual = 0)
{  
    global $project_sales_order_item_types;    

    display_heading("Manually Added Lines");
    $result = get_pdr_details_manual($pdr_no);      
                              
    start_table(TABLESTYLE, "width=90%");
    $th = array(_("ID"), _('Type'),_('Details'),
                _('Unit'), "Rate", _("Qty"), "Line Total", _("Comment"),"","");  
                          

    table_header($th);
    $k = 0; //row colour counter
   // $total = 0;
    
    while ($myrow = db_fetch($result)) 
    {
        if($selected_id != $myrow["id"]){
        alt_table_row_color($k);

        label_cell($myrow["id"], "align=center");
             
        label_cell($project_sales_order_item_types[$myrow["type"]]);  
        
        switch ($myrow["type"]) {
            case PSOIT_BOQ_ITEM:
                $boq_item = get_project_boq_item_details($myrow["item_id"]);
                $item_details = $boq_item['code']." - ".$boq_item['description'];
                break;
            case PSOIT_STOCK_ITEM:
                $stock_item = get_stock_item_edit_info($myrow["item_id"]);
                $item_details = $stock_item['stock_id']." - ".$stock_item['description'];
                break;
            case PSOIT_TEXT:
            default:
                $item_details = $myrow["description"];
                break;
        }
        
        label_cell($item_details);         
        label_cell($myrow["unit_name"]);  
        amount_decimal_cell($myrow["tran_unit_rate"]);
        label_cell($myrow["tran_unit_qty"], "align=right"); 

        $line_total = $myrow["tran_unit_rate"] * $myrow["tran_unit_qty"];
        amount_decimal_cell($line_total);
        
        label_cell($myrow["line_comment"]);
        
        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));  

        end_row();        
      
        $total_manual += $line_total;
        }
        else{
            display_pdr_edit_controls_manual($selected_id, $Mode);
        }
    }
        
    if(!($selected_id > 0)){
        display_pdr_edit_controls_manual($selected_id, $Mode);
    }
    
    start_row();
    label_cell("Sub Total", "align=right colspan=6");
    label_cell("<b>".number_format($total_manual, 2)."</b>", "align=right");
    end_row();

    end_table();
}

function display_pdr_edit_controls_manual($selected_id, &$Mode)
{
    global $Ajax, $project_sales_order_item_types;
    
    $Ajax->activate("billing_items");
    
    if ($selected_id > 0)   
    {
        $myrow = get_pdr_detail_record($selected_id); 
        $pdrd_line = get_pdr_detail_line($selected_id, $myrow['type']);
        
        
        $_POST['id'] = $pdrd_line["id"];
        $_POST['type'] = $pdrd_line["type"];
        $_POST['item_id'] = $pdrd_line["item_id"];    
        $_POST['description'] = $pdrd_line["description"];    
        $_POST['tran_unit'] = $pdrd_line["tran_unit"];       
        $_POST['tran_unit_rate'] = $pdrd_line["tran_unit_rate"];       
        $_POST['line_comment'] = $pdrd_line["line_comment"];  
        $_POST['tran_unit_qty'] = $pdrd_line["tran_unit_qty"];  
        $_POST['task_id'] = $pdrd_line["task_id"];       
        
        $_POST['item_description'] = $pdrd_line["item_description"];    
        $_POST['unit_name'] = $pdrd_line["unit_name"];   
        
    }
  

    br();

//    div_start('billing_items');
//    start_table(TABLESTYLE2);
 
    label_cell($selected_id > 0 ? $selected_id : "", "align=center");
    
//    three_value_list_row("Description / BOQ Item :", "type", null, "Comment", 0, "BOQ Item", 1, "Item", 2, true);
    
    if($selected_id > 0){
        label_cell($project_sales_order_item_types[$_POST['type']]);
        hidden('type', $_POST['type']);
    }
    else{
        project_sales_order_item_types_list_cells(null, "type", null, false, true);
    }

    switch ($_POST['type']) {
        case PSOIT_STOCK_ITEM:
            if($selected_id > 0){
                label_cell($_POST['item_id']." - ".$_POST['item_description']);
                hidden('item_id', $_POST['item_id']);
            }
            else{
                echo "<td>";
                echo sales_items_list('item_id', null, "Please select an item", true,
                    'local', array('cells'=>false, 'editable' => false));
                echo "</td>\n";
            }
            units_list_cells(null, 'tran_unit', $_POST['item_id'], null);
            
            break;
                
        case PSOIT_BOQ_ITEM:
//            if($selected_id > 0){
//                $pdr_line = get_pdr_detail_line($selected_id);
//                $boq_item_initial = get_project_boq_item_record($pdr_line['item_id']);
//                $_POST['boq_group_id'] = $boq_item_initial['group_id'];
//            }
//            
//            if(!isset($_POST['boq_group_id'])){
//                $boq_item_initial = get_project_boq_item_record($_POST['item_id']);
//                $boq_group_id = $boq_item_initial['group_id'];
//            }
//            else{
//                $boq_group_id = $_POST['boq_group_id'];
//            }
            
            if($selected_id > 0){
                label_cell($_POST['item_description']);
                hidden('item_id', $_POST['item_id']);
            }
            else{
                echo "<td>";
                echo project_boq_item_groups_list("boq_group_id", get_post('project_id'), null, "Select a BOQ Item Group", true);
                echo group_boq_items_list("item_id", get_post('project_id'), $_POST['boq_group_id'], null, "Select a BOQ Item", true);
                echo "</td>\n";
            }
            
            if($selected_id > 0){
                label_cell($_POST['unit_name']);
//
//                $_POST['tran_unit_rate'] = $pdr_line['tran_unit_rate'];
//                $_POST['tran_unit_qty'] = $pdr_line['tran_unit_qty'];
            }
            else{
                $boq_item = get_project_boq_item_details($_POST['item_id']);
                label_cell($boq_item['unit_name']);

                $_POST['tran_unit_rate'] = $boq_item['rate'];
                $_POST['tran_unit_qty'] = 0;
            }
            
            hidden("description", '');
            break;
        
        case PSOIT_TEXT:
        default:
            if($selected_id > 0){
                label_cell($_POST['description']);
            }
            else{
                text_cells(null, "description", null, 50, 500);
            }
            
            stock_units_list_cells(null, 'tran_unit', null);
            $_POST['item_id'] = -1;
            hidden('item_id', $_POST['item_id']);
            break;
    }
    
//    tasks_list_row("Budget:", 'task_id', $_POST['project_id'], null, _('Select a budget'), false);
    hidden('task_id', 0);
    
    amount_cells(null, 'tran_unit_rate');
    
    amount_cells(null, 'tran_unit_qty');
   
    label_cell("");
    
    text_cells(null, 'line_comment', null, "35", 500);
      
//    end_table(1);
//    div_end();
    if ($selected_id > 0)
	{
        submit_cells('Update_PDR_Line', _("Update"), "colspan=1", _('Save changes'), true);
//		button_cell('Update_PDR_Line', _("Update"), _('Confirm changes'), ICON_UPDATE);
        submit_cells('CancelItemChanges', _("Cancel"), "colspan=1", _('Cancel changes'), true);
//		button_cell('CancelItemChanges', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $selected_id);
 		set_focus('qty');
	}
	else
	{
		submit_cells('Add_PDR_Line', _("Add Item"), "colspan=2",
		    _('Add new item to document'), true);
	}

}


function save_pdr_details_pso($pdr_no)
{
    $result = get_pdr_details_pso($_POST['PSONo'], $pdr_no);  

    while($psod_row = db_fetch($result)){
        if((isset($_POST["selected_".$psod_row['id']])) && ($_POST["selected_".$psod_row['id']] == true)){
            
                $pso_detail_id = $psod_row['id'];
                $type = $psod_row['type'];
                $description = $psod_row['description'];
                $item_id = $psod_row['item_id'];
                
                if($psod_row["type"] == 2){
                    $tran_unit = $psod_row['order_unit'];
                }else{
                    $tran_unit = $psod_row['order_unit'];
                }     
                
                if(isset($psod_row["pdrd_id"]) &&  $psod_row["pdrd_id"] > 0){
                    $tran_unit_rate = $psod_row["pdrd_tran_unit_rate"];
                }else{
                    $tran_unit_rate = $psod_row["order_unit_rate"];
                } 
                        
                $tran_unit_qty = input_num('quantity_psod'."_".$psod_row['id']);
                                
                $line_comment = $psod_row['line_comment'];
                
//                $task_id = $psod_row['task_id'];
                $task_id = 0;
                
                $conversion_factor = 1;
                if($psod_row["type"] == 2){
                    get_convertion_factor2($psod_row['item_id'], $tran_unit, $conversion_factor);
                    $quantity = $tran_unit_qty * $conversion_factor;
                }else{                
                    $quantity = $tran_unit_qty * $conversion_factor;
                }
            
                       
            $pdr_detail_id = get_existing_pdr_details_id($pso_detail_id, $pdr_no);
        
        
            if(!($pdr_detail_id > 0)){
                add_project_dispatch_request_line($pdr_no, $type, $description, $item_id,
                                                    $tran_unit, $tran_unit_rate, $tran_unit_qty, $line_comment, 
                                                    $task_id, $conversion_factor, $quantity, $pso_detail_id);                
                               
            }else{
                update_project_dispatch_request_line($pdr_detail_id, $type, $description, $item_id,
                                                    $tran_unit, $tran_unit_rate, $tran_unit_qty, $line_comment, 
                                                    $task_id, $conversion_factor, $quantity, $pso_detail_id);                
            }                          
        
        }    
       
    }
        return array("success" => true, 'trans_no' => $pdr_no, "message" => "Selected lines successfully saved.");
   
}


function display_pdr_details_pso($pso_no, $pdr_no, &$total_pso = 0){
    global $project_sales_order_item_types;
    
    display_heading("Project Sales Order Details");

    $result = get_pdr_details_pso($pso_no, $pdr_no);

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

    $th = array(_("Id"), _('Type'),_("Description"),
                _('Unit'), _('Rate'),
                _("Qty"), "Line Total", _('Comment'), "");              

    table_header($th);

    $k = 0; 
    while($psod_row = db_fetch($result)){
        alt_table_row_color($k);
        label_cell($psod_row['id'], "align=center");

        label_cell($project_sales_order_item_types[$psod_row["type"]]);  
        
        switch($psod_row['type']){
            case PSOIT_BOQ_ITEM:
                $boq_item = get_project_boq_item_details($psod_row["item_id"]);
                $item_details = $boq_item['code']." - ".$boq_item['description'];
                break;
            case PSOIT_STOCK_ITEM:
                $stock_item = get_stock_item_edit_info($psod_row["item_id"]);
                $item_details = $stock_item['stock_id']." - ".$stock_item['description'];
                break;
            case PSOIT_TEXT:
            default:
                $item_details = $psod_row["description"];
                break;
            
        }
        
        label_cell($item_details);  
        
        label_cell($psod_row['unit_name']);       
     
        label_cell($psod_row['order_unit_rate']);

        $pdr_details = get_applicable_quantity($psod_row['id'], $pdr_no);
        $pdrd_quantity = $pdr_details['pdrd_quantity'];
              
        if(isset($pdrd_quantity)){
            $_POST['quantity_psod'."_".$psod_row['id']] = $pdr_details['pdrd_quantity'];
        }else{
            $_POST['quantity_psod'."_".$psod_row['id']]  = $psod_row['quantity'];
        }     
        
        if(isset($psod_row['pdrd_id']) && $psod_row['pdrd_id'] > 0){
            label_cell(number_format($pdrd_quantity, 3), "align=right");
        }
        else{
            amount_cells(null, 'quantity_psod'."_".$psod_row['id']);
        }

        $line_total = $pdrd_quantity * $psod_row['order_unit_rate'];        
        if(isset($psod_row['pdrd_id']) && $psod_row['pdrd_id'] > 0){
            amount_decimal_cell($line_total);
        }
        else{
            label_cell("");
        }
        
        label_cell($psod_row['line_comment']);
        
        if(isset($psod_row['pdrd_id']) && $psod_row['pdrd_id'] > 0){
            delete_button_cell("Delete".$psod_row["pdrd_id"], _("Delete")); 
        }
        else{
            check_cells(null, 'selected_'.$psod_row['id'], null, false);
        }
                                

        end_row();    

        $total_pso += $line_total;
    }

    start_row();
    label_cell("Sub Total", "align=right colspan=6");
    label_cell("<b>".number_format($total_pso, 2)."</b>", "align=right");
    end_row();
    end_table();

}

function display_selected_tax_types($pdr_no, $tax_group_id)
{
    display_heading("Tax Details");
    
    start_table(TABLESTYLE, "width=20%");

    $th = array(_('Tax Type'),_("Amount"));              

    table_header($th);
    
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type) {
        if($tax_type['rate'] > 0){
            $tax_amount = get_pdr_tax_type_amount($pdr_no, $tax_type['tax_type_id']);
            $_POST[$tax_type['tax_type_id'].'_mpi_tax'] = $tax_amount;
            amount_row($tax_type['tax_type_name'], $tax_type['tax_type_id'].'_mpi_tax');   
        }
    }
    
    end_table();
}


if(isset($_POST['Save_Project_Dispatch_Request_Header'])){
        
    $msg = save_pdr_header($pdr_no);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['PDRNo'] = $msg['trans_no'];
        display_notification($msg['message']);
        $Mode = 'RESET';
    }

}


if(isset($_POST['Add_PDR_Line']) || isset($_POST['Update_PDR_Line'])){
        
        $header_msg = can_process_pdr_header($pdr_no);
        if($header_msg['success'] !== true){
            display_error($header_msg['message']);
            return $header_msg;
        }
        
        $line_msg = can_process_pdr_line_manual();
        if($line_msg['success'] !== true){
            display_error($line_msg['message']);
            return $line_msg;
        }
       

    $msg = save_pdr_manual($pdr_no, $selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $pdr_no = $msg['trans_no'];
        hidden('PDRNo', $msg['trans_no']);
        display_notification($msg['message']);
        $Mode = 'RESET';
    }

}


if(isset($_POST['Save_PDR_Lines_PSO'])){
   
    $selected_msg = can_process_pdr_lines_pso($pdr_no);
    if($selected_msg['success'] !== true){
        display_error($selected_msg['message']);
        return $selected_msg['message'];
    }

    $h_msg = save_pdr_header($pdr_no);
    
    if($h_msg['success'] !== true){
        display_error($h_msg['message']);
    }
    else{
        $_POST['PDRNo'] = $h_msg['trans_no'];
        display_notification($h_msg['message']);
        $Mode = 'RESET';
    }
    
    
    $s_line_msg = save_pdr_details_pso($pdr_no);
    if($s_line_msg['success'] !== true){
        display_error($s_line_msg['message']);
    }else{
        display_notification($s_line_msg['message']);
    }   
    
}


if (isset($_POST['cancel']) || isset($_POST['CancelItemChanges'])){
    $Mode = 'RESET';
    $selected_id = -1;
    unset($_POST);
}  
//--------------------------------------------------------------------------------------------------------

if ($Mode == 'Delete')
{
        $recs = delete_project_dispatch_request_line($selected_id);
               
        if($recs == 1){
               display_notification(_("Project dispatch request item has been deleted."));
        }
        else{
                display_error(_("Project dispatch request item could not be deleted."));
        }
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}
    $Ajax->activate('_page_body');
    $Ajax->activate('billing_items');
//--------------------------------------------------------------------------------------------------------------
if (!@$_GET['popup'])
start_form();

$pi_header = display_pdr_header($pdr_no);
//hidden('reference', $_POST['reference']);

if(($pdr_no > 0)){
    submit_center_first('Save_Project_Dispatch_Request_Header', _("Save"), '', 'default');
  
//    hidden('PDRNo', $_POST['PDRNo']);
}
 
br(2);

//------------------------------------------------------------------------------------------------------------
    
  
display_pdr_details_pso($pso_no, $pdr_no);
  
br();

if($pso_no > 0){
     submit_center_first('Save_PDR_Lines_PSO', _("Save Selected Lines"), '', 'default');
   
}

br(2);

display_pdr_details_manual($pdr_no, $selected_id);
hidden('PDRNo', $pdr_no);


//inactive_control_row($th);

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

//display_pdr_edit_controls_manual($selected_id, $Mode);
//
//
//if($selected_id > 0){
//    submit_center_first('Update_PDR_Line', _("Update"), '', 'default');
//    hidden('selected_id', $selected_id);
//    
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}
//else{        
//    submit_center_first('Add_PDR_Line', _("ADD"), '', 'default');
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}

br();

display_selected_tax_types($pdr_no, $_POST['tax_group_id']);
    
br();

if($pso_no > 0){
     submit_center_first('Save_PDR_Taxes', _("Save Taxes"), '', 'default');
}

if (!@$_GET['popup'])
{
    end_form();
    end_page(@$_GET['popup'], false, false);        
}


?>
