<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_GENERATE_PRODUCTION_SCHEDULE';
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 . "/payroll/includes/payroll_db.inc");

include_once($path_to_root . "/payroll/includes/payroll_calculation.inc");
include_once($path_to_root . "/manufacturing/includes/db/manufacturing_requirements_db.inc");
include_once($path_to_root . "/manufacturing/includes/db/production_schedule_db.inc");
include_once($path_to_root . "/manufacturing/includes/db/generate_production_schedule_db.inc");
include_once($path_to_root . "/jobq/includes/jobq_requests.inc");
include_once($path_to_root . "/manufacturing/includes/generate_production_schedule.inc");
include_once($path_to_root . "/manufacturing/includes/work_order_validations.inc");
include_once($path_to_root . "/manufacturing/includes/db/confirm_production_schedule_db.inc");
include_once($path_to_root . "/payroll/includes/db/shifts_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 = "Production Shedule Run"));

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

    
$run = false;

if(substr($selected_id, 0, 6) == "Select"){
    $selected_id = substr($selected_id, 6);
    $run = true;
}

//$calculate_summary = false;

//if(substr($selected_id, 0, 16) == "CalculateSummary"){
//    $selected_id = substr($selected_id, 16);
//    $calculate_summary = true;
//}

if (isset($_GET['AddedID'])) 
{
    $trans_no = $_GET['AddedID'];
    $trans_type = ST_PAYROLL;

    display_notification_centered("Request $trans_no has been submitted to job queue");


    display_footer_exit();
}


function check_data($Mode, $selected_id)
{	
    if (strlen($_POST['description']) < 1)
    {
        display_error( _("Description can not be empty."));
        set_focus('description');
        return false;
    }
    
    if (!is_date($_POST['period_start_date'])) 
    {
        display_error( _('Period start date is not a valid date'));
        set_focus('period_start_date');
        return false;
    }

    if (!is_date($_POST['period_end_date'])) 
    {
        display_error( _('Period end date is not a valid date'));
        set_focus('period_end_date');
        return false;
    }

    $ps = get_production_schedule_run($selected_id);
    if ($Mode=='UPDATE_ITEM' && $ps['run_by'] > 0)
    {
        display_error( _('This schedule has been run at least once and can not amend.'));
        set_focus('period_end_date');
        return false;
    }

    return true;
    
}
//--------------------------------------------------------------------------------------------------

if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($Mode, $selected_id))
{

    if ($Mode == 'ADD_ITEM') 
    {
            add_production_schedule($_POST['description'], 
                        date2sql($_POST['period_start_date']), date2sql($_POST['period_end_date']),
                        "N");
            
            display_notification(_("Production schedule has been added."));
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
            update_production_schedule($selected_id, $_POST['description'],
                        date2sql($_POST['period_start_date']), date2sql($_POST['period_end_date']),
                        "U");

            $selected_id = -1;
            display_notification(_("Production schedule been updated."));
    }
    $Mode = 'RESET';

}

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

if ($Mode == 'Delete')
{      
//    delete_production_schedule($selected_id);
//	display_notification(_("Production schedule has been sucessfully deleted."));
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}

if (isset($_POST['_selected_id_update']) )
{
	$selected_id = $_POST['selected_id'];
	$Ajax->activate('_page_body');
}

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

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

    
    generate_manufacturing_schedule($selected_id);
    
    
//        $parameters[] = array('payroll_run_id' => $selected_id, 'payroll_processing_type' => 'CALCULATE');
//        $parameters_json = json_encode($parameters);
//        
//        $submitted_by = $_SESSION['wa_current_user']->user;
//
//        $msg_cjr = create_jobq_request(350, $submitted_by, $parameters_json);
//        if($msg_cjr['passed'] == true){
//            update_payroll_run_joq_request_id($selected_id, (int)$msg_cjr['message']);
//            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$msg_cjr['message']);
//        }
//        else{
//            display_error($msg_cjr['message']);
//        }
//    
//    
        $selected_id = -1;
}

