<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/projects/includes/db/tasks_db.inc");
include_once($path_to_root . "/inventory/includes/db/material_requisitions_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
//--------------------------------------------------------------------------------

function add_pr_to_cart(&$order, $new_item, $new_item_qty, $required_date, 
                    $line_comment=null,$row_id = 0, $issued_qty = 0, $requested_qty = 0,
                    $stock_category_id = 0, $price = 0, $requesting_location = null,
                    $tran_unit = '', $tran_qty = 0, $convertion_factor = 1)
{
    $order->add_to_cart(count($order->line_items), $new_item, $new_item_qty, 
                    null, null, null, $required_date, 
                    $line_comment, $row_id, $issued_qty, $requested_qty,
                    $stock_category_id, $price, $requesting_location, 0,null, null,null, null, null,
                    $tran_unit, $tran_qty, $convertion_factor);
    
//    if ($order->find_cart_item($new_item))
//    {
//        display_error(_("For Part :") . $new_item . " " . "This item is already on this material requisition.  You can change the quantity requested of the existing line if necessary.");
//    }
//    else
//    {
//        $order->add_to_cart(count($order->line_items), $new_item, $new_item_qty, 
//                    null, null, null, $required_date, 
//                    $line_comment, $row_id, $issued_qty, $requested_qty,
//                    $stock_category_id, $price, $requesting_location, 0,null, null,null, null, null,
//                    $tran_unit, $tran_qty, $convertion_factor);
//    }
}

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

function display_pr_header(&$order)
{
	global $Refs, $approval_statuses, $Ajax, $systypes_array;
    
    if(isset($order->order_id) && $order->order_id > 0){
        $project_id = $order->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;
        }  
    }        

    div_start('header_tbl');
	start_outer_table(TABLESTYLE2, "width=65%"); // outer table
	table_section(1);
        
        if($order->order_id > 0)
        {
            $order = $_SESSION['pr_items'];
            
            if(!isset($_POST['requesting_location'])){
                $_POST["requesting_location"] = $order->requesting_location;
            }
            if(isset($_POST['requesting_location'])){
                $order->requesting_location  = $_POST["requesting_location"];
            }
            
            if(isset($_POST['location'])){
                $order->location  = $_POST["location"];
            }
            
            if(isset($_POST['project_id'])){
            $order->project_id  = $_POST["project_id"];
            }

            locations_list_row(_("Requesting Location:"), 'requesting_location', $order->requesting_location);
            //project_list_row(_("Job:"), 'project_id', $order->project_id,FALSE,TRUE);
//            if(isset($order->job_reference) && !list_updated('project_id')){
//                label_row(_("Job Reference:"), $order->job_reference);
//            }
            if($order->count_items() > 0){
                hidden("project_id", $order->project_id);
                $_POST['project_id'] = $order->project_id;
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Project:"), $order->job_reference);
            }
            else{
                project_list_row(_("Project:"), 'project_id', $order->project_id,FALSE,TRUE);
            }

            if(list_updated('project_id') && $_POST['project_id'] != -1)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Project:"), $order->job_reference);
            }
            //tasks_list_row(_("Budget:"), 'task_id', $order->project_id, $order->task_id,FALSE,TRUE);
//            approval_path_list_row(_("Select Approval Path:"), 'approval_path_id', $order->approval_path_id,FALSE,TRUE);
//            if ($_POST['project_id'] != -1)
//            {
//                $result = get_project_approval_path($_POST['project_id']);
//                label_row(_("Approval Path:"), $result['approval_path_name']);
//            }
//            else {
//                label_row(_("Approval Path:"),"");
//            }
            
            
            table_section(2);
            //text_row(_("Reference:"), 'pr_reference', $order->reference, 10, 20);
            label_row(_("Reference:"),$order->reference);
            hidden('pr_reference', $order->reference);
            
            $_POST['pr_date'] = sql2date($order->required_date);
            date_row(_("Date:"), 'pr_date');
            
            if (! isset($_POST['purchase_to_stock'])) {
                $_POST["purchase_to_stock"] = $order->pr_complete;
            }
            
            if($order->source_type > 0){
                label_row('Source Type',$systypes_array[$order->source_type]);
                $source_link = get_trans_view_str($order->source_type, $order->source_order_id);            
                label_row('Source No.',$source_link);
                
                $_POST["purchase_to_stock"] = 1;
                hidden('purchase_to_stock', $_POST["purchase_to_stock"]);
            }
            else{
                yesno_list_row(_("Purchase to Stock:"), 'purchase_to_stock');
            }
            
            table_section(3);
            //yesno_list_row("Make Requisition Complete:", "pr_complete", $order->pr_complete);
            //yesno_list_row("Use Future Budgets:", "use_future_budget", $order->use_future_budget);
            label_row(_("Requestor:"), $order->requestor_name);
//            label_row(_("Approval Status"), $approval_statuses[$order->approval_status]);
            
            
            
            
            $s = get_project_trans_view_str(ST_APPROVAL_LOG, $order->order_id."&source_type_id=".ST_PURCH_REQ, "Approval Status");
            //label_cell($s);
            label_row($s,$approval_statuses[$order->approval_status]);
            
            
        }
        
        else 
        {
            table_section(1, "50%");
            
            locations_list_row(_("Requesting Location:"), 'requesting_location', null);
            //project_list_row(_("Job:"), 'project_id', null, _('Select a Job'), true);
//            if(isset($order->job_reference) && !list_updated('project_id')){
//                label_row(_("Job Reference:"), $order->job_reference);
//            }

            if(isset($_POST['project_id'])){
                $order->project_id  = $_POST["project_id"];
            }
            
            if($order->count_items() > 0){
                hidden("project_id", $order->project_id);
                $_POST['project_id'] = $order->project_id;
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            }
            else{
                project_list_row(_("Job:"), 'project_id', $order->project_id,FALSE,TRUE);
            }

            if((list_updated('project_id') && $_POST['project_id'] != -1) || 
                    (!isset($order->job_reference) && $_POST['project_id'] != -1))
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            }
            //tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], null, _('Select a budget'), true);
            if ($_POST['project_id'] != -1)
            {
                $approval_path_type_code = get_approval_path_type(ST_PURCH_REQ);
        
                $approval_path = get_approval_path($_POST['project_id'], $approval_path_type_code);
                label_row(_("Approval Path:"), $approval_path['approval_path_name']);
            }
            else {
                label_row(_("Approval Path:"),"");
            }
            
            
            table_section(2, "25%");
            
            ref_row(_("Reference:"), 'pr_reference', '', $Refs->get_next(ST_PURCH_REQ));
            date_row(_("Date:"), 'pr_date', '', false);
            

            table_section(3, "35%");
            
            //yesno_list_row("Make Requisition Complete:", "pr_complete");
            //yesno_list_row("Use Future Budgets:", "use_future_budget");

            $id_user = $_SESSION['wa_current_user']->user;
            $user = get_requestor($id_user);
            label_row(_("Requestor:"), $user['real_name']);
            
            if (list_updated('project_id')) {
                unset($_POST['purchase_to_stock']);
            }
            
            if (! isset($_POST['purchase_to_stock'])) {
                $project = get_project($_POST['project_id']);
                    if (is_array($project)) {
                        $_POST["purchase_to_stock"] = $project['purchase_to_stock'];
                    }
            }
            
            yesno_list_row(_("Purchase to Stock:"), 'purchase_to_stock');
            label_row(_("Approval Status"), $approval_statuses[$order->approval_status]);
        }

        end_outer_table(1); // outer table
        div_end();
        $Ajax->activate('header_tbl');
}

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

