<?php
/**********************************************************************
***********************************************************************/
//-----------------------------------------------------------------------------
//
//	Entry/Modify Delivery Note against Sales Order
//
$page_security = 'SA_SALESDELIVERY';
$path_to_root = "..";

include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/sales/includes/cart_class.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/sales/includes/sales_ui.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/taxes/tax_calc.inc");

include_once($path_to_root . "/purchasing/includes/pr_validations.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");

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

if (isset($_GET['OrderNumber'])) {
	$_SESSION['page_title'] = sprintf(_("Purchase for Sales Order # %d."), $_GET['OrderNumber']);
	$help_context = "Supply for Sales Order";
	processing_start();
}

page($_SESSION['page_title'], false, false, "", $js);

                
if (isset($_GET['AddedPRID']) || isset($_GET['AddedClosedPRID'])) {
	$added_pr_no = $_GET['AddedPRID'];

    if(isset($_GET['AddedPRID'])){
        display_notification_centered(sprintf(_("Purchase Requisition # %d has been created."),$added_pr_no));
    }
    if(isset($_GET['AddedClosedPRID'])){
        display_notification_centered(sprintf(_("Purchase Requisition # %d has been created and sales order was closed for purchasing."),$added_pr_no));
    }

	display_note(get_customer_trans_view_str(ST_PURCH_REQ, $added_pr_no, _("&View this Purchase Requisition")), 0, 1);

	display_note(print_document_link($added_pr_no, _("&Print this Purchase Requisition"), true, ST_PURCH_REQ));
//	display_note(print_document_link($dispatch_no, _("&Email Delivery Note"), true, ST_CUSTDELIVERY, false, "printlink", "", 1), 1, 1);
//	display_note(print_document_link($dispatch_no, _("P&rint as Packing Slip"), true, ST_CUSTDELIVERY, false, "printlink", "", 0, 1));
//	display_note(print_document_link($dispatch_no, _("E&mail as Packing Slip"), true, ST_CUSTDELIVERY, false, "printlink", "", 1, 1), 1);

//	display_note(get_gl_view_str(13, $dispatch_no, _("View the GL Journal Entries for this Dispatch")),1);

//	hyperlink_params("$path_to_root/sales/customer_invoice.php", _("Invoice This Delivery"), "DeliveryNumber=$dispatch_no");

	hyperlink_params("$path_to_root/sales/inquiry/sales_orders_view.php", _("Select another Sales Order for Ordering"), "type=30");

	display_footer_exit();

} 

if (isset($_GET['ClosedOnlySOID'])) {
	$closed_so_no = $_GET['ClosedOnlySOID'];
    
    display_notification_centered(sprintf(_("Sales order # %d has been closed for purchasing."),$closed_so_no));

    display_footer_exit();
    
}
//-----------------------------------------------------------------------------


if (isset($_GET['OrderNumber']) && $_GET['OrderNumber'] > 0) {

	$ord = new Cart(ST_SALESORDER, $_GET['OrderNumber'],false);

//	if ($ord->count_items() == 0) {
//		hyperlink_params($path_to_root . "/sales/inquiry/sales_orders_view.php",
//			_("Select a different sales order to delivery"), "OutstandingOnly=1");
//		die ("<br><b>" . _("This order has no items. There is nothing to delivery.") . "</b>");
//	}

 	// Adjust Shipping Charge based upon previous deliveries TAM
	adjust_shipping_charge($ord, $_GET['OrderNumber']);
 
	$_SESSION['Items'] = $ord;
	copy_from_cart();
}


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

function check_data()
{
	global $Refs;

	if (!isset($_POST['SupplyRequiredDate']) || !is_date($_POST['SupplyRequiredDate']))	{
		display_error(_("The entered date of delivery is invalid."));
		set_focus('SupplyRequiredDate');
		return false;
	}

    if (!($_POST['project_id'] > 0))	{
		display_error(_("Please select a Project."));
		set_focus('project_id');
		return false;
	}
    
    if (!($_POST['task_id'] > 0))	{
		display_error(_("Please select a Task / Budget."));
		set_focus('task_id');
		return false;
	}
    
	if ($_SESSION['Items']->trans_no==0) {
		if (!$Refs->is_valid($_POST['ref'])) {
			display_error(_("You must enter a reference."));
			set_focus('ref');
			return false;
		}
	}
    
    $ref_msg = reference_exists($_POST['im_reference'], ST_PURCH_REQ);    
    if ($ref_msg){
		display_error($ref_msg);
		set_focus('im_reference');
		return false;
	}


	if (!check_quantities()) {
		return false;
	}

	return true;
}

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

