<?php

//function get_pr_allocation_ids_string($po_line_id)
//{
//    $pr_ids_info = get_pr_allocation_ids_for_po_line($po_line_id);
//    $pr_ids_string = "";
//    while($pr_ids=db_fetch($pr_ids_info)){
//        $pr_ids = array_unique($pr_ids);
//        foreach ($pr_ids as $pr_id){
//            $pr_ids_string .= get_supplier_trans_view_str(ST_PR_DETAIL_ALLOCATIONS,$pr_id)." ";
//        }
//    }
//    $pr_ids_string = trim($pr_ids_string);
//    return $pr_ids_string;
//}


function display_approve_purchase_order_summary(&$po, $is_self=false, $editable=false)
{
    global $approval_statuses;
    
    start_outer_table(TABLESTYLE2, "width=80%"); // outer table
        start_table(TABLESTYLE2);  
    
            table_section(1, "width=30%");

                label_row(_("Supplier: "), $po->supplier_name);
                
                $tax_group = get_tax_group($po->tax_group_id);
                label_row(_("Tax Group: "), $tax_group['name']);
                label_row(_("Date"), $po->orig_order_date);
                label_row(_("Reference: "), $po->reference);
                label_row(_("Receive Into:"), get_location_name($po->Location));             
                

            table_section(2, "width=30%");
                get_payment_terms_to_order($po, $po->supplier_id, $po->terms['terms_indicator']);
                label_row(_("Payment Terms: "), $po->terms['description']);
                label_row(_("Supplier's Reference: "), $po->supp_ref);
                label_row(_("Project: "), $po->project_description);
                
                
                label_row(_("Order Currency: "), $po->curr_code);
                
                $s = get_project_trans_view_str(98, $po->order_no."&source_type_id=".ST_PURCHORDER, "Approval Status");
                label_row($s,$approval_statuses[$po->approval_status]);

            table_section(3, "width=30%");
//                label_row(_("Approval Path:"), $approval_statuses[$po->approval_status]);
                label_row(_("Delivery Address: "), $po->delivery_address, "", "colspan=9");
        end_outer_table();
    
    end_table(1);
}

