<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE);

//set_include_path('/data/application_files/php:' . get_include_path() . ':./lib:./includes');
 

 $ds = DIRECTORY_SEPARATOR;
 $path =  dirname(__FILE__) . "{$ds}..{$ds}vendor{$ds}";
 
 ///echo $path; exit;
 
set_include_path($path);


require_once 'Zend/Db.php';
require_once 'Zend/Db/Table.php';

require_once('../includes/core_handler.php');

ob_start();
$getargs = array(
	//we lock this down in the query
	'action' => array('filter'=>FILTER_SANITIZE_STRING),
	'bill_number' => array('filter'=>FILTER_SANITIZE_STRING),
	'author' => array('filter'=>FILTER_SANITIZE_STRING),
	'keyword' => array('filter'=>FILTER_SANITIZE_STRING),
	'staff'	=> array('filter'=>FILTER_SANITIZE_STRING),
    's' => array('filter'=>FILTER_SANITIZE_NUMBER_INT),
    'p'	=> array('filter'=>FILTER_SANITIZE_NUMBER_INT),
	'l'	=> array('filter'=>FILTER_SANITIZE_NUMBER_INT),
	'submit' => array( 'filter'=>FILTER_SANITIZE_STRING)
);

$MYGET = filter_input_array(INPUT_GET, $getargs);
$MYPOST = filter_input_array(INPUT_POST, $getargs);
$MYREQUEST = filter_var_array($_REQUEST, $getargs);


//not sure I'm going to need smarty here
$smarty = setupSmarty();
$options = setupDBO();

$smarty->assign('_GET', $MYGET);

//fetch an array of the bills we wish to update
//$bill =& DB_DataObject::factory('Bill');

$dbparams = array (
       'host'     => DB_HOST,
       'username' => DB_USER,
       'password' => DB_PASS,
       'dbname'   => DB_NAME
 );

$type=PDO::FETCH_OBJ;
$dbh = Zend_Db::factory('PDO_MYSQL', $dbparams);
Zend_Db_Table::setDefaultAdapter($dbh);

$hasData = false;

$billParams = getSqlTerms('bill_number');
$authParams = getSqlTerms('author');
$keywordParams = getSqlTerms('keyword');
$staffParams = getSqlTerms('staff');

$params = $billParams + $authParams + $keywordParams + $staffParams;
$paramsSqlSelect = "";
if (!empty($params)) {
    $paramsBillSelect = getSqlLikeStatement($billParams, 'bill_number');
    $paramsAuthorSelect = getSqlLikeStatement($authParams, 'author');
    $paramsKeywordSelect = getSqlLikeStatement($keywordParams, 'keyword');
    $paramsStaffSelect = getSqlLikeStatement($staffParams, 'staff');
    $paramsSqlSelect = $paramsBillSelect . $paramsAuthorSelect . $paramsKeywordSelect . $paramsStaffSelect;
}

if(isset($MYGET['s']) && !empty($MYGET['s'])) {
	$params += array(':department_id' => $MYGET['s']);
	$paramsSqlSelect = $paramsSqlSelect . " AND d.department_id = :department_id";
}

if(isset($MYGET['p']) && !empty($MYGET['p'])) {
	$params += array(':priority_id' => $MYGET['p']);
	$paramsSqlSelect = $paramsSqlSelect . " AND p.priority_id = :priority_id";
}

if(isset($MYGET['l']) && !empty($MYGET['l'])) {
	$params += array(':legsession_id' => $MYGET['l']);
	$paramsSqlSelect = $paramsSqlSelect . " AND l.legsession_id = :legsession_id";
}


//this query will pull all of the bills and duplicate them between the divisions
$query = "SELECT DISTINCT
        GROUP_CONCAT(CONCAT(s.first_name, ' ', s.last_name) SEPARATOR ', ') AS staff,
        b.*,
        p.name priority_name,
        l.name legsession_name
	FROM
		bill b
		LEFT JOIN priority p ON b.priority_id=p.priority_id
		LEFT JOIN bill_dept_rel bdr ON bdr.bill_id=b.bill_id
		LEFT JOIN department d ON bdr.department_id=d.department_id
		LEFT JOIN bill_staff_rel bsr ON b.bill_id=bsr.bill_id
		LEFT JOIN staff s ON bsr.staff_id=s.staff_id
		LEFT JOIN legsession l ON b.legsession_id = l.legsession_id
	WHERE
		bdr.is_deleted = 'N' AND
		b.is_deleted = 'N' AND
		b.is_active = 'Y' AND
		d.is_active = 'Y' AND
		d.is_deleted = 'N' AND
		bsr.is_deleted = 'N' AND
		s.is_deleted = 'N'
		$paramsSqlSelect
	GROUP BY bsr.bill_staff_rel_id
    ORDER BY b.bill_number";

    $billdata = $dbh->prepare($query);

    if (!$billdata) {
        echo "\nPDO::errorInfo():\n";
        print_r($dbh->errorInfo());
        exit;
    }

    $billdata->setFetchMode($type);