function copy_to_cart()
{
	$cart = &$_SESSION['Items'];
	$cart->ship_via = $_POST['ship_via'];
	$cart->freight_cost = input_num('ChargeFreightCost');
	$cart->document_date = $_POST['DispatchDate'];
	$cart->due_date =  $_POST['due_date'];
	$cart->Location = $_POST['Location'];
	$cart->Comments = $_POST['Comments'];
	$cart->dimension_id = $_POST['dimension_id'];
	$cart->dimension2_id = $_POST['dimension2_id'];
    $cart->project_id = $_POST['project_id'];
	if ($cart->trans_no == 0){
		$cart->reference = $_POST['ref'];
    }

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

function copy_from_cart()
{
	$cart = &$_SESSION['Items'];
	$_POST['ship_via'] = $cart->ship_via;
	$_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
	$_POST['DispatchDate'] = $cart->document_date;
	$_POST['due_date'] = $cart->due_date;
	$_POST['Location'] = $cart->Location;
	$_POST['Comments'] = $cart->Comments;
	$_POST['dimension_id'] = $cart->dimension_id;
	$_POST['dimension2_id'] = $cart->dimension2_id;
	$_POST['cart_id'] = $cart->cart_id;
	$_POST['ref'] = $cart->reference;
    $_POST['project_id'] = $cart->project_id;
}
//------------------------------------------------------------------------------

function check_quantities()
{
	$ok =1;

    $item_count = 0;
    foreach ($_SESSION['Items']->line_items as &$line_item) {
        $line = $line_item->id;
        if(isset($_POST['Line'.$line.'_select_line'])){
            $line_item->check_issue_item = true;
            $item_count++;
        }
        else{
            $line_item->check_issue_item = false;
        }    
        
        if($line_item->check_issue_item){
            if(get_mb_flag($line_item->stock_id) == "M"){
                display_error("Item $line_item->stock_id - $line_item->item_description is a Manufacturing item and can not be purchased.");
                return false;
            }
        }
    }
    
    if($item_count == 0){
        display_error("No items selected for purchase requisition creation.");
        return false;
    }
	
// ...
//	else
//	  $_SESSION['Items']->freight_cost = input_num('ChargeFreightCost');
	return true;
}
//------------------------------------------------------------------------------

function check_qoh()
{
    global $SysPrefs;
    $dn = &$_SESSION['Items'];
    $newdelivery = ($dn->trans_no==0);
    if (!$SysPrefs->allow_negative_stock()) {
        foreach ($_SESSION['Items']->line_items as $itm) {

            if ($itm->qty_dispatched && has_stock_holding($itm->mb_flag)) {
                $qoh_by_date = get_qoh_on_date($itm->stock_id, $_POST['Location'], $_POST['DispatchDate']);
                $qoh_abs = get_qoh_on_date($itm->stock_id, $_POST['Location'], null);
                //If editing current delivery delivered qty should be added 
                if (!$newdelivery)
                {
                    $delivered = get_already_delivered($itm->stock_id, $_POST['Location'], key($dn->trans_no));
                    
                    $qoh_abs = $qoh_abs - $delivered;
                    $qoh_by_date = $qoh_by_date - $delivered;
                }
                $qoh = ($qoh_by_date < $qoh_abs ? $qoh_by_date : $qoh_abs); 
                if ($itm->qty_dispatched > $qoh) {
                    display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:") .
                        " " . $itm->stock_id . " - " . $itm->item_description);
                    return false;
                }
            }
        }
    }
    return true;
}

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

function display_sales_order_pr_header()
{
    //start_table(TABLESTYLE2, "width=80%", 5);
    
    if(isset($_SESSION['Items']->order_no) && $_SESSION['Items']->order_no > 0){
        $project_id = $_SESSION['Items']->project_id;
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        }  
    }
    
    display_heading(_("Sales Order"));
    
    echo "<tr><td>"; // outer table

    start_table(TABLESTYLE, "width=50%");
    
    start_row();
        if(isset($_POST['project_id'])){
            $_SESSION['Items']->project_id  = $_POST["project_id"];
        }
        label_cells(_("Project"), $_SESSION['Items']->project_description, "class='tableheader2'");
        hidden('project_id', $_SESSION['Items']->project_id);
        
        label_cells(_("Customer"), $_SESSION['Items']->customer_name, "class='tableheader2'");

    end_row();
    
    
    start_row();
        label_cells(_("For Sales Order"), get_customer_trans_view_str(ST_SALESORDER, $_SESSION['Items']->order_no), "class='tableheader2'");

        label_cells(_("Branch"), get_branch_name($_SESSION['Items']->Branch), "class='tableheader2'");

    end_row();
    
    
    start_row();
        if ($_SESSION['Items']->trans_no==0) {
            ref_cells(_("Reference"), 'ref', '', null, "class='tableheader2'");
        } 
        else {
            label_cells(_("Reference"), $_SESSION['Items']->reference, "class='tableheader2'");
        }
        
        
        if (!isset($_POST['Location'])) {
            $_POST['Location'] = $_SESSION['Items']->Location;
        }

        label_cells(_("Receive Into"), $_SESSION['Items']->location_name, "class='tableheader2'");

    end_row();

    start_row();
        
        label_cells(_("Required Date"), $_SESSION['Items']->due_date , "class='tableheader2'");
        
        if (!isset($_POST['SupplyRequiredDate']) || !is_date($_POST['SupplyRequiredDate'])) {
                $_POST['SupplyRequiredDate'] = $_SESSION['Items']->due_date;
        }
        
    end_row();
    
    end_table();

