<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_INSURED_ITEMS';
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 . "/finance/includes/db/insured_items_db.inc");
include_once($path_to_root . "/finance/includes/db/credit_facilities_db.inc");

include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_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 = "Insured Item"));

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

simple_page_mode(true);

$insured_item_id = -1;

if (isset($_GET['id']))
{
	$_POST['insured_item_id'] = $_GET['id'];
}
if (isset($_POST['insured_item_id']) && $_POST['insured_item_id'] > 0)
{
	$insured_item_id = $_POST['insured_item_id'];
}

if (isset($_GET['AddedID'])) 
{
	//return;
        
    $trans_no = $_GET['AddedID'];
//	$trans_type = ST_MATERIAL_REQ;

    $msg = get_session_variable('INSURED_ITEM_messages');
    clear_session_variable('INSURED_ITEM_messages');
        
	display_notification($msg);
	
//    display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Material Requisition")));
//    
//    hyperlink_params("$path_to_root/inventory/material_requisitions.php", _("Edit this Material Requisition"), "ModifyMRNumber=$trans_no");
//        
////    br();
//
////	display_note(print_document_link($trans_no, _("&Print this Material Requisition"), true, $trans_type), 0, 0);
//
	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &another insured item"));
//
////	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
//        
//    clear_session_variable('mr_messages');

	display_footer_exit();
}


function check_data($insured_item_id)
{	
    if(!(strlen($_POST['description']) > 0))
    {
        display_error( _("Description can not be empty."));
        set_focus('description');
        return false;
    }
    
    if(!(strlen($_POST['name']) > 0))
    {
        display_error( _("Policy number can not be empty."));
        set_focus('name');
        return false;
    }
    
    if(!($_POST['insurer_id'] > 0)){
        if($_POST['insurer_type'] > 0){
            $msg = "Please select a Customer";            
        }
        else{
            $msg = "Please select a Supplier";
        }
        display_error($msg);
        set_focus('insurer_id');
        return false;
    }
    
    switch (get_post('insuree_type')){
        case INSU_REFERENCE:
            if(!(strlen($_POST['insuree']) > 0)){
                display_error("Insuree can not be empty");
                set_focus('insuree');
                return false;
            }
            break;
        case INSU_VEHICLE:  
        case INSU_ASSET:
            if(!($_POST['insuree'] > 0)){
                display_error("Insuree can not be empty");
                set_focus('insuree');
                return false;
            }
            break;
        case INSU_EMPLOYEE:
        case INSU_ITEM:
            if(!(strlen($_POST['insuree']) > 1)){
                display_error("Insuree can not be empty");
                set_focus('insuree');
                return false;
            }
            break;
        case INSU_CUSTOMER:
            if(!($_POST['insuree'] > 0)){
                display_error("Insuree can not be empty");
                set_focus('insuree');
                return false;
            }
            break;
        default:
            break;
    }
                     

    
    
    if(!($_POST['policy_type_id'] > 0)){
        
        display_error("Please select the Policy Type");
        set_focus('policy_type_id');
        return false;
    }
    
    if (!(input_num('insured_amount') > 0))
    {
        display_error( _("Sum insured has to be numeric and positive."));
        set_focus('insured_amount');
        return false;
    }
    
    if (!(input_num('premium') > 0))
    {
        display_error(_("Premium has to be numeric and positive."));
        set_focus('premium');
        return false;
    }    
    
    if(!is_date($_POST['start_date']))
    {
        display_error(_("Start date is not a valid date"));
        set_focus('start_date');
        return false;
    }
    
    if(!is_date($_POST['renewal_date']))
    {
        display_error(_("Renewal Date is not a valid date"));
        set_focus('renewal_date');
        return false;
    }
    
    if(!is_date($_POST['last_renewed_on']))
    {
        display_error(_("Last Renewed On date is not a valid date"));
        set_focus('last_renewed_on');
        return false;
    }
    
    

    
    
    
    if($insured_item_id > 0){
        $insured_item = get_insured_item($insured_item_id);

        if($insured_item['expired'] == 1){

            display_error("This insured item is expired. It can not be updated.");
            return false;
        }
    }
     
    return true;    
}


function can_renew_insured_item($insured_item_id)
{
    $insured_item = get_insured_item($insured_item_id);
    if($insured_item['inactive'] == 1){
        
        display_error("This insured item is inactive. It can not be renewed.");
        return false;
    }
    
    if($insured_item['expired'] == 1){
        
        display_error("This insured item is expired. It can not be renewed.");
        return false;
    }

    return true;    
}