//echo $paramsSqlSelect;
//print_r($params);
//exit;

    $result = $billdata->execute($params);
	$results = $billdata->fetchAll();

    $bills = array();

foreach($results as $id => $row) {
    $bill['bill_id'] = $row->bill_id;
    $bill['create_date'] = $row->create_date;
    $bill['update_date'] = $row->update_date;
    $bill['bill_number'] = $row->bill_number;
    $bill['bill_author'] = $row->bill_author;
    $bill['bill_desc'] = $row->bill_desc;
    $bill['bill_edit_status'] = stripslashes($row->bill_edit_status);
    $bill['bill_pull_status'] = stripslashes($row->bill_pull_status);
    $bill['leginfo_url'] = $row->leginfo_url;
    $bill['legsession_id'] = $row->legsession_id;
    $bill['priority_id'] = $row->priority_id;
    $bill['notes'] = $row->notes;
    $bill['is_active'] = $row->is_active;
    $bill['is_deleted'] = $row->is_deleted;
    $bill['staff'] = $row->staff;
    $legsession_short1 = substr($row->legsession_name, 2, 2);
    $legsession_short2 = substr($row->legsession_name, 7, 2);
    $bill['legsession_shortconcat'] = $legsession_short1 ."".$legsession_short2;
    $bills[$row->bill_number] = $bill;
}


uksort($bills, 'strnatcasecmp');

$position =& DB_DataObject::factory('Document');
$position->orderBy("document.document_date ASC");


$position->find();

$positions = array();
while($position->fetch()) {
	$positions[$position->bill_id][] = $position->toArray();
}

$priority =& DB_DataObject::factory('Priority');
$priority->find();
$priorities = $priority->getAll();

$legsession =& DB_DataObject::factory('Legsession');
$legsession->find();
$legsessions = $legsession->getAll();

/*PDF USING MULTIPLE PAGES
* Originally created by: Carlos Jos� V�squez S�ez
* heavily modified so that it actually works by: jon Bertsch Nov 19, 2003

* NOTE: looping though doesn't work, the pdf overwrites itself. Had to
* go through one building type at a time. blahhhh. what a pain.
*/
session_start();
define('FPDF_FONTPATH','font/');
require('fpdf152/fpdf.php');


define("PAPERWIDTH", 210);
define("USABLEWIDTH", 190);
//require('fpdf.php');


class PDF extends FPDF
{
    var $flowingBlockAttr;

    function saveFont()
    {
        $saved = array();

        $saved[ 'family' ] = $this->FontFamily;
        $saved[ 'style' ] = $this->FontStyle;
        $saved[ 'sizePt' ] = $this->FontSizePt;
        $saved[ 'size' ] = $this->FontSize;
        $saved[ 'curr' ] =& $this->CurrentFont;

        return $saved;
    }

    function restoreFont( $saved )
    {
        $this->FontFamily = $saved[ 'family' ];
        $this->FontStyle = $saved[ 'style' ];
        $this->FontSizePt = $saved[ 'sizePt' ];
        $this->FontSize = $saved[ 'size' ];
        $this->CurrentFont =& $saved[ 'curr' ];

        if( $this->page > 0)
            $this->_out( sprintf( 'BT /F%d %.2f Tf ET', $this->CurrentFont[ 'i' ], $this->FontSizePt ) );
    }

    function newFlowingBlock( $w, $h, $b = 0, $a = 'J', $f = 0 )
    {
        // cell width in points
        $this->flowingBlockAttr[ 'width' ] = $w * $this->k;

        // line height in user units
        $this->flowingBlockAttr[ 'height' ] = $h;

        $this->flowingBlockAttr[ 'lineCount' ] = 0;

        $this->flowingBlockAttr[ 'border' ] = $b;
        $this->flowingBlockAttr[ 'align' ] = $a;
        $this->flowingBlockAttr[ 'fill' ] = $f;

        $this->flowingBlockAttr[ 'font' ] = array();
        $this->flowingBlockAttr[ 'content' ] = array();
        $this->flowingBlockAttr[ 'contentWidth' ] = 0;
    }