function display_approve_purchase_order_details($purchase_order)
{
    start_table(TABLESTYLE, "colspan=9 width=98%");

    $th = array(_("Id"),_("PRs"),_("Allo."), _("Item Code"), _("Item Description"), _("Quantity"), _("Unit"), _("Price"), 
                _("Discount"), _("Del. Date"), _("Line Total"), _("Qty Rcvd"), _("Qty Invcd"));
    table_header($th);
    $total = $k = $discounts_total = 0;
    $overdue_items = false;

    foreach ($purchase_order->line_items as $stock_item){
//        $ids ='';
//        $ids_pr =  get_pr_allocation_ids_for_po_line($stock_item -> row_id);
//        
//            while($ids_data= db_fetch($ids_pr)){
//                $id =  $ids_data['allocation_id'];
//                if($id > 0){
//                     $ids .= get_supplier_trans_view_str(ST_PR_PO_DETAILS,$id, $id).' ' ;
//                }
//            }
            $line_total = $stock_item->tran_qty * ($stock_item->order_unit_price * (1 - $stock_item->order_unit_price_discount /100));
            $line_discounts_total = $stock_item->tran_qty * ($stock_item->order_unit_price * ($stock_item->order_unit_price_discount /100));

            if (($stock_item->quantity - $stock_item->qty_received > 0)	&& date1_greater_date2(Today(), $stock_item->req_del_date)){
                start_row("class='overduebg'");
                $overdue_items = true;
            }
            else{
                alt_table_row_color($k);
            }
            
            label_cell($stock_item->row_id, "align=center");
                
            $prs = get_pr_line_ids_string($stock_item->row_id);
            label_cell($prs, "align=center");

            $pr_allocs = get_pr_allocation_ids_string($stock_item->row_id);
            label_cell($pr_allocs, "align=center");
                
                
//            label_cell($ids, "align=center");
            label_cell($stock_item->stock_id, "align=center");
            label_cell($stock_item->item_description);
            $dec = get_qty_dec($stock_item->stock_id);
            qty_cell($stock_item->tran_qty, false, $dec);
            $alternate_unit = get_unit_name($stock_item->tran_unit);
            label_cell($alternate_unit['name'], "align=center");

            amount_decimal_cell($stock_item->order_unit_price);
            amount_decimal_cell($stock_item->order_unit_price_discount);
            label_cell($stock_item->req_del_date, "align=center");
            amount_cell($line_total);
            if($stock_item->convertion_factor > 0){
                qty_cell($stock_item->qty_received / $stock_item->convertion_factor, false, $dec);
                qty_cell($stock_item->qty_inv / $stock_item->convertion_factor, false, $dec);
            }else{
                qty_cell(0, false, $dec);
                qty_cell(0, false, $dec);
            }
            end_row();

            $total += $line_total;
            $discounts_total += $line_discounts_total;
            
            if(strlen($stock_item->line_comment) > 0){
                $k = $k == 0 ? 1 : 0;
                alt_table_row_color($k);
                label_cell("", 'colspan=4');
                label_cell(nl2br($stock_item->line_comment), 'colspan=6');
                label_cell("", 'colspan=3');
                end_row();
            }
    }

    start_row();
    $display_discounts_total = number_format2($discounts_total,user_price_dec());
    label_cells(_("Discounts Total"), $display_discounts_total, "align=right colspan=8", "nowrap align=right",2);
    label_cell('',"colspan=2");
    label_cell('',"colspan=2");
    end_row();
    
    $display_sub_tot = number_format2($total,user_price_dec());
    label_row(_("Sub Total"), $display_sub_tot, "align=right colspan=10", "nowrap align=right",2);

    $all_taxes = $purchase_order->get_all_taxes();
    $all_taxes_total = display_edit_tax_items($all_taxes, 10, $purchase_order->tax_included,2);

    $staxes = $purchase_order->get_staxes_total();

    $tax_total = $all_taxes_total - $staxes;
    $display_total = price_format(($total + $tax_total));

    start_row();
    label_cells(_("Amount Total"), $display_total, "colspan=10 align='right'","align='right'");
    label_cell('', "colspan=2");
    end_row();

    end_table();

    if ($overdue_items){
        display_note(_("Marked items are overdue."), 0, 0, "class='overduefg'");
    }

    br(1);
    start_table(TABLESTYLE, "width=40%");
    if ($purchase_order->Comments != ""){
        label_row(_("Comments: "), $purchase_order->Comments, '', "colspan=9");
    }
    end_table();
    
    //----------------------------------------------------------------------------------------------------

//    br(2);
//    start_outer_table(TABLESTYLE, "width=60%");
//    $k = 0;
//
//    $grns_result = get_po_grns($_GET['trans_no']);
//
//    if (db_num_rows($grns_result) > 0){
//
//        display_heading2(_("Deliveries"));
//        start_table(TABLESTYLE);
//        $th = array(_("#"), _("Reference"), _("Delivered On"));
//        table_header($th);
//        while ($myrow = db_fetch($grns_result)){
//            alt_table_row_color($k);
//
//            label_cell(get_trans_view_str(ST_SUPPRECEIVE,$myrow["id"]));
//            label_cell($myrow["reference"]);
//            label_cell(sql2date($myrow["delivery_date"]));
//            end_row();
//        }
//        end_table();
//    }

//    $invoice_result = get_po_invoices_credits($_GET['trans_no']);
//
//    $k = 0;
//
//    if (db_num_rows($invoice_result) > 0){
//
//        echo "</td><td valign=top>"; // outer table
//
//        display_heading2(_("Invoices/Credits"));
//        start_table(TABLESTYLE);
//        $th = array(_("#"), _("Date"), _("Total"));
//        table_header($th);
//        while ($myrow = db_fetch($invoice_result)){
//            alt_table_row_color($k);
//
//            label_cell(get_trans_view_str($myrow["type"],$myrow["trans_no"]));
//            label_cell(sql2date($myrow["tran_date"]));
//            amount_cell($myrow["Total"]);
//            end_row();
//        }
//        end_table();
//    }
//    
//    end_outer_table();
}





function can_commit_approve_purchase_order($purchase_order)
{
    global $Refs;
    
        if (!($purchase_order->order_no > 0)){
                $message = (_("There is no purchase order selected."));
                return array("success" => false, "message" => $message);
        }

        if (!$purchase_order->supplier_id){
                $message = (_("There is no supplier selected."));
                return array("success" => false, "message" => $message);
        } 

        if ($purchase_order->project_id < 1){
                $message = (_("There is no job selected."));
                return array("success" => false, "message" => $message);
        }
	
	if (!$purchase_order->orig_order_date){
		$message = (_("The entered order date is invalid."));
		return array("success" => false, "message" => $message);
	} 
	
        if ($purchase_order->trans_type == ST_PURCHORDER){
            if($purchase_order->order_no > 0){
                $po_info = get_po_edit_info($purchase_order->order_no);
                if(!($po_info['approval_status'] == AS_NEW || $po_info['approval_status'] == AS_AWAITING_APPROVAL 
                        || $po_info['approval_status'] == AS_WITH_THE_APPROVER || $po_info['approval_status'] == AS_BACK_TO_ORIGINATOR 
                        || $po_info['approval_status'] == AS_REOPENED)){
                    $message = ("This Purchase Order has been approved or rejected already. Further updating not allowed.");
                    return array("success" => false, "message" => $message);
                }

                $ced_msg = can_edit_document($purchase_order->trans_type, $purchase_order->project_id, $purchase_order->next_approval_group_id, 
                                             $_SESSION['wa_current_user']->user, $purchase_order->created_by);
                if($ced_msg['success'] !== true){
                    $message = ( $ced_msg['message']);
                    return array("success" => false, "message" => $message);
                }
            }
        }
    
	if ($purchase_order->trans_type != ST_PURCHORDER && !is_date_in_fiscalyear($purchase_order->orig_order_date)){
            $message = (_("PO date is not in fiscal year"));
            return array("success" => false, "message" => $message);
	}
	
	if ($purchase_order->trans_type == ST_PURCHORDER && $purchase_order->delivery_address == ''){
            $message = (_("There is no delivery address specified."));
            return array("success" => false, "message" => $message);
	} 
	if ($purchase_order->Location == ''){
            $message = (_("There is no location specified to move any items into."));
            return array("success" => false, "message" => $message);
	} 
	if (!db_has_currency_rates($purchase_order->curr_code, $purchase_order->orig_order_date)){
            return array("success" => false, "message" => '');
        }

	if ($purchase_order->order_has_items() == false){
            $message = (_("The order cannot be placed because there are no lines entered on this order."));
            return array("success" => false, "message" => $message);
	}
        	
	return array("success" => true, "message" => '');
}


