<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_REOPEN_SALES_ORDERS';
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/approval_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
//include_once($path_to_root . "/payroll/includes/payroll_db.inc");

include_once($path_to_root . "/sales/includes/db/reopen_sales_quotations_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();
}

page(_($help_context = "Reopen Sales Quotations"));

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

//return;


if (isset($_GET['AddedID'])) 
{
	$trans_no = $_GET['AddedID'];
	$trans_type = ST_SALESORDER;
        
    display_notification_centered(sprintf( _("Sales Quotation # %d has been reopened."),$trans_no));
    
    display_note(sprintf( _("Sales Quotation # %d has been reopened."),$trans_no),0,2);
        
//
//	display_note(print_document_link($trans_no, _("&Print This Payslips"), true, $trans_type), 0, 0);

	display_footer_exit();
}

function can_reopen_sq($order_no)
{
    $result = get_sqs_for_reopen($order_no);
    $so = db_fetch($result);
    if(!$so){
        $msg = "Sales Quotation $order_no has been updated by another user";
        display_error($msg);
        return false;
    }
    
    return true;
}


function reopen_sales_order_work_orders($so_no)
{
    $messages = array();
    
    $result = get_sales_order_work_orders($so_no);
    while ($myrow = db_fetch($result)){
        if($myrow["closed"] == 1){
            $messages[] = array("type"=>E_WARNING, "message"=>"Could not reopen workorder ".$myrow["id"]." and it's status is Closed");
        }
        elseif($myrow["approval_status"] == AS_REOPENED){
            $messages[] = array("type"=>E_WARNING, "message"=>"No need to reopen workorder ".$myrow["id"]." and it's status is Reopned");
        }
        elseif($myrow["approval_status"] == AS_REJECTED){
            $messages[] = array("type"=>E_WARNING, "message"=>"Could not reopen workorder ".$myrow["id"]." and it's status is Rejected");
        }
        elseif($myrow["approval_status"] == AS_APPROVED || $myrow["approval_status"] == AS_REOPENED){                    
            $wo['wo_project_id'] = $myrow['project_id'];
            $wo['wo_id'] = $myrow['id'];

            //get_work_order_estimated_material_cost($myrow['wo_id']);
            $wo['wo_total'] = 0; // Set workorder value to zero as the person reopening the sales order may not have sufficient permission to reopne work order
            $wo['wo_released'] = $myrow['released'];
            $wo['wo_row_state'] = $myrow['row_state'];

            $current_user_id = $_SESSION['wa_current_user']->user;
            $change_type = "REOPEN";
            $cwoas = change_work_order_approval_status($wo, $change_type, $current_user_id);
            if($cwoas['success'] === true){
                $messages[] = array("type"=>E_NOTICE, "message"=>"Workorder ".$myrow["id"]." has been Reopened");
            }
            else{
                $cwoas['message'] = "Workorder ".$wo['wo_id']." - ".$cwoas['message'];
                return $cwoas;
            }
        }
        elseif($myrow["id"] < 0){
            $messages[] = array("type"=>E_WARNING, "message"=>"Could not reopen workorder ".$myrow["id"]." and it's status is Draft");
        }
        else{
            $messages[] = array("type"=>E_WARNING, "message"=>"Could not reopen workorder ".$myrow["id"]." and it is not yet approved");
        }
    }
    
    return array("success" => true, "message" =>$messages);
    
}

function reopen_approved_sq($sq_no){
        
    if(!can_reopen_sq($sq_no)){
        return;
    }
    
    $sq_header = get_sales_order_header($sq_no, ST_SALESQUOTE);
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    begin_transaction();
    $rad_msg = direct_reopen_sales_quotation($sq_header, $current_user_id);
//    $rad_msg = reopen_approved_document(ST_SALESORDER, $so_no, $so_header['project_id'], 
//                        $so_header['next_approval_group_id'], $current_user_id, $so_header['row_state'],
//                        $so_header['created_by']);
    
    if($rad_msg['success'] !== true){
        cancel_transaction();
        display_error($rad_msg['message']);
    }

    commit_transaction();

    meta_forward($_SERVER['PHP_SELF'], "AddedID=$sq_no");
    
}

if(isset($_POST['reopen_sq'])){

    reopen_approved_sq($selected_id);
    
    $selected_id = -1;
}
//--------------------------------------------------------------------------------------------------

if (!@$_GET['popup'])
	start_form();


br();	

   // $result = get_payroll_runs();
    $result = get_sqs_for_reopen(); 
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no Sales Quotations to Reopen."));
    }
    else
    {
        start_table(TABLESTYLE, "width=80%");

		$th = array(_("Id"), _("Reference"), _("Supplier"),
                        _("Location"), //_("Supplier's Reference"),
                        _("Order Date"),_("Currency"),
                        _("Order Total"),"");

        table_header($th);

        $k = $j = 0; //row colour counter

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            label_cell($myrow["order_no"]);
            label_cell($myrow["reference"]);
            label_cell($myrow["customer_name"]);
            label_cell($myrow["location_name"], "align=center");
//            label_cell($myrow["requisition_no"], "align=center");
            label_cell(sql2date($myrow["ord_date"]), "align=center");
            label_cell($myrow["curr_code"], "align=center");

            amount_decimal_cell($myrow["OrderValue"], "align=center");

//            label_cell($myrow["approval_status"]);
            //label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");

            select_button_cell("Edit".$myrow['order_no'], _("Select"), _("Select this PO to reopen"));

            //label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                                

            end_row();

            $j++;
            If ($j == 25)
            {
            	$j = 1;
        	table_header($th);
            } //end of page full new headings
        } //end of while loop

        end_table();
    }
    div_end();

//-----------------------------------------------------------------------------------------------
    $_POST['order_no'] = 0;
    $_POST['reference'] = "";
    $_POST['supp_name'] = "";
    $_POST['location_name'] = "";
    $_POST['requisition_no'] = 0;
    $_POST['ord_date'] = 0;
    $_POST['curr_code'] = 0;
    
$dec2 = 6;
if ($Mode =='Edit' && $selected_id > 0)
{
    $myrow = get_po_header($selected_id);

    $_POST['order_no'] = $myrow["order_no"];
    $_POST['reference'] = $myrow["reference"];
    $_POST['supp_name'] = $myrow["supp_name"];
    $_POST['location_name'] = $myrow["location_name"];
    $_POST['requisition_no'] = $myrow["requisition_no"];
    $_POST['ord_date'] = sql2date($myrow["ord_date"]);
    $_POST['curr_code'] = $myrow["curr_code"];
    
    hidden('id', $_POST['order_no']);    
}

br();

hidden('selected_id', $selected_id);

if($selected_id > 0){
    start_table(TABLESTYLE2);
    
    label_row("Id:", $_POST['order_no']);
    label_row("Reference:", $_POST['reference']);
    label_row(_("Supplier Name:"), $_POST['supp_name']);
    label_row(_("Location:"), $_POST['location_name']);
    label_row(_("Order Date:"), $_POST['ord_date']);
    label_row(_("Currency:"), $_POST['curr_code']);

    end_table(1);
    
    submit("reopen_sq", "Reopen Sales Quotation" );


    end_table(1);
    br();
   // submit_add_or_update_center($selected_id == -1, '', 'both');
}


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