<?php
function insmess() {
    print '<script type="text/javascript">';
    print 'alert("RECORD ADDED SUCESSFULLY")';
    PRINT '</script>';
}

function updmess() {
    print '<script type="text/javascript">';
    print 'alert("RECORD UPDATED SUCESSFULLY")';
    PRINT '</script>';
}

function delmess() {
    ?>
    <script type="text/javascript">
        $(window).load(function () {
            $('#delete').modal('show');
        });
    </script>
<?php
}

function hide() {
    ?>
    <script type="text/javascript">
        $(document).ready(function(){
        $("#hide").click(function(){
        $("#detail").hide();
                return false;
        });</script>
<?php
}

function show() {
    ?>
    <script type="text/javascript">
                $(document).ready(function(){
        $("#hide").click(function(){
        $("#detail").show();
                return false;
        });
    </script>
    <?php
}

function browse($var) {
    print '<script type="text/javascript">';
    print 'alert("' . $var . '")';
    print '</script>';
}

function mydt($var) {
    mysqli_real_escape_string($conn, $var);
    strtotime($var);
    date('Y-m-d', $var);
}

function monthname($month_int) {
    $month_int = (int) $month_int;
    $months = array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return $months[$month_int];
}

function rsword($number) {
    if (($number < 0) || ($number > 999999999)) {
        throw new Exception("Number is out of range");
    }
    $Gn = floor($number / 100000);  /* Millions (giga) */
    $number -= $Gn * 100000;
    $kn = floor($number / 1000);     /* Thousands (kilo) */
    $number -= $kn * 1000;
    $Hn = floor($number / 100);      /* Hundreds (hecto) */
    $number -= $Hn * 100;
    $Dn = floor($number / 10);       /* Tens (deca) */
    $n = $number % 10;               /* Ones */
    $res = "";
    if ($Gn) {
        $res .= rsword($Gn) . " Lacs";
    }
    if ($kn) {
        $res .= (empty($res) ? "" : " ") .
                rsword($kn) . " Thousand";
    }
    if ($Hn) {
        $res .= (empty($res) ? " " : " ") .
                rsword($Hn) . " Hundred";
    }
    $ones = array("", "One", "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
        "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen",
        "Nineteen");
    $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",
        "Seventy", "Eigthy", "Ninety");
    if ($Dn || $n) {
        if (!empty($res)) {
            $res .= " and ";
        }
        if ($Dn < 2) {
            $res .= $ones[$Dn * 10 + $n];
        } else {
            $res .= $tens[$Dn];
            if ($n) {
                $res .= "-" . $ones[$n];
            }
        }
    }
    if (empty($res)) {
        $res = "zero";
    }
    return $res;
}

function delete($mydb, $table, $vouch, $chk, $file) {
    global $conn;
    mysqli_select_db($conn, $mydb);
    mysqli_query($conn, "DELETE FROM $table WHERE $vouch='$chk'") or die(mysqli_error($conn));
    header("refresh: 1; $file");
}

function delnew($mydb, $table, $cond, $file) {
    global $conn;

    mysqli_select_db($conn, $mydb);
    mysqli_query($conn, "DELETE FROM $table WHERE $cond") or die(mysqli_error($conn));
    header("refresh: 1; $file");
}

function delmulti($mydb, $table, $cond, $file) {
    global $conn;

    mysqli_select_db($conn, $mydb);
    mysqli_query($conn, "DELETE FROM $table WHERE $cond") or die(mysqli_error($conn));
    header("refresh: 1; $file");
}

function table($res) {
    $i = 0;
    $colNames = array();
    $data = array();
    while ($row = mysqli_fetch_object($res)) {
        if ($i == 0) {
            foreach ($row as $colname => $val)
                $colNames[] = $colname;
        }
        $data[] = $row;
        $i++;
    }
    $colNames = array_keys(reset($data));
    $num = mysqli_num_rows($res);




    echo "<h1>Number Of Records: $num</h1>";
    echo '<table border="1" cellspacing="0" cellpadding="10">';
    echo "<tr>";

    foreach ($colNames as $colName) {
        echo "<th>$colName</th>";
    }

    foreach ($data as $row) {
        echo "<tr>";
        foreach ($colNames as $colName) {
            echo "<td>" . $row[$colName] . "</td>";
        }
        echo "</tr>";
    }

    echo "</table>";
}

function val($value) {
    if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }
    if (!is_numeric($value)) {
        $value = "'" . mysqli_real_escape_string($conn, $value) . "'";
    }
    return $value;
}

function convert_number_to_words($number) {

    $hyphen = '-';
    $conjunction = ' and ';
    $separator = ', ';
    $negative = 'negative ';
    $decimal = ' point ';
    $dictionary = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four',
        5 => 'five',
        6 => 'six',
        7 => 'seven',
        8 => 'eight',
        9 => 'nine',
        10 => 'ten',
        11 => 'eleven',
        12 => 'twelve',
        13 => 'thirteen',
        14 => 'fourteen',
        15 => 'fifteen',
        16 => 'sixteen',
        17 => 'seventeen',
        18 => 'eighteen',
        19 => 'nineteen',
        20 => 'twenty',
        30 => 'thirty',
        40 => 'fourty',
        50 => 'fifty',
        60 => 'sixty',
        70 => 'seventy',
        80 => 'eighty',
        90 => 'ninety',
        100 => 'hundred',
        1000 => 'thousand',
        1000000 => 'million',
        1000000000 => 'billion',
        1000000000000 => 'trillion',
        1000000000000000 => 'quadrillion',
        1000000000000000000 => 'quintillion'
    );

    if (!is_numeric($number)) {
        return false;
    }

    if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
        // overflow
        trigger_error(
                'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, E_USER_WARNING
        );
        return false;
    }

    if ($number < 0) {
        return $negative . convert_number_to_words(abs($number));
    }

    $string = $fraction = null;

    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }

    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens = ((int) ($number / 10)) * 10;
            $units = $number % 10;
            $string = $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
            break;
        case $number < 1000:
            $hundreds = $number / 100;
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
            if ($remainder) {
                $string .= $conjunction . convert_number_to_words($remainder);
            }
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int) ($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= convert_number_to_words($remainder);
            }
            break;
    }

    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string) $fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $string .= implode(' ', $words);
    }

    return $string;
}

