<?php
//this script is to special advertising sections - will be injected into jobs
include("includes/boot.php");

if( $_POST ) {
	$action = $_POST['submit'];
} else {
	$action = $_GET['action'];
}

switch($action) {
	case "view" : view_single(); break;
	case "add" : view_form('add'); break;
	case "edit" : view_form('edit'); break;
	case "Save Section" : save_row('insert'); break;
	case "Update Section" : save_row('update'); break;
	case "delete" : delete_row(); break;
	case "pjob" : print_job(); break;
	default : view_list(); break;
}

function view_list()
{
	global $pubids;

	//get product type
	$ptypes = array();
	$ptypes[0] = 'Please choose';
	$sql = "SELECT * FROM special_section_types WHERE site_id=" . SITE_ID . " ORDER BY product_name";
	$dbP = dbselectmulti($sql);
	if( $dbP['numrows'] > 0 ) {
		foreach( $dbP['data'] as $p ) {
			$ptypes[$p['id']]=$p['product_name'];
		}
	}

    
    
	$sql = "SELECT * FROM special_sections WHERE site_id=" . SITE_ID . " ORDER BY insert_date DESC";
	$dbSections = dbselectmulti($sql);
	
    $searchBlock = "<form method=post class='form'>\n";
    $searchBlock.="<br><input type='submit' class='btn btn-dark' name='submit' value='Search' /><br>";
    $searchBlock.="</form>\n";
    
    tableStart("<a href='?action=add'>Add new special section</a>","Month,Section Name,Insertion Date,Outside Job,Sales Deadline,Pagination Date,Product Type",10,$searchBlock);
	if( $dbSections['numrows'] > 0 )
	{
		foreach( $dbSections['data'] as $section )
		{
			$id = $section['id'];
			$month = ( trim($section['insert_date']) > '' ? date("F",strtotime($section['insert_date'])) : '' );
			$desc = $section['section_name'];
			$insert = ( trim($section['insert_date']) > '' ? date("D, M j",strtotime($section['insert_date'])) : '' );
			$sales = ( trim($section['sales_date']) > '' ? date("D, M j",strtotime($section['sales_date'])) : '' );
			$pagination = ( trim($section['pagination_date']) > '' ? date("D, M j",strtotime($section['pagination_date'])) : '' );
			$ptype = $ptypes[$section['product_type']];
			( $section['outside_job']==1 ) ? $outside='Outside Vendor' : $outside='We print';
			print "<tr>\n";
			print "<td>$month</td>\n";
			print "<td><a href='?action=view&sectionid=$id'>$desc</a></td>\n";
			print "<td>$insert</td>\n";
			print "<td>$outside</td>\n";
			print "<td>$sales</td>\n";
			print "<td>$pagination</td>\n";
			print "<td>$ptype</td>\n";
			print "<td>\n";
			print "<div class='btn-group'>\n";
			print "<a href='?action=edit&sectionid=$id' class='btn btn-dark'>Edit</a>\n";
			print "<button type='button' class='btn btn-dark dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>\n";
			print "<span class='caret'></span>\n";
			print "<span class='sr-only'>Toggle Dropdown</span>\n";
			print "</button>\n";
			print "<ul class='dropdown-menu'>\n";
			print "<li><a href='?action=pjob&sectionid=$id'>Convert to Press Job</a></li>\n";
			print "<li><a href='?action=delete&sectionid=$id' class='delete'><i class='fa fa-trash'></i> Delete</a></li>\n";
			print "</ul>\n";
			print "</div>\n";
			print "</td>\n";
			print "</tr>\n";
		}
	}
	tableEnd($dbSections);
}