//    echo "</td><td>";// outer table

    br();
    
    display_heading(_("Purchase Requisition"));
    global $Refs;
    
    start_outer_table(TABLESTYLE2, "width=50%"); // outer table
        table_section(1, "50%");
        if(isset($_POST['project_id'])){
            $_SESSION['Items']->project_id  = $_POST["project_id"];
        }
            locations_list_row("Receive Into", 'Location', null, false, true);
            ref_row(_("Reference"), 'im_reference', '', $Refs->get_next(ST_PURCH_REQ));
        
        table_section(2, "50%");
            tasks_list_row("Budget", 'task_id', $_SESSION['Items']->project_id, null, _('Select a Budget'));
            
            if (!isset($_POST['SupplyRequiredDate']) || !is_date($_POST['SupplyRequiredDate'])) {
                $_POST['SupplyRequiredDate'] = new_doc_date();
                if (!is_date_in_fiscalyear($_POST['SupplyRequiredDate'])) {
                    $_POST['SupplyRequiredDate'] = end_fiscalyear();
                }
            }
            date_row(_("Required Date"), 'SupplyRequiredDate', $_POST['SupplyRequiredDate']);
//
//    echo "</td></tr>";
    end_outer_table(1); // outer table
//    end_table(1); // outer table
}


function display_sales_order_pr_items()
{
    br();
    
    display_heading(_("Sales Order Items for Purchase Requisition"));
    div_start('Items');
    start_table(TABLESTYLE, "width=80%");

    $new = $_SESSION['Items']->trans_no==0;
    $th = array(_("Item Code"), _("Item Description"),  
                _("Units"), ("SO Qty"),  ("Invoiced"), 
                _("Ordered"),  _("Units"), _("Ordering Qty"), "Select");
    
    table_header($th);
    
    $k = 0;
    $has_marked = false;

    foreach ($_SESSION['Items']->line_items as $ln_itm) {

        $line = $ln_itm->id;

        if(isset($_POST['_Location_update']) || isset($_POST['clear_quantity']) || isset($_POST['reset_quantity'])) {
            // reset quantity
            $ln_itm->qty_dispatched = $ln_itm->quantity-$ln_itm->qty_done;
        }
        // if it's a non-stock item (eg. service) don't show qoh
        $row_classes = null;
        if (has_stock_holding($ln_itm->mb_flag) && $ln_itm->qty_dispatched) {
            // It's a stock : call get_dispatchable_quantity hook  to get which quantity to preset in the
            // quantity input box. This allows for example a hook to modify the default quantity to what's dispatchable
            // (if there is not enough in hand), check at other location or other order people etc ...
            // This hook also returns a 'reason' (css classes) which can be used to theme the row.

            $qoh = get_qoh_on_date($ln_itm->stock_id, $_POST['Location'], $_POST['SupplyRequiredDate']);
            $q_class =  hook_get_dispatchable_quantity($ln_itm, $_POST['Location'], $_POST['SupplyRequiredDate'], $qoh);
            // Skip line if needed
            if($q_class === 'skip')  continue;
            if(is_array($q_class)) {
              list($ln_itm->qty_dispatched, $row_classes) = $q_class;
                $has_marked = true;
            }

        }

        alt_table_row_color($k, $row_classes);
        view_stock_status_cell($ln_itm->stock_id);

        if ($ln_itm->descr_editable){
            text_cells(null, 'Line'.$line.'Desc', $ln_itm->item_description, 30, 50);
        }
        else{
            label_cell($ln_itm->item_description);
        }

        $dec = get_qty_dec($ln_itm->stock_id);
    
        $order_unit_name = get_unit_descr($ln_itm->tran_unit);
        label_cell($order_unit_name);

        
        $so_unit_so_qty = $ln_itm->quantity / $ln_itm->convertion_factor;
        // SO line tran qty
        qty_cell($so_unit_so_qty, false, $dec);

        //Invoiced tran Qty
        $order_unit_qty_done =  $ln_itm->qty_done / $ln_itm->convertion_factor;
        qty_cell($order_unit_qty_done, false, $dec);

        if(isset($_POST['clear_quantity'])) {
            $ln_itm->qty_dispatched = 0;
        }

        // Ordered
        amount_cell($ln_itm->quantity_ordered / $ln_itm->convertion_factor);
        
        if(!isset($_POST['Line'.$line.'disp_unit'])){
            $_POST['Line'.$line.'disp_unit'] = $ln_itm->tran_unit;
        }
        units_list_cells(null, 'Line'.$line.'purch_unit', $ln_itm->stock_id, 0, false, true);

        $alternate_unit = get_convertion_factor(get_post('Line'.$line.'purch_unit'), $ln_itm->stock_id);
        if($alternate_unit){
            $ln_itm->disp_unit_convertion_factor = $alternate_unit['convertion_factor'];
        }
        else{
            $ln_itm->disp_unit_convertion_factor = 1;
            $item_edit_info = get_item_edit_info($ln_itm->stock_id);
            $_POST['Line'.$line.'disp_unit'] = $item_edit_info['units'];
        }
    
        if(isset($_POST['Line'.$line.'purch_unit_disp_qty'])){
            $purch_unit_disp_qty = input_num('Line'.$line.'purch_unit_disp_qty');
        }
        else{
            $to_be_purchased_qty = $ln_itm->quantity - $ln_itm->quantity_ordered;
            if($to_be_purchased_qty < 0){
                $to_be_purchased_qty = 0;
            }
            $purch_unit_disp_qty = $to_be_purchased_qty / $ln_itm->disp_unit_convertion_factor;
        }
            
        if(list_updated('Line'.$line.'purch_unit')){
            $to_be_purchased_qty = $ln_itm->quantity - $ln_itm->quantity_ordered;
            if($to_be_purchased_qty < 0){
                $to_be_purchased_qty = 0;
            }
            $purch_unit_disp_qty = $to_be_purchased_qty / $ln_itm->disp_unit_convertion_factor;
        }
        
        $_POST['Line'.$line.'purch_unit_disp_qty'] = qty_format($purch_unit_disp_qty, $ln_itm->stock_id, $dec);
        small_qty_cells(null, 'Line'.$line.'purch_unit_disp_qty', null, null, null, $dec);

//        $display_discount_percent = percent_format($ln_itm->discount_percent*100) . "%";
//
//        $line_total = ($ln_itm->qty_dispatched * $ln_itm->price * (1 - $ln_itm->discount_percent));

//        amount_cell($ln_itm->price * $ln_itm->disp_unit_convertion_factor);
//        label_cell($ln_itm->tax_type_name);
//        label_cell($display_discount_percent, "nowrap align=right");
//        amount_cell($line_total);

        check_cells(null, 'Line'.$line.'_select_line');
        
        hidden('Line'.$line.'_row_state', $ln_itm->row_state);
        
        end_row();
    }
    
    end_table(1);
    
    div_end();

}
//------------------------------------------------------------------------------
function create_pr_for_sales_order($close = false, $close_only = false)
{
    $_SESSION['pr_for_so'] = new items_cart(ST_PURCH_REQ);
    $pr = &$_SESSION['pr_for_so'];
    $so = $_SESSION['Items'];
    
    $trans_no = $so->order_no;
    //$pfm->order_id = $trans_no;
    
    $pr->order_id = 0;
    $pr->release = false;
    $pr->pr_reference = $_POST["im_reference"];
    $pr->requesting_location = $_POST["Location"];
    
    // Do not allow PR issues for this PR
    $pr->pr_complete = 1;
    $pr->project_id = $_POST["project_id"];
    $pr->pr_date = $_POST["SupplyRequiredDate"];

    $pr->next_approval_group_id = 0;
    //$pfm->total = $im_cart->total;
    $pr->approval_status = AS_NEW;
    
    $pr->source_type = ST_SALESORDER;
    $pr->source_order_id = $so->order_no;
    
    $count = 0;
    $total = 0;
    
    foreach ($so->line_items as $line_item)
    {
        if( $line_item->check_issue_item){
            $line = $line_item->id;
            if(isset($_POST['Line'.$line.'purch_unit_disp_qty']) && input_num('Line'.$line.'purch_unit_disp_qty') > 0){
                
                $pr_unit_qty = input_num('Line'.$line.'purch_unit_disp_qty');
                $line_item->row_id = $line_item->id;
                
                $alternate_unit = get_post('Line'.$line.'purch_unit');
                get_convertion_factor2($line_item->stock_id, $alternate_unit, $convesion_factor);
                $line_item->tran_unit = $alternate_unit;
                $line_item->quantity = $pr_unit_qty * $convesion_factor;
                $line_item->tran_qty = $pr_unit_qty;

                $line_item->task_id = $_POST["task_id"];
                $line_item->project_site_id = 0 ;
                $line_item->required_date = $pr->pr_date;
                $line_item->line_comment = "";
                $line_item->row_state = get_post('Line'.$line.'_row_state');
                
                // Set item standard cost as the estimate price of PR item
                $standard_cost = get_standard_cost($line_item->stock_id);
                $line_item->price = $standard_cost * $convesion_factor;
                
                $total += $line_item->quantity * $line_item->price;
                
                $pr->line_items[] = $line_item;

                $count = $count + 1;


            }
            
        }
    }
   
    $pr->total = $total;
    
    if($count == 0){
        display_error("No items with outstanding quantities to create a PR or a PR has been already created.");
        return;
    }
        
//        add_pr($mr_data_array, $_SESSION['pr_from_im']->line_items); 
        
    $vpid = validate_pr_item_data($pr);
    
    if($vpid["success"] !== true){
        display_error($vpid["message"]);  
        set_focus($vpid["focus_to"]);
        return;
    }
    else{
        if($vpid["message"] == "close_only"){
            display_error("No need to create a purchase requistion. This MR is to be closed");  
            return;
        }
        else{
            begin_transaction();
            $apr_msg = add_pr($_SESSION['pr_for_so']);
            if($apr_msg['success'] !== true){
                //cancel_transaction();
                cancel_transaction();
                display_error($apr_msg['message']);
            }
            else{
                $pr_no = $apr_msg['tran_no'];
                $so_no = $so->order_no;
                if($close || $close_only){
                    close_sales_order_for_prs($so_no);
                }
                
                commit_transaction();
                new_doc_date($_SESSION['pr_for_so']->pr_date);
                $_SESSION['pr_for_so']->clear_items();
                unset($_SESSION['pr_for_so']);

                $_SESSION['Items']->clear_items();
                unset($_SESSION['Items']);
                
                //set_session_variable('pr_for_wo_messages', $apr_msg["message"]);
                //commit_transaction();
//                end_processing($pr_no, ST_PURCH_REQ);
                
                if($close){
                    meta_forward($_SERVER['PHP_SELF'], "AddedClosedPRID=$pr_no");
                }
                else{
                    meta_forward($_SERVER['PHP_SELF'], "AddedPRID=$pr_no");
                }               
            }
        }
    }
}