//if (isset($_POST['calculate_summary']) )
//{
//
//        $upli = update_payroll_link_id($selected_id);
//
//        if($upli == 1){
//            $parameters[] = array('payroll_run_id' => $selected_id, 'payroll_processing_type' => 'CALCULATE_SUMMARY');
//            $parameters_json = json_encode($parameters);
//
//            $submitted_by = $_SESSION['wa_current_user']->user;
//
//            $msg_cjr = create_jobq_request(ST_PAYROLL, $submitted_by, $parameters_json);
//            if($msg_cjr['passed'] == true){
//                update_payroll_run_joq_request_id($selected_id, (int)$msg_cjr['message']);
//                meta_forward($_SERVER['PHP_SELF'], "AddedID=".$msg_cjr['message']);
//            }
//            else{
//                display_error($msg_cjr['message']);
//            }
//
//
//            $selected_id = -1;
//        }
//}


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


br();	

    $result = get_production_schedules();
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no production shedule defined."));
    }
    else
    {
        start_table(TABLESTYLE, "width=80%");

		$th = array(_("Id"), _("Description"),
                        _("Period Start Date"), _("Period End Date"),
                        _("Status"), _("Run By"), "", "");

        table_header($th);

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

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

            label_cell($myrow["id"]);
            label_cell($myrow["description"]);
            label_cell(sql2date($myrow["period_start_date"]), "align=center");
            label_cell(sql2date($myrow["period_end_date"]), "align=center");          
            label_cell($myrow["production_schedule_status_name"]);
            label_cell($myrow["real_name"]);
            
            $s = $myrow["status"];
                    if($s == "N" || $s == "U"){
                        edit_button_cell("Edit".$myrow['id'], _("Edit"));
                        //delete_button_cell("Delete".$myrow['id'], _("Delete"));
                    }
                    else{
                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                        //label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    }
                                        
                    if($s == "N" || $s == "U" || $s == "C" || $s == "L"){
                        select_button_cell("EditSelect".$myrow['id'], _("Select"), _("Run Payroll"));
                    }
                    else{
                        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['id'] = 0; 
    $_POST['description'] = "";
    $_POST['period_start_date'] = 0;
    $_POST['period_end_date'] = 0;
    $_POST['tran_date'] = 0;
    
    $editable = true;
$dec2 = 6;
if ($Mode =='Edit')
{
    $myrow = get_production_schedule_run($selected_id);

   
    $_POST['id'] = $myrow["id"];    
    $_POST['description'] = $myrow["description"];
    $_POST['period_start_date'] = sql2date($myrow["period_start_date"]);
    $_POST['period_end_date'] = sql2date($myrow["period_end_date"]);
    
    hidden('id', $_POST['id']); 
    
    if($myrow['run_by'] > 0){
        $editable = false;
    }
}

br();

hidden('selected_id', $selected_id);



if($run == true || $editable == false){
    start_table(TABLESTYLE2);
    
   // label_row("Payroll Name:", $_POST['payroll_name']);
    label_row("Description:", $_POST['description']);
    label_row(_("Period Start Date:"), $_POST['period_start_date']);
    label_row(_("Period End Date:"), $_POST['period_end_date']);
    
    end_table(1);
    

    submit("run_production_schedule", "Run Production Schedule" );

}
//elseif($calculate_summary == true){
//    start_table(TABLESTYLE2);
//    
//    //label_row("Payroll Name:", $_POST['payroll_name']);
//    label_row("Description:", $_POST['description']);
//    label_row(_("Period Start Date:"), $_POST['period_start_date']);
//    label_row(_("Period End Date:"), $_POST['period_end_date']);
//    label_row(_("Transaction Date:"), $_POST['tran_date']);
//   // payroll_run_list_row("Linked Payroll Run:", 'linked_payroll_run_id', null, '');
//    
//    end_table(1);
//    
//
//    submit("calculate_summary", "Calculate Summary" );
//
//}
else{
    start_table(TABLESTYLE2);

   // value_list_row('Select Payroll:', 'payroll_id', 'PAYROLLS', $_POST['payroll_id']);
    text_row("Description:", "description", $_POST['description'], 50,200);
    date_row(_("Period Start Date:"), 'period_start_date');
    date_row(_("Period End Date:"), 'period_end_date');
    //date_row(_("Transaction Date:"), 'tran_date');
    


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





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