function view_single()
{
	$sectionid = intval( $_GET['sectionid'] );
	$sql = "SELECT * FROM special_sections WHERE id=$sectionid LIMIT 1";
	$dbSections = dbselectsingle($sql);
	$section = $dbSections['data'];

	// table start
	print "<div class='row'>\n";
	print "<div class='col xs-12 col-sm-9'> <!-- opens up the div for the table! -->\n";
	print "<div class='table-responsive' style='min-height:75vh !important;'>\n";
	print "<table id='stable' class='table table-striped table-bordered table-hover' cellspacing='0' width='100%'>\n";
	print "<thead>\n<tr>\n";
	print "<th>Field</th>";
	print "<th>Value</th>";
	print "</tr>\n</thead>\n";
	print "<tbody>\n";

	if( $dbSections['numrows'] > 0 )
	{
		// basic
		$pubid = $section['pub_id'];
		$sql="SELECT A.pub_name FROM publications A, special_section_pub_xref B WHERE A.id=B.pub_id AND B.section_id=$sectionid";
        $dbPubs = dbselectmulti($sql);
        if($dbPubs['numrows']>0)
        {
            $pubs = array();
            foreach($dbPubs['data'] as $pub)
            {
                $pubs[]=$pub['pub_name'];
            }
            $pubs = implode(", ",$pubs);
        } else {
            $pubs = "None set";
        }
        $sectionname = $section['section_name'];
		$insertdate = ( trim($section['insert_date']) > '' ? date("D, M j",strtotime($section['insert_date'])) : '' );
		$flyerdue = ( trim($section['flyer_due']) > '' ? date("D, M j",strtotime($section['flyer_due'])) : '' );
		$draw = $section['draw'];
		$overrun = $section['overrun'];
		$revenueGoal = $section['revenue_goal'];
		$revenueActual = $section['revenue_actual'];
		// production
		$ptype = $section['product_type'];
		$requestPrint = ( trim($section['request_printdate']) > '' ? date("D, M j",strtotime($section['request_printdate'])) : '' );
		$pressdate = ( trim($section['press_date']) > '' ? date("D, M j",strtotime($section['press_date'])) : '' );
		$editorialcontent = $section['editorial_content'];
		$outsideJob = $section['outside_job'];
		$digitalJob = $section['digital_job'];
		$bindery = $section['bindery'];
		$glossycover = $section['glossy_cover'];
		$pagelayout = ( trim($section['page_layout']) > '' ? date("D, M j",strtotime($section['page_layout'])) : '' );
		$paper = $section['paper_type'];
		$pagination = ( trim($section['pagination_date']) > '' ? date("D, M j",strtotime($section['pagination_date'])) : '' );
		$dummyDate = ( trim($section['dummy_date']) > '' ? date("D, M j",strtotime($section['dummy_date'])) : '' );
		$dummiesTo = $section['dummies_to'];
		// sales
		$glossysales = ( trim($section['glossy_sales']) > '' ? date("D, M j",strtotime($section['glossy_sales'])) : '' );
		$glossyclear = ( trim($section['glossy_clear']) > '' ? date("D, M j",strtotime($section['glossy_clear'])) : '' );
		$salesdeadline = ( trim($section['sales_date']) > '' ? date("D, M j",strtotime($section['sales_date'])) : '' );
		$adsclear = ( trim($section['clear_date']) > '' ? date("D, M j",strtotime($section['clear_date'])) : '' );
		// notes
		$notes = $section['notes'];

		print "<tr><td>Publication</td><td>$pubs</td></tr>\n";
		print "<tr><td>Section Name</td><td>$sectionname</td></tr>\n";
		print "<tr><td>Insert Date</td><td>$insertdate</td></tr>\n";
		print "<tr><td>Flyer Due</td><td>$flyerdue</td></tr>\n";
		print "<tr><td>Draw</td><td>$draw</td></tr>\n";
		print "<tr><td>Overrun</td><td>$overrun</td></tr>\n";
		print "<tr><td>Revenue Goal</td><td>$revenueGoal</td></tr>\n";
		print "<tr><td>Revenue Actual</td><td>$revenueActual</td></tr>\n";
		print "<tr><td>Production Type</td><td>$ptype</td></tr>\n";
		print "<tr><td>Requested Press Date</td><td>$requestPrint</td></tr>\n";
		print "<tr><td>Actual Press Date</td><td>$pressdate</td></tr>\n";
		print "<tr><td>Editorial</td><td>$editorialcontent</td></tr>\n";
		print "<tr><td>Outside Printer</td><td>$outsideJob</td></tr>\n";
		print "<tr><td>Digital Job</td><td>$digitalJob</td></tr>\n";
		print "<tr><td>Stitch &amp; Trim</td><td>$bindery</td></tr>\n";
		print "<tr><td>Glossy Cover</td><td>$glossycover</td></tr>\n";
		print "<tr><td>Page Layout</td><td>$pagelayout</td></tr>\n";
		print "<tr><td>Paper</td><td>$paper</td></tr>\n";
		print "<tr><td>Pagination Date</td><td>$pagination</td></tr>\n";
		print "<tr><td>Dummy Date</td><td>$dummyDate</td></tr>\n";
		print "<tr><td>Dummies To</td><td>$dummiesTo</td></tr>\n";
		if( $glossycover ) {
			print "<tr><td>Glossy Sales Deadline</td><td>$glossysales</td></tr>\n";
			print "<tr><td>Glossy Ad Clear Deadline</td><td>$glossyclear</td></tr>\n";
		} else {
			print "<tr><td>Glossy Sales Deadline</td><td>NA</td></tr>\n";
			print "<tr><td>Glossy Ad Clear Deadline</td><td>NA</td></tr>\n";
		}
		print "<tr><td>Sales Deadline</td><td>$salesdeadline</td></tr>\n";
		print "<tr><td>Ad Clear Deadline</td><td>$adsclear</td></tr>\n";
		print "<tr><td>Notes</td><td>$notes</td></tr>\n";
	}

	// table end
	print "</tbody>\n";
	print "</table>\n";
	print "</div>\n";
	print "</div>\n";
	print "<div class='col xs-12 col-sm-3'>\n";
	print "<div id='tableoptions' class='well'>\n";
	print "<p><strong>Actions:</strong></p>\n";
	print "<a href='?action=edit&sectionid=$sectionid'>Edit this Special Section</a>\n";
	print "</div>\n";
	print "</div>\n";
	print "</div> <!-- close row -->\n";

}