//function approve_po($po_no, $cart)
//{
//    $current_user_id = $_SESSION['wa_current_user']->user;
//    $po_total = calculate_po_remaining_total($cart->line_items);
//      
//    $info = approve_document(ST_PURCHORDER, $po_no, $cart->project_id, $po_total, $cart->next_approval_group_id, $current_user_id, $cart->row_state);
//
//    if($info['success'] !== true){
//        cancel_transaction();
//        return array("success" => $info['success'], "message" => $info['message']);
//    }
//
//    return array("success" => true, "message" => $info['message']);
//
//}




function release_approve_purchase_order(&$purchase_order)
{
    $ccpo_msg = can_commit_approve_purchase_order($purchase_order);
    if($ccpo_msg['success'] !== true){
        cancel_transaction();
        display_error($ccpo_msg['message']);
        return;
    }
    
    $current_user_id = $_SESSION['wa_current_user']->user;

    $po_total = $purchase_order->get_trans_total();
    
    $row_state = $purchase_order->row_state;
    
    begin_transaction();
    $info = approve_document(ST_PURCHORDER, $purchase_order->order_no, $purchase_order->project_id, 
                        $po_total, $purchase_order->next_approval_group_id, 
                        $current_user_id, $row_state);

    if($info['success'] !== true){
        cancel_transaction();
        display_error($info['message']);
    }
    else{
        commit_transaction();
        $po_no = $purchase_order->order_no;
        unset($purchase_order);
        set_session_variable('po_messages', array('success' => true, 'message' => $info['message']));
        
        meta_forward($_SERVER['PHP_SELF'], "ReleasedID=".$po_no);	
    }
}



function send_approve_purchase_order_back_to_originator($purchase_order)
{
    $ccpo_msg = can_commit_approve_purchase_order($purchase_order);
    if($ccpo_msg['success'] !== true){
        cancel_transaction();
        display_error($ccpo_msg['message']);
        return;
    }
    
    $po = $purchase_order;
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    begin_transaction();
    $sbdo_msg = send_back_to_document_originator($po->trans_type, $po->order_no, $po->project_id,
                                                 $po->next_approval_group_id, $current_user_id, $po->row_state, 
                                                 $po->created_by);
    
    if($sbdo_msg['success'] !== true){
        cancel_transaction();
        display_error($sbdo_msg['message']);
    }
    else{
        commit_transaction();
//        new_doc_date($_POST['OrderDate']);
//        $_SESSION['PO']->clear_items();
        $po_no = $purchase_order->order_no;
        unset($purchase_order);
        set_session_variable('po_messages', array('success' => true, 'message' => $sbdo_msg['message']));
        
        meta_forward($_SERVER['PHP_SELF'], "ReleasedID=".$po_no);	
    }

}


function reject_approve_purchase_order($purchase_order)
{
    $ccpo_msg = can_commit_approve_purchase_order($purchase_order);
    if($ccpo_msg['success'] !== true){
        cancel_transaction();
        display_error($ccpo_msg['message']);
        return;
    }
    
//    $po = $_SESSION['PO'];
    $po = $purchase_order;
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    begin_transaction();
    $sbdo_msg = reject_document($po->trans_type, $po->order_no, $po->project_id, $po->next_approval_group_id, $current_user_id, $po->row_state);
    
    if($sbdo_msg['success'] !== true){
        cancel_transaction();
        display_error($sbdo_msg['message']);
    }
    else{
        commit_transaction();
        $trans_no = $po->order_no;
        unset($purchase_order);
        set_session_variable('po_messages', array('success' => true, 'message' => "Purchase order ".$sbdo_msg['tran_no']." has been rejected."));
        
        meta_forward($_SERVER['PHP_SELF'], "ReleasedID=".$trans_no);	
    }

}



?>
















































































































































