function can_delete_insured_item($selected_id)
{
    $result = get_insured_item_renewal_details($selected_id);
    if(db_num_rows($result) > 0){
        display_error(_("This insured item has renewals. It can not be deleted."));
        return false;
    }
    
    return true;
}


//function display_company_loans()
//{
//    $result = get_company_loans();
//    
//    div_start('price_table');
//    
//    if (db_num_rows($result) == 0)
//    {
//    	display_note(_("There are no active loans."));
//        return;
//    }
//
//    start_table(TABLESTYLE, "width=90%");
//
//    $th = array(_("id"),_("Credit Facility"),_("Bank"),_("Branch"),
//                        _("Loan Description"), _("Total Loan"),
//                        _("Installment"), _("Interest"),_("Start Date"), 
//                        _("Capital paid"), _("Interest Paid"), _("Last Pay. Date"), 
//                        _("On Hold"), _("Completed"), "", "");
//
//    table_header($th);
//
//    $k = $j = 0; //row colour counter
//
//    while ($myrow = db_fetch($result))
//    {
//        alt_table_row_color($k);
//
//        if($myrow['credit_facility_id'] > 0){
//            $credit_facility = get_credit_facility($myrow['credit_facility_id']); 
//            $credit_facility_name = $credit_facility['name'];
//            $banck_name = $credit_facility['bank_name'];
//            $branch_name = $credit_facility['branch_name'];
//        }
//        else{
//            $credit_facility_name = '';
//            $banck_name = $myrow['bank_name'];
//            $branch_name = $myrow['branch_name'];
//        }
//    
//    
//        label_cell($myrow["id"]);
//        label_cell($credit_facility_name);
//        label_cell($banck_name);
//        label_cell($branch_name);           
//        label_cell($myrow["loan_description"]);                      
//        label_cell(number_format($myrow["loan_amount"], 2), "align=right");
//        label_cell(number_format($myrow["installment_amount"], 2), "align=right");
//        label_cell(number_format($myrow["interest"], 2), "align=right");
//        label_cell(sql2date($myrow["start_date"]), "align=center");
//        label_cell(number_format($myrow["total_captal_paid"], 2), "align=right");
//        label_cell(number_format($myrow["total_interest_paid"], 2), "align=right");
//        
//        if(substr($myrow["last_payment_date"], 0, 4) == "0000"){
//            label_cell('');      
//        }
//        else{
//            label_cell(sql2date($myrow["last_payment_date"]), "align=center");
//        }
//
//        if($myrow["inactive"] == 1)
//            label_cell("Yes", "align=center");
//        else {
//            label_cell("No", "align=center");
//        }
//
//        if($myrow["completed"] == 1)
//            label_cell("Yes", "align=center");
//        else {
//            label_cell("No", "align=center");
//        }
//
//        edit_button_cell("Edit".$myrow['id'], _("Edit"));
//        delete_button_cell("Delete".$myrow['id'], _("Delete"));
//        end_row();
//
//        $j++;
//        If ($j == 12)
//        {
//            $j = 1;
//            table_header($th);
//        } //end of page full new headings
//    } //end of while loop
//
//    end_table();
//    
//    div_end();
//    
//}


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

    if (list_updated('credit_facility_id')){
        $Ajax->activate('price_table');
    }
    
    $Ajax->activate('insuree');
    