function view_form($action)
{
	global $pubs, $papertypes;

	$sectionid = intval( $_GET['sectionid'] );

	//get product type
	$ptypes = array();
	$ptypes[0] = 'Please choose';
	$sql = "SELECT * FROM special_section_types WHERE site_id=" . SITE_ID . " ORDER BY product_name";
	$dbP = dbselectmulti($sql);
	if( $dbP['numrows'] > 0 ) {
		foreach( $dbP['data'] as $p ) {
			$ptypes[$p['id']]=$p['product_name'];
		}
	}

	$isAdd = true;
	$section = array();
	if( $action == 'edit' ) {
		$isAdd = false;
		$sql = "SELECT * FROM special_sections WHERE id=$sectionid";
		$dbSection = dbselectsingle($sql);
		$section = $dbSection['data'];
	}
    
    $button = ( $isAdd ) ? 'Save Section' : 'Update Section';
	$insertdate = ( $isAdd ) ? false : $section['insert_date'];
	$sectionname = ( $isAdd ) ? '' : $section['section_name'];
	$flyerdue = ( $isAdd ) ? false : $section['flyer_due'];
	$glossycover = ( $isAdd ) ? 0 : $section['glossy_cover'];
	$glossysales = ( $isAdd ) ? false : $section['glossy_sales'];
	$glossyclear = ( $isAdd ) ? false : $section['glossy_clear'];
	$salesdeadline = ( $isAdd ) ? false : $section['sales_date'];
	$adsclear = ( $isAdd ) ? false : $section['clear_date'];
	$pagination = ( $isAdd ) ? false : $section['pagination_date'];
	$ptype = ( $isAdd ) ? '0' : $section['product_type'];
	$editorialcontent = ( $isAdd ) ? 0 : $section['editorial_content'];
	$pressdate = ( $isAdd ) ? false : $section['press_date'];
	$draw = ( $isAdd ) ? 0 : $section['draw'];
	$overrun = ( $isAdd ) ? 0 : $section['overrun'];
	$paper = ( $isAdd ) ? $GLOBALS['defaultNewsprintID'] : $section['paper_type'];
	$bindery = ( $isAdd ) ? 0 : $section['bindery'];
	$notes = ( $isAdd ) ? '' : $section['notes'];
	$revenueGoal = ( $isAdd ) ? 0 : $section['revenue_goal'];
	$revenueActual = ( $isAdd ) ? 0 : $section['revenue_actual'];
	$outsideJob = ( $isAdd ) ? 0 : $section['outside_job'];
	$digitalJob = ( $isAdd ) ? 0 : $section['digital_job'];
	$requestPrint = ( $isAdd ) ? false : $section['request_printdate'];
	$dummiesTo = ( $isAdd ) ? '' : $section['dummies_to'];
    $dummyDate = ( $isAdd ) ? false : $section['dummy_date'];
    $editorialDueDate = ( $isAdd ) ? false : $section['editorial_date'];
	$whoPagination = ( $isAdd ) ? '' : $section['who_paginates'];

    $pubids = array();
    $sql="SELECT pub_id FROM special_section_pub_xref WHERE special_section_id=$sectionid";
    $dbPubs=dbselectmulti($sql);
    if($dbPubs['numrows']>0)
    {
        foreach($dbPubs['data'] as $pub)
        {
            $pubids[]=$pubs[$pub['pub_id']];
        }
    }    
    
    print "<form method=post class='form-horizontal'>\n";
		print "<div>";
			print "<ul id='specialSectionsFormInfo' class='nav nav-tabs' role='tablist'>\n";
				print "<li role='presentation' class='active'><a href='#basicInfo' aria-controls='basicInfo' role='tab' data-toggle='tab'>Basic Information</a></li>\n";
				print "<li role='presentation' ><a href='#productionInfo' aria-controls='productionInfo' role='tab' data-toggle='tab'>Production</a></li>\n";
				print "<li role='presentation' ><a href='#salesInfo' aria-controls='salesInfo' role='tab' data-toggle='tab'>Sales</a></li>\n";
				print "<li role='presentation' ><a href='#notes' aria-controls='notes' role='tab' data-toggle='tab'>Notes</a></li>\n";
			print "</ul>\n";
			print "<div class='tab-content'>";
				print "<div id='basicInfo' role='tabpanel' class='tab-pane active'>\n";
					make_select('pub_ids',$pubids,$pubs,'Publication','Which publication(s) will this section run in?','',false,'',false,true);
					make_date('insert_date',$insertdate,'Insert Date','When does this section first publish?','','','',true);
                    make_text('section_name',$sectionname,'Section Name','Name of the special secton.',50);
					make_select('paper_type',$papertypes[$paper],$papertypes,'Paper','Type of paper to print on.');
                    make_select('product_type',$ptypes[$ptype],$ptypes,'Product Type','Type of product.');
                    make_number('draw',$draw,'Draw','How many copies to produce?');
					make_number('overrun',$overrun,'Overrun','How many copies for other purposes?');
					make_number('revenue_goal',$revenueGoal,'Revenue Goal','How much do we hope to make?');
					make_number('revenue_actual',$revenueGoal,'Revenue Actual','How much did we actually make?');
				print "</div>\n";
				print "<div id='productionInfo' role='tabpanel' class='tab-pane'>\n";
					make_date('flyer_due',$flyerdue,'Flyer Due','When is the promotional flyer due?','','','',true);
                    make_checkbox('editorial_content',$editorialcontent,'Editorial','Check if this product requires editorial content.');
					make_checkbox('outside_job',$outsideJob,'Outside Printer','Check if this will be printed/produced by a 3rd party printer.');
					make_checkbox('digital_job',$digitalJob,'Digital Job','Check if this will be an online only product (no printing required).');
					make_checkbox('bindery',$bindery,'Stitch &amp; Trim','Check if this product requires stitching and trimming.');
					make_checkbox('glossy_cover',$glossycover,'Glossy Cover','Check if this product has a glossy cover.');
					make_date('dummy_date',$dummyDate,'Dummy Date','When is the section dummied?','','','',true);
                    make_text('dummies_to',$dummiesTo,'Dummies To','Who gets the dummies?');
                    make_date('editorial_date',$editorialDueDate,'Editorial Due Date','When is the editorial copy due?','','','',true);
                    make_date('pagination_date',$pagination,'Pagination Date','Deadline for pagination of the section.','','','',true);
                    make_text('who_paginates',$whoPagination,'Who paginates','Who will be paginating this section?');
                    make_date('request_printdate',$requestPrint,'Requested Press Date','When should this product be scheduled to print?','','','',true);
                    make_date('pressdate',$pressdate,'Press Date','When did this product actually print?','','','',true);
                print "</div>\n";
				print "<div id='salesInfo' role='tabpanel' class='tab-pane'>\n";
					make_date('glossy_sales',$glossysales,'Glossy Sales Deadline','When is the deadline for glossy sales?','','','',true);
					make_date('glossy_clear',$glossyclear,'Gloss Ad Clear','When do the glossy ads need to clear?','','','',true);
					make_date('sales_date',$salesdeadline,'Sales Deadline','Deadline for regular ad sales.','','','',true);
					make_date('clear_date',$adsclear,'Ad Clear Deadline','Deadline for ads to clear.','','','',true);
				print "</div>\n";
				print "<div id='notes' role='tabpanel' class='tab-pane'>\n";
					make_textarea('notes',$notes,'Notes','All notes and additional information about this job.');
				print "</div>\n";
			print "</div>\n";
			make_submit('submitbutton',$button);
			make_hidden('sectionid',$sectionid);
		print "</div>\n";
	print "</form>\n";
    
    $GLOBALS['scripts'][]="\$('#pub_ids').select2();";
}