    function finishFlowingBlock()
    {
        $maxWidth =& $this->flowingBlockAttr[ 'width' ];

        $lineHeight =& $this->flowingBlockAttr[ 'height' ];

        $border =& $this->flowingBlockAttr[ 'border' ];
        $align =& $this->flowingBlockAttr[ 'align' ];
        $fill =& $this->flowingBlockAttr[ 'fill' ];

        $content =& $this->flowingBlockAttr[ 'content' ];
        $font =& $this->flowingBlockAttr[ 'font' ];

        // set normal spacing
        $this->_out( sprintf( '%.3f Tw', 0 ) );

        // print out each chunk

        // the amount of space taken up so far in user units
        $usedWidth = 0;

        foreach ( $content as $k => $chunk )
        {
            $b = '';

            if ( is_int( strpos( $border, 'B' ) ) )
                $b .= 'B';

            if ( $k == 0 && is_int( strpos( $border, 'L' ) ) )
                $b .= 'L';

            if ( $k == count( $content ) - 1 && is_int( strpos( $border, 'R' ) ) )
                $b .= 'R';

            $this->restoreFont( $font[ $k ] );

            // if it's the last chunk of this line, move to the next line after
            if ( $k == count( $content ) - 1 )
                $this->Cell( ( $maxWidth / $this->k ) - $usedWidth + 2 * $this->cMargin, $lineHeight, $chunk, $b, 1, $align, $fill );
            else
                $this->Cell( $this->GetStringWidth( $chunk ), $lineHeight, $chunk, $b, 0, $align, $fill );

            $usedWidth += $this->GetStringWidth( $chunk );
        }
    }

    function WriteFlowingBlock( $s )
    {
        // width of all the content so far in points
        $contentWidth =& $this->flowingBlockAttr[ 'contentWidth' ];

        // cell width in points
        $maxWidth =& $this->flowingBlockAttr[ 'width' ];

        $lineCount =& $this->flowingBlockAttr[ 'lineCount' ];

        // line height in user units
        $lineHeight =& $this->flowingBlockAttr[ 'height' ];

        $border =& $this->flowingBlockAttr[ 'border' ];
        $align =& $this->flowingBlockAttr[ 'align' ];
        $fill =& $this->flowingBlockAttr[ 'fill' ];

        $content =& $this->flowingBlockAttr[ 'content' ];
        $font =& $this->flowingBlockAttr[ 'font' ];

        $font[] = $this->saveFont();
        $content[] = '';

        $currContent =& $content[ count( $content ) - 1 ];

        // where the line should be cutoff if it is to be justified
        $cutoffWidth = $contentWidth;

        // for every character in the string
        for ( $i = 0; $i < strlen( $s ); $i++ )
        {

            // extract the current character
            $c = $s{ $i };

            // get the width of the character in points
            $cw = $this->CurrentFont[ 'cw' ][ $c ] * ( $this->FontSizePt / 1000 );

            if ( $c == ' ' )
            {

                $currContent .= ' ';
                $cutoffWidth = $contentWidth;

                $contentWidth += $cw;

                continue;

            }

            // try adding another char
            if ( $contentWidth + $cw > $maxWidth )
            {

                // won't fit, output what we have
                $lineCount++;

                // contains any content that didn't make it into this print
                $savedContent = '';
                $savedFont = array();

                // first, cut off and save any partial words at the end of the string
                $words = explode( ' ', $currContent );

                // if it looks like we didn't finish any words for this chunk
                if ( count( $words ) == 1 )
                {

                    // save and crop off the content currently on the stack
                    $savedContent = array_pop( $content );
                    $savedFont = array_pop( $font );

                    // trim any trailing spaces off the last bit of content
                    $currContent =& $content[ count( $content ) - 1 ];

                    $currContent = rtrim( $currContent );

                }

                // otherwise, we need to find which bit to cut off
                else
                {

                    $lastContent = '';

                    for ( $w = 0; $w < count( $words ) - 1; $w++)
                        $lastContent .= "{$words[ $w ]} ";

                    $savedContent = $words[ count( $words ) - 1 ];
                    $savedFont = $this->saveFont();

                    // replace the current content with the cropped version
                    $currContent = rtrim( $lastContent );

                }

                // update $contentWidth and $cutoffWidth since they changed with cropping
                $contentWidth = 0;

                foreach ( $content as $k => $chunk )
                {

                    $this->restoreFont( $font[ $k ] );

                    $contentWidth += $this->GetStringWidth( $chunk ) * $this->k;

                }

                $cutoffWidth = $contentWidth;

                // if it's justified, we need to find the char spacing
                if( $align == 'J' )
                {

                    // count how many spaces there are in the entire content string
                    $numSpaces = 0;

                    foreach ( $content as $chunk )
                        $numSpaces += substr_count( $chunk, ' ' );

                    // if there's more than one space, find word spacing in points
                    if ( $numSpaces > 0 )
                        $this->ws = ( $maxWidth - $cutoffWidth ) / $numSpaces;
                    else
                        $this->ws = 0;

                    $this->_out( sprintf( '%.3f Tw', $this->ws ) );

                }

                // otherwise, we want normal spacing
                else
                    $this->_out( sprintf( '%.3f Tw', 0 ) );

                // print out each chunk
                $usedWidth = 0;

                foreach ( $content as $k => $chunk )
                {

                    $this->restoreFont( $font[ $k ] );

                    $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k );

                    // determine which borders should be used
                    $b = '';

                    if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) )
                        $b .= 'T';

                    if ( $k == 0 && is_int( strpos( $border, 'L' ) ) )
                        $b .= 'L';

                    if ( $k == count( $content ) - 1 && is_int( strpos( $border, 'R' ) ) )
                        $b .= 'R';

                    // if it's the last chunk of this line, move to the next line after
                    if ( $k == count( $content ) - 1 )
                        $this->Cell( ( $maxWidth / $this->k ) - $usedWidth + 2 * $this->cMargin, $lineHeight, $chunk, $b, 1, $align, $fill );
                    else
                    {

                        $this->Cell( $stringWidth + 2 * $this->cMargin, $lineHeight, $chunk, $b, 0, $align, $fill );
                        $this->x -= 2 * $this->cMargin;

                    }

                    $usedWidth += $stringWidth;

                }