function display_pr_items($title, &$order)
{
	global $path_to_root, $stock_types;;

	display_heading($title);
        div_start('items_table');
	start_table(TABLESTYLE, "width=100%");
	$th = array(_("Item Code"), _("Item Description"), _("Item Type"), _("Quantity"),
                _("Unit"), _("Estimated Price"), _("Required Date"),
                _("Commnets"),_("Budget"), _("Job"), "");
	if ( count($order->line_items)) $th[] = '';

	table_header($th);
	$total = 0;
	$k = 0;  //row colour counter

        if(isset($_POST['LineNo']) && $_POST['LineNo'] >= 0){
            $id = $_POST['LineNo'];
        }
        else{
            $id = find_submit('Edit');
        }
	foreach ($order->line_items as $line_no=>$stock_item)
	{

		$total += ($stock_item->standard_cost * ($stock_item->quantity * $stock_item->convertion_factor));

		if ($id != $line_no)
		{
                    alt_table_row_color($k);
                    $stock_category_name = get_category_name($stock_item->stock_category_id);
                    //label_cell($stock_category_name);
                   
                    view_stock_status_cell($stock_item->stock_id);
                    label_cell($stock_item->item_description);
                    label_cell($stock_types[$stock_item->mb_flag]);
//                    qty_cell($stock_item->requested_qty);
//                    label_cell($stock_item->units);
                    qty_cell($stock_item->tran_qty, false, get_qty_dec($stock_item->stock_id));
                    if($stock_item->tran_unit == ""){
                        label_cell($stock_item->units);
                    }
                    else{
                        label_cell($stock_item->tran_unit);
                    }
//                    amount_cell($stock_item->estimate_price);
                    qty_cell($stock_item->estimate_price, false, 2);
                    //amount_decimal_cell($stock_item->standard_cost);
                    label_cell($stock_item->required_date);
                    label_cell($stock_item->line_comment);
                    label_cell($stock_item->task_description);
                    label_cell($stock_item->project_site_description);

                    edit_button_cell("Edit$line_no", _("Edit"),
                            _('Edit document line'));
                    delete_button_cell("Delete$line_no", _("Delete"),
                            _('Remove line from document'));
                    end_row();
		}
		else
		{
			pr_edit_item_controls($order, $line_no);
		}
	}

	if ($id == -1)
		pr_edit_item_controls($order);

        $total = calculate_pr_total($order);
        $order->total = $total;
//        label_cells(text_bold("Total ".number_format($total,2)), "", "colspan=5 align=right");
        label_cell("Total Cost: ". spaces(2).text_bold(number_format($total,2)), "colspan=5 align=right");
        label_cell('',"colspan=6");
	//label_row(_("Total"), number_format2($total,user_price_dec()), "align=right colspan=5", "align=right", 2);

    end_table();
	div_end();
}

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