function save_row($action)
{
	$sectionid = $_POST['sectionid'];

	$insertdate = $_POST['insert_date'];
	$pubids = $_POST['pub_ids'];
	$sectionname = $_POST['section_name'];
	$flyerdue = $_POST['flyer_due'];
	$glossyclear = $_POST['glossy_clear'];
	$glossysales = $_POST['glossy_sales'];
	($_POST['glossy_cover']) ? $glossycover=1 : $glossycover=0;
	($_POST['editorial_content']) ? $editorialcontent=1 : $editorialcontent=0;
	($_POST['outside_job']) ? $outsidejob=1 : $outsidejob=0;
	($_POST['digitial_job']) ? $digitaljob=1 : $digitaljob=0;
	($_POST['bindery']) ? $bindery=1 : $bindery=0;
	$salesdate = $_POST['sales_date'];
	$pagelayout = $_POST['page_layout'];
	$adsclear = $_POST['clear_date'];
	$pagination = $_POST['pagination_date'];
	$ptype = $_POST['product_type'];
	$pressdate = $_POST['press_date'];
	$draw = $_POST['draw'];
	$overrun = $_POST['overrun'];
	$paper = $_POST['paper_type'];
	$notes = addslashes($_POST['notes']);
	$revenueGoal = $_POST['revenue_goal'];
	$revenueActual = $_POST['revenue_actual'];
	$requestPrint = $_POST['request_printdate'];
	$dummiesTo = addslashes($_POST['dummies_to']);
    $dummyDate = $_POST['dummy_date'];
    $editorialDueDate = $_POST['editorial_date'];
	$whoPaginates = addslashes($_POST['who_paginates']);

	if( $action == 'insert' ) {

		$sql = "INSERT INTO special_sections (
				insert_date, section_name, flyer_due, glossy_clear,
				glossy_sales, glossy_cover, editorial_content, outside_job,
				digital_job, bindery, sales_date, clear_date,
				pagination_date, product_type, draw, overrun, paper_type, notes,
				revenue_goal, revenue_actual, site_id, request_printdate,
				press_date, dummies_to, dummy_date, editorial_date, who_paginates )
			VALUES (
				" . ( !$insertdate ? "Null" : "'$insertdate'" ) . ",
				'$sectionname',
				" . ( !$flyerdue ? "null" : "'$flyerdue'" ) . ",
				" . ( !$glossyclear ? "null" : "'$glossyclear'" ) . ",
				" . ( !$glossysales ? "null" : "'$glossysales'" ) . ",
				'$glossycover',
				'$editorialcontent',
				'$outsidejob',
				'$digitaljob',
				'$bindery',
				" . ( !$salesdate ? "null" : "'$salesdate'" ) . ",
				" . ( !$adsclear ? "null" : "'$adsclear'" ) . ",
				" . ( !$pagination ? "null" : "'$pagination'" ) . ",
				'$ptype',
				'$draw',
				'$overrun',
				'$paper',
				'$notes',
				'$revenueGoal',
				'$revenueActual',
				'" . SITE_ID . "',
				" . ( !$requestPrint ? "null" : "'$requestPrint'" ) . ",
				" . ( !$pressdate ? "null" : "'$pressdate'" ) . ",
				'$dummiesTo',
                " . ( !$dummyDate ? "null" : "'$dummyDate'" ) . ",
                " . ( !$editorialDueDate ? "null" : "'$editorialDueDate'" ) . ",
				'$whoPaginates')
                ";
		$dbInsert = dbinsertquery($sql);
		$error = $dbInsert['error'];
        $sectionid = $dbInsert['insertid'];
	} else {

		$sql = "UPDATE special_sections SET
				insert_date = " . ( !$insertdate ? "Null" : "'$insertdate'" ) . ",
				section_name = '$sectionname',
				flyer_due = " . ( !$flyerdue ? "Null" : "'$flyerdue'" ) . ",
				glossy_clear = " . ( !$glossyclear ? "Null" : "'$glossyclear'" ) . ",
				glossy_sales = " . ( !$glossysales ? "Null" : "'$glossysales'" ) . ",
				glossy_cover = '$glossycover',
				editorial_content = '$editorialcontent',
				outside_job = '$outsidejob',
				digital_job = '$digitaljob',
				bindery = '$bindery',
				sales_date = " . ( !$salesdate ? "Null" : "'$salesdate'" ) . ",
				clear_date = " . ( !$adsclear ? "Null" : "'$adsclear'" ) . ",
				pagination_date = " . ( !$pagination ? "Null" : "'$pagination'" ) . ",
				product_type = '$ptype',
				draw = '$draw',
				overrun = '$overrun',
				paper_type = '$paper',
				notes = '$notes',
				revenue_goal = '$revenueGoal',
				revenue_actual = '$revenueActual',
                request_printdate = " . ( !$requestPrint ? "Null" : "'$requestPrint'" ) . ",
				editorial_date = " . ( !$editorialDueDate ? "Null" : "'$editorialDueDate'" ) . ",
                who_paginates = '$whoPaginates',
				dummies_to = '$dummiesTo',
				dummy_date = " . ( !$dummyDate ? "Null" : "'$dummyDate'" ) . "
			WHERE id=$sectionid";
		$dbUpdate = dbexecutequery($sql);
		$error = $dbUpdate['error'];

	}
    //handle the pub ids
    $sql="DELETE FROM special_section_pub_xref WHERE special_section_id = $sectionid";
    $dbDelete = dbexecutequery($sql);
    
    //add the pubs
    if(count($pubids)>0)
    {
        $pubInserts = array();
        foreach($pubids as $pubid)
        {
            $pubInserts[]="($sectionid, $pubid)";
        }
        $pubInserts = implode(",",$pubInserts);
        $sql="INSERT INTO special_section_pub_xref (special_section_id, pub_id) VALUES $pubInserts";
        $dbInsert = dbinsertquery($sql);
        
    }
    
    
	if( $error == '' ) {
		setUserMessage('The special section was saved successfully','success');
	} else {
		setUserMessage('There was a problem saving the special section.<br>'.$error,'error');
	}
	redirect("?action=list");
}

function delete_row()
{
	$sectionid = intval( $_GET['sectionid'] );
	$sql = "DELETE FROM special_sections WHERE id=$sectionid";
	$dbDelete = dbexecutequery($sql);
	redirect("?action=list");
}

function  print_job()
{
    //@todo create function for Special Sections to convert to a press run & bindery run if needed
    print "This function has not been set up yet.";
}

$Page->footer();
