<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <title>ISC Historical Bulletins</title>
    <link rel="icon" href="/images/favicon.ico" type="image/ico"/>
    <link rel="stylesheet" type="text/css" href="/css/iscschema.css"> <!-- /html -->
    <link rel="stylesheet" type="text/css" href="/css/main.css"/> <!-- /html -->
</head>

<div id="container">

<?php
$home = getenv('WEB');
#home=$_ENV['WEB'];
set_include_path("$home/html/include");
// Works in all PHP versions
ini_set('include_path', "$home/html/include");
include ('include/dbconnect.php');
include ('header.php');

?>

<div id="maingeneral" style= "width:970px;">
    <div id="content" style= "width:990px;">
        <div id="refmanst2-res" style= "width:950px; padding:10px 10px 30px 10px;" >
            <?php
            
            $town_val = preg_replace('/\D/', '', $_GET['townid']);
            
            $tscmd = pg_query("SELECT town FROM isc.reference WHERE townid = $town_val AND SCAN IS NOT NULL GROUP BY town");
            
            $c = 0;
            while ($row = pg_fetch_array($tscmd)){
                if($c !=0){
                    $towns .= ", " . $row["town"];  //Check for multiple town names, and comma seperate them accordingly.
                } else { $towns = $row["town"]; }
                $c++;
            }
            if (empty($towns)){
                echo "<b>Warning: incorrect dsid</b> <br><br>"; 
            }else{
                echo "<h3 align='center'><strong>Bulletins from $towns</strong></h3>";
                echo "<p> Download bulletin scans by clicking on their associated hyperlinks in the file column. Some bulletin scans span multiple years, and have large file sizes as a result.";
                $cmd = pg_query("SELECT DISTINCT publication FROM isc.reference WHERE townid = '$town_val' AND scan IS NOT NULL");
            }
            //$pub  = str_replace("'","''",$pub);
            
    //             $cmdloc = pg_query("SELECT address,town,region,country,other,type,gmtoffset,amptype,ampunits
    //                     FROM isc.reference
    //                     WHERE townid = '$town_val'");
    //                     
    //             $resultloc = pg_fetch_array($cmdloc);
    //             $address   = $resultloc['address'];
    //             $town      = $resultloc['town'];
    //             $region    = $resultloc['region'];
    //             $country   = $resultloc['country'];
    //             $other     = $resultloc['other'];
    //             $type      = $resultloc['type'];
    //             $gmtoffset = $resultloc['gmtoffset'];
    //             $amptype   = $resultloc['amptype'];
    //             $ampunits  = $resultloc['ampunits'];

                # Collect all those years that has been published
                $cmdYear = pg_query("select distinct year from isc.reference
                    where townid = '$town_val'
                    order by 1");
                ?>
                <table style="width:930px;">
                    <tr>
                        <th>Year</th>
                        <th>Jan</th>
                        <th>Feb</th>
                        <th>Mar</th>
                        <th>Apr</th>
                        <th>May</th>
                        <th>Jun</th>
                        <th>Jul</th>
                        <th>Aug</th>
                        <th>Sep</th>
                        <th>Oct</th>
                        <th>Nov</th>
                        <th>Dec</th>
                        <th>File</th>
                        <th>Size</th>
                    </tr>
                    <?php
                    # For all the years available returns all months:
                    #   green and refid if exists
                    #   red cross if it doesn't
                    $yyyy = "";
                    while($resultYear = pg_fetch_array($cmdYear)){
                        $year  = $resultYear['year'];
                        $boxes = boxes($town_val,$year);
                        echo $boxes;
                    }
                    ?>
                </table>
                <br/><br/>
        <?php

        #
        # Returns green or red for those time periods covered by
        # the reference as well as the refid to that period.
        # Period could be 1 month, several months or years.
        #
        function boxes($town_val,$year){

            # Select everything for a year
            $cmdMonth = pg_query("SELECT refid,startmonth,endmonth,other,scan, REPLACE(filename, '/export/internal-website/html/iscscans', '/printedStnBulletins') AS filename ,filesize FROM isc.reference
            WHERE townid = '$town_val'
            AND year = '$year'
            AND scan IS NOT NULL
            ORDER BY refid");

            $yes = "<img src=\"images/yesS.png\">"; # Reference exists
            $no  = "<img src=\"images/noS.png\">";  # Reference doesn't exist
            while($resultMonth = pg_fetch_array($cmdMonth)){
            
                $smonth = $resultMonth['startmonth'];
                $emonth = $resultMonth['endmonth'];
                $refid  = $resultMonth['refid'];
                $other  = $resultMonth['other'];
                $scan = $resultMonth['scan'];
                $filename = $resultMonth['filename'];
                
                
                if($resultMonth['filesize'] == NULL){
                    $filesize = filesize($filename);
                    $sqlup = "UPDATE isc.reference SET filesize = $filesize WHERE refid = $refid";
                    $x = pg_query($sqlup);
                }else{
                    $filesize = number_format($resultMonth['filesize']/100000, 2) . "MB";
                }
                
                #  one year with starting and ending month
                if(empty($other) and isset($emonth)){
//         echo "A ";
                    for ($j=1; $j<=12; $j++){
                        if ($j >= $smonth and $j <= $emonth){
                            $box[$year][$j] = "$yes";
                        }
                    }
                    # Just one month of data
                }elseif(empty($other) and empty($emonth)){
//         echo "B ";
                    for ($j=1; $j<=12; $j++){
                        if ($j == $smonth){
                            $box[$year][$j] = "$yes";
                        }
                    }
                }
                # When there is a time period of years
                if(isset($other) and preg_match("/\+/", $other)){
                    $lastmonth = substr($other,1,2);
                    $lastyear  = substr($other,4,8);
                    # Just one extra year
                    if ($lastyear == $year + 1){
//             echo "C ";
                        # Months in between
                        for ($j=1; $j<=12; $j++){
                            if ($j >= $smonth ){
                                $box[$year][$j] = "$yes";
                            }
                        }
                        # months of the last year
                        for ($j=1; $j<=$lastmonth; $j++){
                            if ($j <= $lastmonth){
                                $box[$lastyear][$j] = "$yes";
                            }
                        }
                        # For more than 1 year
                    }else{
//                 echo "D ";
                        # all the months in between
                        for ($j=1; $j<=12; $j++){
                            if ($j >= $smonth ){
                                $box[$year][$j] = "$yes";
                            }
                        }
                        # All the years in between
                        for ($y = $year +1; $y <= $lastyear -1; $y++){
                            for ($j=1; $j<=12; $j++){
                                $box[$y][$j] = "$yes";
                            }
                        }
                        # months of the last year
                        for ($j=1; $j<=$lastmonth; $j++){
                            if ($j <= $lastmonth){
                                $box[$lastyear][$j] = "$yes";
                            }
                        }
                    }
                    # Other time periods smaller than years
                }else{
                    # Just one year with starting and ending month
                    if(isset($emonth)){
//             echo "E ";
                        for ($j=1; $j<=12; $j++){
                            if ($j >= $smonth and $j <= $emonth){
                                $box[$year][$j] = "$yes";
                            }
                        }
                        # Just one month of data
                    }elseif(empty($emonth)){
//             echo "F ";
                        for ($j=1; $j<=12; $j++){
                            if ($j == $smonth){
                                $box[$year][$j] = "$yes";
                            }
                        }
                    } else { $box = null; }
                }
            }
            
            # Return rows of information
            $boxes = "";
            
            foreach ((array)$box as $year => $value) {     //this line will throw errors when box is uninitilized :( but still works as intended, initializing box breaks it. 
                $boxes .= "<tr>\n";
                $boxes .= "<th>$year</th>";
                for ($m=1; $m<=12; $m++){
                    if(isset($box[$year][$m])){
                        $val = $box[$year][$m];
                        $boxes .=  "<td>$val</td>";
                    }else{
                        $boxes .=  "<td>$no</td>";
                    }
                }
                
                $rowresult = pg_query("SELECT DISTINCT ON (scan) * FROM isc.reference
                WHERE townid = '$town_val'
                AND year = '$year'
                AND scan IS NOT NULL");
                
                $srows = pg_num_rows($rowresult);
                $scanList = '';
                $filesizes = '';
                
                if($srows > 1){ //if more than one bulletin for the year
                    while($rScans = pg_fetch_array($rowresult)){ //gets each scan and size for the year
                    $rPath  = addslashes(str_replace("/export/internal-website/html/iscscans","/printedStnBulletins",$rScans['filename']));
                    $rFile  = $rScans['scan'];
                        if($rScans['filesize'] == NULL){             //writes filesize to db if the file doesnt have one
                            $filesize = filesize($filename);
                            $sqlup = "UPDATE isc.reference SET filesize = $filesize WHERE refid = $refid"; 
                            $x = pg_query($sqlup);
                        }
                        $rSize  = number_format($rScans['filesize']/100000, 2) . "MB";
                        $scanList .= "<code><a href='$rPath'>$rFile</a></code>\n";
                        $filesizes .= "$rSize\n";
                    }
                    $boxes .= "<td>$scanList</td><td>$filesizes</td></tr>\n";
                }else{
                    $boxes .= "<td><code><a href=$filename>$scan</a></code></td><td>$filesize</td></tr>\n";
                } 
            }
            //unset($value);
            return ($boxes); 
        }
        ?>
        <a href="index.php">
        <button style="float: right; position:relative; right:20px;" >Return to town map</button></a>
        </div>    
    </div>
</div>
<?php include ('footer.php')?>
</html>