//    $Ajax->activate('insuree_reference');
//    $Ajax->activate('insuree_vehicle');
//    $Ajax->activate('insuree_asset');
//    $Ajax->activate('insuree_employee');
//    $Ajax->activate('insuree_customer');
        

    start_table(TABLESTYLE_NOBORDER);
    start_row();
    
    
    if($selected_id > 0)
    {
        $myrow = get_insured_item($selected_id);

        if(!isset($_POST['name'])){
        $_POST['id'] = $myrow["id"];
        $_POST['name'] = $myrow["name"];
        $_POST['description'] = $myrow["description"];
        $_POST['insurer_type'] = $myrow["insurer_type"];
        $_POST['insurer_id'] = $myrow["insurer_id"];
        $_POST['insuree_type'] = $myrow["insuree_type"];
        $_POST['insuree'] = $myrow["insuree"];
        $_POST['group_company_code'] = $myrow['company_code'];
//            $_POST['insuree_vehicle'] = $_POST['insuree'];
//            $_POST['insuree_asset'] = $_POST['insuree'];
//            $_POST['insuree_employee'] = $_POST['insuree'];
//            $_POST['insuree_customer'] = $_POST['insuree'];
        $_POST['insured_amount'] = $myrow["insured_amount"];          
        $_POST['premium'] = $myrow["premium"]; 
        
        $_POST['policy_type_id'] = $myrow["policy_type_id"]; 
//        if(!isset($_POST['start_date'])){
        $_POST['start_date'] = sql2date($myrow["start_date"]);
        $_POST['renewal_date'] = sql2date($myrow["renewal_date"]);
        $_POST['last_renewed_on'] = sql2date($myrow["last_renewed_on"]);
//        }

        $_POST['inactive'] = $myrow["inactive"];
        $_POST['expired'] = $myrow["expired"];  
        }
        
//        if(list_updated('insuree_type')){
//             $_POST['insuree_reference'] = $_POST['insuree'];
//            $_POST['insuree_vehicle'] = $_POST['insuree'];
//            $_POST['insuree_asset'] = $_POST['insuree'];
//            $_POST['insuree_employee'] = $_POST['insuree'];
//            $_POST['insuree_customer'] = $_POST['insuree'];
//        $_POST['insured_amount'] = $myrow["insured_amount"];   
//        }
        
    }
    else{
//        $_POST['id'] = 0;
//        $_POST['name'] = "";
//        $_POST['description'] = "";
//        $_POST['lc_amount'] = 0;
//        $_POST['bank_charge'] = 0;
//
//        $_POST['start_date'] = "";
//        $_POST['expiry_date'] = "";
//        
//        $_POST['payable_no_of_days'] = 0;
//        
//        $_POST['inactive'] = 0;
//        $_POST['expired'] = 0;
        
        if(!(isset($_POST['credit_facility_id']) && $_POST['credit_facility_id'] > 0)){
            $_POST['credit_facility_id'] = 0;
        }
    }
     
    
    text_row("Description :", "description", null, 50,200);
    text_row("Policy No :", "name", null, 50,100);
    
    yesno_list_row("Insurer Type :", "insurer_type", null, "Customer", "Supplier", true);
    if($_POST['insurer_type'] > 0){
        customer_list_row("Insurer :", 'insurer_id', null, "Select a Customer");        
    }
    else{
        supplier_list_row("Insurer :", 'insurer_id', null, "Select a Supplier");
    }
    
    insuree_types_list_row("Insuree Type :", "insuree_type", null, false, true);
    

//    hidden('insuree', $_POST['insuree']);
    
    $Ajax->activate('insuree');
    
    switch (get_post('insuree_type')){
        case INSU_REFERENCE:
//            unset($_POST['insuree']);
            hidden('group_company_code', "");
            text_row("Insuree :", "insuree", null, 50, 200);
            break;
        case INSU_VEHICLE:    
            hidden('group_company_code', "");
            vehicles_list_row("Insuree :", "insuree", null, '');
            break;
        case INSU_ASSET:
            hidden('group_company_code', "");
            asset_list_row("Insuree :", "insuree", null, '');
            break;
        case INSU_EMPLOYEE:
            group_companies_list_row("Company", 'group_company_code', null, false, true);
            group_company_employees_simple_list_row("Insuree :", "insuree", get_post('group_company_code'), null, 'Select an employee');
            break;
        case INSU_ITEM:
            hidden('group_company_code', "");
            start_row();
            label_cell(_("Component:"), "class='label'");
            echo "<td>";
            echo stock_items_list('insuree', null, false, true);
            echo "</td>";
            end_row();
            break;
        case INSU_CUSTOMER:
            
            customer_list_row("Insuree :", "insuree", null, '');
        default:
            break;
    }                 

    value_list_row("Policy Type:", 'policy_type_id', 'INSURANCE_POLICY_TYPES', null, 'Select a Policy Type', false);
    amount_row(_("Sum Insured :"),'insured_amount', null, null, null, 2);
    amount_row(_("Premium :"),'premium', null,null,null,2);

    date_row("Started Date :", "start_date");
    date_row("Last Renewed On :", "last_renewed_on");
    date_row("Next Renewal Date :", "renewal_date");
    
    
    textarea_row("Comment :", "comment", null, 35, 3);
    
    yesno_list_row("On Hold :", 'inactive');
    yesno_list_row("Expired :", 'expired');

    end_table(1);

    hidden('insured_item_id', $selected_id); 

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


