<?php

include('accesscheck2.php');
require_once('Connections/courier.php');
if (!function_exists("GetSQLValueString")) {

    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
        if (PHP_VERSION < 6) {
            $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
        }

        $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

        switch ($theType) {
            case "text":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
            case "long":
            case "int":
            $theValue = ($theValue != "") ? intval($theValue) : "NULL";
            break;
            case "double":
            $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
            break;
            case "date":
            $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
            break;
            case "defined":
            $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
            break;
        }
        return $theValue;
    }

}
mysql_select_db($database_courier, $courier);
$action = $_POST["act"];
$id = $_POST['id'];

$userid = $_SESSION['myMM_Userid_investment'];
$branch_name = strtoupper(mysql_real_escape_string($_POST["branch_name"]));
$branch_code = $_POST["branch_code"];
$postal_address = $_POST["postal_address"];
$location = $_POST["branch_location"];
$city = $_POST["branch_city"];
$region = $_POST["region"];
$country = $_POST["country"];

if ($action == 'save_new_branch') {
    $query_insert = "INSERT INTO branches(branch_name,branch_code,postal_address,location,city,region,country,user_id) VALUES('$branch_name','$branch_code','$postal_address','$location','$city','$region','$country','$userid')";
    $rsinsert = mysql_query($query_insert, $courier) or die(mysql_error());

    if ($rsinsert == TRUE) {
        echo 'Success! New Branch Saved.@@@success@@@';
    } else {
        echo 'Oops! Failed to Save New Branch.@@@error@@@';
    }
    include('list_branches.php');
}

if ($action == "update_branch_details") {
    $update_records = "update branches set branch_name='$branch_name', branch_code='$branch_code',postal_address='$postal_address',location='$location',city='$city',region='$region', country='$country',user_id='$userid' WHERE id='$id'";
    $rsupdate_records = mysql_query($update_records, $courier) or die(mysql_error());

    if ($rsupdate_records == TRUE) {
        echo 'Success! Branch Details Updated.@@@success@@@';
    } else {
        echo 'Oops! Failed to Update Branch Details.@@@error@@@';
    }
    include('list_branches.php');
}

if ($action == 'save_new_user') {
    $title = $_POST['title'];
    $username = $_POST['username'];
    $password = md5($_POST['password']);
    $surname = $_POST['surname'];
    $othernames = $_POST['othernames'];
    $phone_number = $_POST['phone_number'];
    $security_level = $_POST['security_level'];
    $branch_id = $_POST['branch_id'];
    $branch_id_station = $_POST['branch_id_station'];
    $staff_id = $_POST['staff_id'];
    $email_address = $_POST['email_address'];
    $address = $_POST['address'];
    $perm_role = $_POST['perm_role'];
    $department_code = $_POST['department_code'];

    $insert_user = mysql_query("INSERT INTO users (firstnames,surname,username,password,email,tel,security,perm_role_id,staffid,branch_id,address,department_code,title,active_branch_id) VALUES('$othernames','$surname','$username','$password','$email_address','$phone_number','$security_level','$perm_role','$staff_id','$branch_id','$address', '$department_code','$title','$branch_id_station')");
    $id4 = mysql_insert_id();

    $query_rsodest = "delete from securitypermissions where user_id='$id4'";
    $rsodest = mysql_query($query_rsodest, $courier) or die(mysql_error());

    $query_rsodest_item = "SELECT * from security_roles_permissions where perm_role_id='$perm_role' order by securitylevel_id";
    $rsodest_item = mysql_query($query_rsodest_item, $courier) or die(mysql_error());
    $row_rsodest_item = mysql_fetch_assoc($rsodest_item);
    $totalRows_rsodest_item = mysql_num_rows($rsodest_item);

    do {
        $item = $row_rsodest_item['securitylevel_id'];
        $query_rsodest = "INSERT INTO `securitypermissions` (`id`, `user_id`, `securitylevel_id`, `perm_role_id`) VALUES (NULL, '$id4', '$item', '$perm_role');";
        $rsodest = mysql_query($query_rsodest, $courier) or die(mysql_error());
    } while ($row_rsodest_item = mysql_fetch_assoc($rsodest_item));

    if ($insert_user == TRUE) {
        echo 'Success! New User Added Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Add New User.@@@error@@@';
    }
    include('list_users.php');
}