                // move on to the next line, reset variables, tack on saved content and current char
                $this->restoreFont( $savedFont );

                $font = array( $savedFont );
                $content = array( $savedContent . $s{ $i } );

                $currContent =& $content[ 0 ];

                $contentWidth = $this->GetStringWidth( $currContent ) * $this->k;
                $cutoffWidth = $contentWidth;
            }
            // another character will fit, so add it on
            else
            {
                $contentWidth += $cw;
                $currContent .= $s{ $i };
            }
        }
    }
}


class myPDF extends PDF
{
    //Page header
    function Header()
    {
        global $priorities, $MYGET;

    	//Logo
        $this->Image(PDF_INCLUDES.'pdf_header.png',5,10,200);

        //$this->setY(30);
        $this->Ln(30);

        //Arial bold 15
        $this->SetFont('Arial','B',14);

        $header_cellwidth = 150;
        //Move to the right
        $this->Cell((USABLEWIDTH-$header_cellwidth)/2);

        $date = date('m/d/Y');
        if($MYGET['p'] != '')
            $priority_title = $priorities[$MYGET['p']]['name']. " Legislation as of {$date}";
        else
            $priority_title = "Legislation as of {$date}";

        //Title
        $this->Cell($header_cellwidth,9,$priority_title,"TBRL",2,'C');
        $this->Ln(12);
    }

    //Page footer
    function Footer()
    {
        //Position at 1.5 cm from bottom
        $this->SetY(-15);
        //Arial italic 8
        $this->SetFont('Arial','I',8);
        //Page number
        $this->Cell(0,10,'Page '.$this->PageNo(),0,0,'R');
    }
    function NbLines($w,$txt)
    {
        //Computes the number of lines a MultiCell of width w will take
        $cw=&$this->CurrentFont['cw'];
        if($w==0)
            $w=$this->w-$this->rMargin-$this->x;
        $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
        $s=str_replace("\r",'',$txt);
        $nb=strlen($s);
        if($nb>0 and $s[$nb-1]=="\n")
            $nb--;
        $sep=-1;
        $i=0;
        $j=0;
        $l=0;
        $nl=1;
        while($i<$nb)
        {
            $c=$s[$i];
            if($c=="\n")
            {
                $i++;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
                continue;
            }
            if($c==' ')
                $sep=$i;
            $l+=$cw[$c];
            if($l>$wmax)
            {
                if($sep==-1)
                {
                    if($i==$j)
                        $i++;
                }
                else
                    $i=$sep+1;
                $sep=-1;
                $j=$i;
                $l=0;
                $nl++;
            }
            else
                $i++;
        }
        return $nl;
    }