function display_insured_items_renewal_controls($selected_id)
{      
    $_POST['renewed_on'] = $_POST['renewal_date'];
    
    start_table(TABLESTYLE_NOBORDER);        
        
        date_row("Next Renewal Date:", 'next_renewal_date');
        date_row("Renewed On:", 'renewed_on');
        amount_row("Amount:", 'amount', $_POST['premium']);
        text_row("Reference:", 'reference', null, 50, 10);
        textarea_row("Comment:", 'comment', null,  35, 3);            
    
    end_table();
 
   submit_center_first('RENEW_INSURED_ITEMS', _("Renew"), '', 'default');  
    
}

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


if(isset($_POST['RENEW_INSURED_ITEMS']) && can_renew_insured_item($insured_item_id)){
    
    begin_transaction();
    
    add_insured_item_renewal($insured_item_id, $_POST['next_renewal_date'], 
                                $_POST['renewed_on'], $_POST['amount'], $_POST['reference'], $_POST['comment']);
    
    $n3 = update_renewal_dates($insured_item_id, $_POST['next_renewal_date'], $_POST['renewed_on']);
    if($n3 == 1){
        commit_transaction();
        $selected_id = -1;
        $Mode = 'RESET';

        set_session_variable('INSURED_ITEM_messages', "Insured item ".$insured_item_id." has been renewed.");
        meta_forward($_SERVER['PHP_SELF'], "AddedID=".$insured_item_id);
    }
    else{
        cancel_transaction();
        display_error("Could not renew insured item ".$insured_item_id);
    }
    
 
}

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


if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($insured_item_id))
{
    if(isset($_POST['group_company_code']) && strlen($_POST['group_company_code']) > 0){
        $group_company_code = $_POST['group_company_code'];
    }
    else{
        $group_company_code = "";
    }
    
    if ($Mode == 'ADD_ITEM') 
    {
        $status = 'N';
        $insured_item_id = add_insured_item($_POST['name'], $_POST['description'], $_POST['insurer_type'], 
                                $_POST['insurer_id'], $_POST['insuree_type'], $group_company_code, $_POST['insuree'],
                                $_POST['policy_type_id'], input_num('insured_amount'), input_num('premium'), 
                                date2sql($_POST['start_date']), date2sql($_POST['renewal_date']),date2sql($_POST['last_renewed_on']), 
                                $_POST['comment'], $_POST['inactive'], $_POST['expired']);
        
        if($insured_item_id > 0){
            $selected_id = -1;
            $Mode = 'RESET';

            set_session_variable('INSURED_ITEM_messages', "Insured item ".$insured_item_id." has been added.");
            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$insured_item_id);
        }
        else{
            display_error(_("Could not add insured item."));
        }
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
        $status = 'U';
        $n1 = update_insured_item($insured_item_id, $_POST['name'], 
                            $_POST['description'], $_POST['insurer_type'], 
                            $_POST['insurer_id'], $_POST['insuree_type'], $group_company_code, $_POST['insuree'],
                            $_POST['policy_type_id'], input_num('insured_amount'), input_num('premium'), 
                            date2sql($_POST['start_date']), date2sql($_POST['renewal_date']),date2sql($_POST['last_renewed_on']), 
                            $_POST['comment'], $_POST['inactive'], $_POST['expired']);

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

            set_session_variable('INSURED_ITEM_messages', "Insured item ".$insured_item_id." has been updated.");
            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$insured_item_id);
        }
        else{
            display_error(_("Could not update insured item."));
        }
    }    
    $Mode = 'RESET';
}
//--------------------------------------------------------------------------------------------------

if($Mode == 'Delete' && can_delete_insured_item($selected_id))
{   
    delete_insured_item($selected_id);
    display_notification(_("The Selected Company Loan has been deleted."));
    $Mode = 'RESET';
}

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

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

start_form();

//start_table(TABLESTYLE2);
//company_loans_list_row("Company Loan :", 'compay_lc_id');
//end_table();

//display_company_loans();

$Ajax->activate('insured_item_edit_controls');

div_start('insured_item_edit_controls');

display_insured_item_edit_controls($insured_item_id);  
 
br();
   
if($insured_item_id > 0){
    display_insured_items_renewal_controls($insured_item_id);
}

  
div_end(); 

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


?>