if ($action == 'update_user_details') {
    $username = $_POST['username'];
    $password = md5($_POST['password']);
    $surname = $_POST['surname'];
    $othernames = $_POST['othernames'];
    $phone_number = $_POST['phone_number'];
    $security_level = $_POST['security_level'];
    $branch_id = $_POST['branch_id'];
    $branch_id_station = $_POST['branch_id_station'];
    $staff_id = $_POST['staff_id'];
    $email_address = $_POST['email_address'];
    $address = $_POST['address'];
    $perm_role = $_POST['perm_role'];
    $account_status = $_POST['account_status'];

    $update = mysql_query("UPDATE users SET username='$username',surname='$surname',firstnames='$othernames',email='$email_address',tel='$phone_number',security='$security_level',perm_role_id='$perm_role',staffid='$staff_id',branch_id='$branch_id',address='$address',account_status='$account_status',active_branch_id='$branch_id_station' WHERE id = '$id'");
    if (!empty($_POST['password'])) {
        mysql_query("UPDATE users SET password='$password' WHERE id = '$id'");
    }

    // $rsodest = mysql_query("delete from securitypermissions where user_id='$id'", $courier) or die(mysql_error());
    // $rsodest_item = mysql_query("SELECT * from security_roles_permissions where perm_role_id='$perm_role' order by securitylevel_id", $courier) or die(mysql_error());
    // $row_rsodest_item = mysql_fetch_assoc($rsodest_item);
    // $totalRows_rsodest_item = mysql_num_rows($rsodest_item);

    // do {
    //     $item = $row_rsodest_item['securitylevel_id'];
    //     $query_rsodest = "INSERT INTO `securitypermissions` (`id`, `user_id`, `securitylevel_id`, `perm_role_id`) VALUES (NULL, '$id', '$item', '$perm_role');";
    //     $rsodest = mysql_query($query_rsodest, $courier) or die(mysql_error());
    // } while ($row_rsodest_item = mysql_fetch_assoc($rsodest_item));

    if ($update == TRUE) {
        echo 'Success! User Details Updated Successfully.@@@success@@@';
    } else {
        echo 'Oops! Failed to Update Users Details.@@@error@@@';
    }
    include('list_users.php');
}

if($action == 'add_new_company'){ ?>
 <form role="form" class="form-horizontal" id="form_save_company_info">   
    <div class="form-body">
        <div class="form-group">
            <label class="col-md-4 control-label">Company Name</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <input required="" type="text" class="form-control" name="company_name" id="company_name"> 
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">Comapny Code</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <input required="" type="text" class="form-control" name="company_code" id="company_code"> 
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">Type</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <select required="" class="form-control" name="insurance_type" id="insurance_type">
                        <option value="insurance">Insurance</option>
                        <option value="company">Company</option>
                    </select> 
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">Contact Person</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <input type="text" class="form-control" name="contact_person" id="contact_person"> 
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">Address</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <input name="address" id="address" type="text" class="form-control"> 
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">Contact Tel.</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <input name="phone_no" id="phone_no" type="text" class="form-control"> 
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">How to Serve Clients</label>
            <div class="col-md-8">
                <div class="input-icon right">
                    <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                    <textarea row="3" name="serve_clients" id="serve_clients" class="form-control"></textarea>
                </div>
            </div>
        </div>

    </div>
</form>

<?php }

if($action =='save_new_company'){
    $company_name = $_POST['company_name'];
    $company_code = $_POST['company_code'];
    $type = $_POST['insurance_type'];
    $insuranceStatus = $_POST['insurance_status'];
    $address = $_POST['address'];
    $contact_person = $_POST['contact_person'];
    $phone_no = $_POST['phone_no'];
    $serve_clients = $_POST['serve_clients'];
    $id = $_POST['company_id'];

    

    if($id>0){
       $updateCompany = mysql_query("UPDATE insurance_company SET company_name='$company_name',company_code='$company_code',type='$type',status='$insuranceStatus',company_address='$address',company_tel='$phone_no',contact_person='$contact_person',serve_clients_info='$serve_clients' WHERE id='$id'");
       if($updateCompany){
        mysql_query("UPDATE `patient_information` SET `company_status` = '$insuranceStatus' WHERE `insurance_company1` = '$company_code'");
       }

       echo "success@@@Information Updated Successfully.@@@";
   }else{

    ////////////////////////////// Get existing Company and compare the name //////////////////////////////
    $companyInfo = mysql_num_rows(mysql_query("SELECT * FROM insurance_company WHERE company_name = '$company_name'"));
    if ($companyInfo > 0) {
        echo "error@@@Duplcate Name Found.@@@";
    }else{
        mysql_query("INSERT INTO insurance_company (company_name,company_code,type,company_address,company_tel,contact_person,status,serve_clients_info) VALUES('$company_name','$company_code','$type','$address','$phone_no','$contact_person','Active','$serve_clients')");
        echo "success@@@Information Saved Successfully.@@@";
    }
}

include("list_companies.php");
}