function pr_edit_item_controls(&$order, $line_no=-1)
{
	global $Ajax, $stock_types;
	start_row();

	$dec2 = 0;
        
        if(isset($_POST['LineNo']) && $_POST['LineNo'] >= 0){
            $id = $_POST['LineNo'];
        }
        else{
            $id = find_submit('Edit');
        }
        
	if ($line_no != -1 && $line_no == $id)
	{
            //stock_categories_list_cells(null, 'stock_category_id', $order->line_items[$id]->stock_category_id);
            $_POST['stock_id'] = $order->line_items[$id]->stock_id;
            $_POST['qty'] = $order->line_items[$id]->requested_qty;
            $_POST['tran_qty'] = qty_format($order->line_items[$id]->tran_qty,$order->line_items[$id]->stock_id, $dec);
            $_POST['units'] = $order->line_items[$id]->units;
            $_POST['estimate_price'] = $order->line_items[$id]->estimate_price;
            $_POST['required_date'] = $order->line_items[$id]->required_date;
            $_POST['line_comment'] = $order->line_items[$id]->line_comment;
            
            $_POST['task_id'] = $order->line_items[$id]->task_id;
            $_POST['project_site_id'] = $order->line_items[$id]->project_site_id;
             
            hidden('stock_id', $_POST['stock_id']);
            label_cell($_POST['stock_id']);
                        
//            if(!isset($_POST['item_description'])){
                $_POST['item_description'] = $order->line_items[$id]->item_description;
//            }
            
            if($order->line_items[$id]->descr_editable){
                text_cells('', 'item_description',null,30);
            }
            else{
                label_cell($order->line_items[$id]->item_description, 'nowrap');
                hidden('item_description', $order->line_items[$id]->item_description);
            }
            
            label_cell($stock_types[$order->line_items[$id]->mb_flag]);
            
	    $Ajax->activate('items_table');
	}
	else
	{
            //stock_categories_list_cells(null, 'stock_category_id');
//            stock_costable_items_list_cells(null, 'stock_id', null, false, true);
            stock_items_list_cells(null, 'stock_id', null, false, true, false, true);
		if (list_updated('stock_id')) {
			    $Ajax->activate('units');
			    $Ajax->activate('qty');
                            $Ajax->activate('tran_unit');
                            $Ajax->activate('tran_qty');
		}

            $item_info = get_stock_item_edit_info($_POST['stock_id']);
            $dec = $item_info['decimals'];
            $_POST['qty'] = number_format2(0, $dec);
            $_POST['units'] = $item_info["units"];
            $_POST['issued_qty'] = number_format2(0, $dec);
//                $_POST['line_required_date'] = $_POST['required_date'];
                $_POST['line_comment'] = "";
                
            label_cell(isset($item_info["mb_flag"])?$stock_types[$item_info["mb_flag"]]:'');
                
        }
        
	qty_cells(null, 'tran_qty', null, null, null, $dec);
        
        if ($line_no != -1 && $line_no == $id)
	{
            $tran_unit = $order->line_items[$id]->tran_unit;
//            $_POST['std_cost'] = $_POST['std_cost'];
            if($tran_unit == ""){
                label_cell($order->line_items[$id]->units);
            }
            else{
                label_cell($order->line_items[$id]->tran_unit);
            }
        }
        else{
            units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
        }
        hidden('qty', $_POST['qty']);
        hidden('units', $_POST['units']);

//        amount_cells(null, 'estimate_price', null, null, null, 2);
        amount_cells(null, 'estimate_price');
        date_cells('', 'required_date');
        
        text_cells('', 'line_comment',null,30);
        tasks_list_cells(null, 'task_id', $_POST['project_id'], null, _('Select a budget'));
//        tasks_list_cells(null, 'task_id', 33, null, _('Select a budget'));
        project_sites_list_cells(null, 'project_site_id', $_POST['project_id'], null,'');
	//label_cell("&nbsp;");

	if ($id != -1)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $line_no);
 		set_focus('qty');
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2",
		    _('Add new item to document'), true);
	}

	end_row();
}


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

function pr_options_controls()
{
	  echo "<br>";
	  start_table();

	  textarea_row(_("Memo"), 'memo_', null, 50, 3);

	  end_table(1);
}


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

?>