function close_so_for_prs()
{
    $so_no = $_SESSION['Items']->order_no;
    close_sales_order_for_prs($so_no);
    
    $_SESSION['Items']->clear_items();
    unset($_SESSION['Items']);
    
    meta_forward($_SERVER['PHP_SELF'], "ClosedOnlySOID=$so_no");

}


if (isset($_POST['CreatePRForSO']) && check_data()) {
	create_pr_for_sales_order();

}

if (isset($_POST['CreatePRForSOClose']) && check_data()) {
	create_pr_for_sales_order(true);

}


if (isset($_POST['CloseSOOnly'])) {
	close_so_for_prs();

}



if (isset($_POST['Update']) || isset($_POST['_Location_update']) || isset($_POST['qty'])) {
	$Ajax->activate('Items');
}
$Ajax->activate('Items');
//------------------------------------------------------------------------------



start_form();
hidden('cart_id');

display_sales_order_pr_header();

$row = get_customer_to_order($_SESSION['Items']->customer_id);
if ($row['dissallow_invoices'] == 1)
{
	display_error(_("The selected customer account is currently on hold. Please contact the credit control personnel to discuss."));
	end_form();
	end_page();
	exit();
}	

display_sales_order_pr_items();

submit_center_first('CreatePRForSO', _("Create PR"),_('Create Purchase Requisition'), 'default');
submit('CreatePRForSOClose', _("Create PR and Close Lines"), true, '', 'default');
br(2);
submit_center_first('CloseSOOnly', _("Close for Purchasing"), '', 'default');


//if(isset($_POST['clear_quantity'])) {
//	submit('reset_quantity', _('Reset quantity'), true, _('Refresh document page'));
//}
//else  {
//	submit('clear_quantity', _('Clear quantity'), true, _('Refresh document page'));
//}


end_form();


end_page();

?>