if($action == 'edit_company_info'){
    $id = $_POST['id'];
    $info = mysql_fetch_assoc(mysql_query("SELECT * FROM insurance_company WHERE id='$id'"));?>
    <form role="form" class="form-horizontal" id="form_save_company_info">   
        <div class="form-body">
            <div class="form-group">
                <label class="col-md-4 control-label">Company Name</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <input required="" type="text" class="form-control" name="company_name" id="company_name" value="<?php echo $info['company_name']; ?>"> 
                        <input type="hidden" name="company_id" id="company_id" value="<?php echo $info['id'];?>">
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">Comapny Code</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <input required="" readonly="" type="text" class="form-control" name="company_code" id="company_code" value="<?php echo $info['company_code']; ?>"> 
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">Type</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <select required="" class="form-control" name="insurance_type" id="insurance_type">
                            <option <?php if($info['type']=='insurance'){ echo 'selected=""';} ?> value="insurance">Insurance</option>
                            <option <?php if($info['type']=='company'){ echo 'selected=""';} ?>  value="company">Company</option>
                        </select> 
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">Status</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <select required="" class="form-control" name="insurance_status" id="insurance_status">
                            <option <?php if($info['status']=='Active'){ echo 'selected=""';} ?> value="Active">Active</option>
                            <option <?php if($info['status']=='Inactive'){ echo 'selected=""';} ?>  value="Inactive">Inactive</option>
                        </select> 
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">Contact Person</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <input type="text" class="form-control" name="contact_person" id="contact_person" value="<?php echo $info['contact_person']; ?>"> 
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">Address</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <input name="address" id="address" type="text" class="form-control" value="<?php echo $info['company_address']; ?>"> 
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">Contact Tel.</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <input name="phone_no" id="phone_no" type="text" class="form-control" value="<?php echo $info['company_tel']; ?>"> 
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label class="col-md-4 control-label">How to Serve Clients</label>
                <div class="col-md-8">
                    <div class="input-icon right">
                        <i class="fa fa-info-circle tooltips" data-original-title="Email address" data-container="body"></i>
                        <textarea row="3" name="serve_clients" id="serve_clients" class="form-control"><?php echo $info['serve_clients_info']; ?></textarea>
                    </div>
                </div>
            </div>

        </div>
    </form>

    <?php
}


if($action == 'change_password'){
    $id = $_POST['id'];
    $old_password = md5($_POST['old_password']);
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    $password = md5($new_password);

    $get_user_details = mysql_fetch_assoc(mysql_query("SELECT password FROM users WHERE id='$id'"));
    if($old_password !== $get_user_details['password']){
        echo  "<div class='alert alert-danger'>
        <strong>Error! </strong> Old Password is not correct. 
        </div>";
        exit;
    } if($new_password !== $confirm_password){
        echo "<div class='alert alert-danger'>
        <strong>Error! </strong>New and Confirm password provided do not match</div>";
        exit;
    }

    if(empty($_POST['old_password']) || empty($new_password) || empty($confirm_password)){
        echo "<div class='alert alert-danger'>
        <strong>Error! </strong>Please fill in all fields</div>";
        exit;
    }
    $sql = mysql_query("UPDATE users SET password='$password' WHERE id='$id'");
    echo "<div class='alert alert-success'>
    <strong>Smart! </strong>New password changed successfully</div>";
    exit;
}

if($action == "delete_insurance_company"){
    $id = $_POST['id'];
    mysql_query("DELETE FROM insurance_company WHERE id='$id'");
    include("admin_utilities/list_companies.php");
}