    function AddPageBreak($h)
    {
        //If the height h would cause an overflow, add a new page immediately
        if($this->GetY()+$h>$this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }
}


$pdf=new myPDF("P", "mm", "Letter");
$pdf->SetMargins(10,10,10,10);
$pdf->SetAutoPageBreak(TRUE);

$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',10);


$line_height = 4;

foreach($bills as $bill) {
	$nb = 0;
	$nb=max($nb,$pdf->NbLines(48,$bill['bill_edit_status']));

	if (strlen($bill['staff']))
	    $bill['bill_desc'] .= "\n\nStaff: " . $bill['staff'];

	$nb=max($nb, $pdf->NbLines(95,$bill['bill_desc']) + $pdf->NbLines(95,"{$bill['bill_number']} ({$bill['bill_author']})"));

	$position_string = "";

	if(isset($positions[$bill['bill_id']])) {
		foreach($positions[$bill['bill_id']] as $thiskey => $pos) {

			if(!empty($pos['document_date'])) {
				$position_string .= $pos['position_name']." (".date("m/d/y",strtotime($pos['document_date'])).")\n";
			} else {
				$position_string .= $pos['position_name']."\n";
			}
		}
	} else {
		$position_string = " ";
	}

	$nb=max($nb,$pdf->NbLines(47,$position_string));

	//$nb = $nb+3;
	$nb = $nb*$line_height;

	//add some extra padding
	$nb += 20;
    $pdf->AddPageBreak($nb);

	if ($pdf->GetY() === 61) {
		$pdf->SetFont( 'Arial', 'B', 16 );
		$pdf->SetFillColor(214, 222, 255);
		$pdf->SetTextColor(0,0,0);
		$pdf->SetFont( 'Arial', 'B', 14 );
		$pdf->Cell(95,$line_height*2,"Legislation",0,0,"L",1);
		$pdf->Cell(48,$line_height*2,"Status",0,0,"L",1);
		$pdf->Cell(47,$line_height*2,"UC Position",0,0,"L",1);
		$pdf->Ln($line_height*2);
	}

	$pdf->SetFillColor(255, 255, 255);

	//how wide we want it
	$cell_width = 95;
	$supertop = $pdf->GetY();
	$pdf->MultiCell(USABLEWIDTH,1,"","T");
	$pdf->Ln(2);

	$top = $pdf->GetY();
	$bottom = 0;
	$bump = 10;

	//place it
	$pdf->SetFont( 'Arial', 'BU', 10 );
	$pdf->MultiCell($cell_width,$line_height,"{$bill['bill_number']} ({$bill['bill_author']})",0);
	$pdf->SetFont( 'Arial', '', 10 );
	$pdf->MultiCell($cell_width,$line_height,"{$bill['bill_desc']}",0,"L");

	//play nice here, and store the maximum bottom value.
	if($pdf->GetY() > $bottom) {
		$bottom = $pdf->GetY();
		$used_section =1;
	}
	//make sure to play nice for the next cell, so tell it how must space we took
	$bump = $bump + $cell_width;

	$cell_width = 48;
	$pdf->SetY($top);
	$pdf->SetX($bump);
	$pdf->MultiCell($cell_width,$line_height,"{$bill['bill_edit_status']}",0, "L");

	if($pdf->GetY() > $bottom) {
		$bottom = $pdf->GetY();
		$used_section =2;
	}
	$bump = $bump + $cell_width;


	$cell_width = 47;
	$pdf->SetY($top);
	$pdf->SetX($bump);
	$pdf->MultiCell($cell_width,$line_height,"{$position_string}",0, "L");

	if($pdf->GetY() > $bottom) {
		$bottom = $pdf->GetY();
		$used_section =3;
	}
	$bump = $bump + $cell_width;

	//$cell_width = 200;

	$pdf->Ln($bottom-$supertop);
	//$pdf->MultiCell($cell_width,$line_height,"$line_height, $bottom, $supertop, $top, $used_section",0,"L");
}

//shows a static filename
$filename = "searchresults.pdf";

//shows a long formatted date
$filename = "searchresults_".date("m")."-".date("d")."-".date("Y")."_".date("hisa").".pdf";

//shows a timestamped date
$filename = "searchresults_".time().".pdf";


$pdf->Output($filename, "I");
ob_end_flush();
?>