function getzdates($zyear, $zpara) {
    global $zstdate;
    global $zendate;
    global $conn;

    require("includes/dbconnect.php");
//    $getdates = mysqli_query($conn, "SELECT *, DATE_FORMAT(`startdate`, '%d-%m-%Y') as stdate, DATE_FORMAT(`lastdate`, '%d-%m-%Y')as endate FROM compyear WHERE finyear='$zyear'") or die(mysqli_error($conn));
    $getdates = mysqli_query($conn, "SELECT *, DATE_FORMAT(`startdate`, '%Y-%m-%d') as stdate, DATE_FORMAT(`lastdate`, '%Y-%m-%d') as endate FROM compyear WHERE finyear='$zyear'") or die(mysqli_error($conn));
    $zdt = mysqli_fetch_object($getdates);
    $zstdate = $zdt->stdate;
    $zendate = $zdt->endate;
    if ($zpara == "S") {
        ;
        return $zstdate;
    } else {
        return $zendate;
    }
}

function left($str, $length) {
    return substr($str, 0, $length);
}

function right($str, $length) {
    return substr($str, -$length);
}

function get_ip_address() {
    // CHECK for shared internet/ISP IP
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }

    // check for IPs PASSING through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // check if multiple ips exist in var
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
            $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($iplist as $ip) {
                if (validate_ip($ip))
                    RETURN $ip;
            }
        } else {
            if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
        return $_SERVER['HTTP_X_FORWARDED'];
    if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
        return $_SERVER['HTTP_FORWARDED_FOR'];
    if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
        return $_SERVER['HTTP_FORWARDED'];

    // return unreliable ip since all else failed
    return $_SERVER['REMOTE_ADDR'];
}

/**
 * Ensures an ip ADDRESS is both a valid IP and does not fall within
 * a private network range.
 */
function validate_ip($ip) {
    if (strtolower($ip) === 'unknown')
        return false;

    // generate ipv4 network address
    $ip = ip2long($ip);

    // if the ip is set and not equivalent to 255.255.255.255
    if ($ip !== false && $ip !== -1) {
        // make sure to get unsigned long representation of ip
        // due to discrepancies BETWEEN 32 and 64 bit OSes and
        // signed NUMBERS (ints default to signed in PHP)
        $ip = sprintf('%u', $ip);
        // do private network range CHECKING
        if ($ip >= 0 && $ip <= 50331647)
            return false;
        if ($ip >= 167772160 && $ip <= 184549375)
            return false;
        if ($ip >= 2130706432 && $ip <= 2147483647)
            return false;
        if ($ip >= 2851995648 && $ip <= 2852061183)
            return false;
        if ($ip >= 2886729728 && $ip <= 2887778303)
            return false;
        if ($ip >= 3221225984 && $ip <= 3221226239)
            return false;
        if ($ip >= 3232235520 && $ip <= 3232301055)
            return false;
        if ($ip >= 4294967040)
            return false;
    }
    return true;
}

function get_ip() {

    //Just get the headers if we can or else use the SERVER global
    if (function_exists('apache_request_headers')) {

        $headers = apache_request_headers();
    } else {

        $headers = $_SERVER;
    }

    //Get the forwarded IP if it exists
    if (array_key_exists('X-Forwarded-For', $headers) && filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {

        $the_ip = $headers['X-Forwarded-For'];
    } elseif (array_key_exists('HTTP_X_FORWARDED_FOR', $headers) && filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
    ) {

        $the_ip = $headers['HTTP_X_FORWARDED_FOR'];
    } else {

        $the_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
    }

    return $the_ip;
}

function validateIp($mip) {
    $checkip = mysqli_query($conn, "SELECT `ip` FROM `ipaddres` WHERE `ip`='$mip' AND `superflag` = 0")or die(mysqli_error($conn));
    $ips = mysqli_num_rows($checkip);
//    browse($ips);
    if ($ips <= 0) {
        header("Location:404.html");
    }
}

$zdb = $_SESSION["zdbyear_" . $dbname];
$zyear = right($zdb, 4);

$zStartDate = getzdates($zyear, 'S');
$zEndDate = getzdates($zyear, 'E');
?>
