<?php 
//echo"<pre>";print_r($contributors1); die(); 
?>
<html>

<HEAD>

<TITLE>Contributor Book Summary</TITLE>

</HEAD>

<Body>	
	
	<?php
		#if we are selecting the current quarter from drop down then show, statement date range as first date of selected quarter to current date of the quarter we are in
		
		if(!empty(\Session::get('week_from'))){
			$week_from = date("m/d/Y", strtotime(\Session::get('week_from')));
		}else{
			$week_from = date("m/d/Y", strtotime($week_from));
		}
       	
       	if(!empty(\Session::get('week_from'))){
			$week_to = date("m/d/Y", strtotime(\Session::get('week_to')));
		}else{
			$week_to = date("m/d/Y", strtotime($week_to));
		}
       	

		$qtrs_val=array();
		/* getting the selected quarter*/
		if($selected_quarter == 1){
			$selected_q = '1st Quarter (Jan-March)';
		}
		if($selected_quarter == 2){
			$selected_q = '2nd Quarter (Apr-June)';
		}
		if($selected_quarter == 3){
			$selected_q = '3rd Quarter (July-Sept)';
		}
		if($selected_quarter == 4){
			$selected_q = '4th Quarter (Oct-Dec)';
		}
		if($selected_quarter == 5){
			$selected_q = 'Custom Quarter (Jan-Dec)';

			#get the quarter of week from date
			$month_name1 = date('M', strtotime($week_from));
			$month1 = date('m', strtotime($week_from));
			$q1 = ceil($month1/3);

			#get the quarter of week to date
			$month_name2 = date('M', strtotime($week_to));
			$month2 = date('m', strtotime($week_to));
			$q2 = ceil($month2/3);  

			#collect the quarter in array
			for($qtrs=$q1; $qtrs <= $q2; $qtrs++){
				$qtrs_val[]=$qtrs;
			}
		}
		#get current quarter values
		$currentDate = floor((date('n') - 1) / 3);

        $year = date('Y');
        $quarters = array();
        $q = "";
        for ($i = 0; $i < 5; $i++)
        {
            $q = (($currentDate+$i)%4) + 1;
           
        }
        
        setlocale(LC_MONETARY, 'en_US.UTF-8'); //for money
	?>
	</div>


	<!--contributor;s name-->
	@foreach ($contributors1 as $contributordet)@endforeach
	
	<?php
	$week_from = date("m/d/Y", strtotime($week_from));
	$week_to = date("m/d/Y", strtotime($week_to));
	?>

	<?php

	$this_quarter = ""; //name of the quarter
	$main_quarter = array(); //collecting name and quarter expense
	$quarter_value = array(); //book id
	$sum = 0; //var to save of the quarter expense
	$iterations = 0; //check which iteration it is so that page break can be added to the second one
	$book_title ="";

	
	foreach($contributordet['calculas'] as $book_no1=>$calc){

		$gross_sales = 0;
			$total_qty = 0;
        foreach($calc as $book_name => $market_details){
            

            if ($iterations >= 1) {
			echo "<span style='page-break-inside:avoid'><span class='no_break_week'>"; echo"<br></span></span>";
			}else{
				echo "<span style='page-break-inside:avoid'><span class=''>";echo"</span><br><span></span></span>";
			}

			#contributor name and quarter
			echo '<div><b>Contributor Name : </b>'.$contributordet["user_details"]["name"].'</div>';
			echo '<div><b> Quarter :</b>'.$selected_q.'- '.$selected_year.'</div>';

            echo "<p><b>BOOK TITLE : </b>".strstr($book_name, '-varprice-', true)."<br>";


            ##DIGITAL PRICE AND PRINT PRINT##
            #get everything between varprice and digiprice to fetch the print price
			if (preg_match('/-varprice-(.*?)-digiprice-/', $book_name, $match) == 1) {
				$var_price = $match[1];
			}
            
            if(empty($var_price)){
                $var_price = 0;
            }
			if(is_float($var_price) == false){
			$var_price= floatval($var_price);
			}else{
			$var_price = $var_price;
			}
			$var_price = money_format('%+n', $var_price); 
            echo "<b>PRINT PRICE : </b>".$var_price."<br>";


            #fetch the digital price
            $digiprice = explode('-digiprice-', $book_name, 2)[1];
			
            
            if(!empty($digiprice)){
                if(is_float($digiprice) == false){
				$digiprice= floatval($digiprice);
				}else{
				$digiprice = $digiprice;
				}
				$digiprice = money_format('%+n', $digiprice); 
                echo "<b>DIGITAL PRICE : </b>".$digiprice."</p>";
            }


            ##OUT OF PRINT##

            if(isset($out_print_array[$book_no1])){
			
				foreach($out_print_array[$book_no1] as $key_id => $things){
					if($things['year']==$selected_year){

						$q_arr = explode(',', $things['quarters']);
						
						if(in_array($selected_quarter, $q_arr)){
							echo "<div><b>NOTE: </b>Item Out of print for ".$selected_q." </div><br>";
						
						}
					}
				}
			}
			

			##SALES TABLE##

            echo '<table class="table_view"  border="1" cellspacing="0" cellpadding="0">	<tbody><tr><th>Sales Outlet</th><th>Net Qty Sold</th><th>Revenue</th></tr>';

			#direct

            echo "<tr><td>Direct Market Sales</td>";

            $net_direct_qty = $market_details['DIRECT_MARKET_STORES']['qty_sold']+$market_details['DIRECT_SHORTAGE_/_DAMAGE']['qty_sold']+$market_details['DIRECT_RETURNS']['qty_sold'];

            $net_direct_revenue =   ($market_details['DIRECT_MARKET_STORES']['total_cost'])+( $market_details['DIRECT_SHORTAGE_/_DAMAGE']['total_cost'])+( $market_details['DIRECT_RETURNS']['total_cost']);

            echo "<td>";echo $net_direct_qty."</td>";

			if(is_float($net_direct_revenue) == false){
				$net_direct_qty1= floatval($net_direct_revenue);
			}else{
				$net_direct_qty1 = $net_direct_revenue;
			}
			$net_direct_qty1 = money_format('%+n', $net_direct_qty1); 


            echo "<td>";echo $net_direct_qty1."</td></tr>";

            #non_direct

            echo "<tr><td>Non-Direct Market Sales</td>";

            $net_non_dir_qty = $market_details['NON-DIRECT_MARKET_STORES']['qty_sold']+$market_details['NON-DIRECT_SHORTAGE']['qty_sold'];

            $net_non_dir_revenue = ($market_details['NON-DIRECT_MARKET_STORES']['total_cost'])+( $market_details['NON-DIRECT_SHORTAGE']['total_cost']);

            echo "<td>";echo $net_non_dir_qty."</td>";

            if(is_float($net_non_dir_revenue) == false){
				$net_non_dir_revenue1= floatval($net_non_dir_revenue);
			}else{
				$net_non_dir_revenue1 = $net_non_dir_revenue;
			}
			$net_non_dir_revenue1 = money_format('%+n', $net_non_dir_revenue1); 

            echo "<td>";echo $net_non_dir_revenue1 ."</td></tr>";

            #returns

            echo "<tr><td>Non-Direct Market Returns</td>";

            $return_qty = $market_details['NON-DIRECT_RETURNS']['qty_sold'];

            $return_revenue = $market_details['NON-DIRECT_RETURNS']['unit_retails'] * $market_details['NON-DIRECT_RETURNS']['qty_sold'] * 3/100 ;

            $net_return = $market_details['NON-DIRECT_RETURNS']['unit_retails']*(1-($market_details['NON-DIRECT_RETURNS']['discount']/100)) * $market_details['NON-DIRECT_RETURNS']['qty_sold'] + $return_revenue;


            echo "<td>";echo $return_qty."</td>";

            if(is_float($net_return) == false){
				$return_revenue1= floatval($net_return);
			}else{
				$return_revenue1 = $net_return;
			}
			$return_revenue1 = money_format('%+n', $return_revenue1); 

            echo "<td>";echo $return_revenue1; echo "</td></tr>";


            #international 
            echo "<tr><td>International Sales</td>";

            $net_internatioal_revenue = $market_details['INTERNATIONAL_NON-DIRECT_MARKET_STORES']['unit_retails']*$market_details['INTERNATIONAL_NON-DIRECT_MARKET_STORES']['qty_sold']*(1-($market_details['INTERNATIONAL_NON-DIRECT_MARKET_STORES']['discount']/100))- ($market_details['INTERNATIONAL_NON-DIRECT_MARKET_STORES']['unit_retails']*$market_details['INTERNATIONAL_NON-DIRECT_MARKET_STORES']['qty_sold']*(2.5/100))+($market_details['INTERNATIONAL_NON-DIRECT_MARKET_SHORTAGES']['unit_retails']*(1-($market_details['INTERNATIONAL_NON-DIRECT_MARKET_SHORTAGES']['discount']/100))*$market_details['INTERNATIONAL_NON-DIRECT_MARKET_SHORTAGES']['qty_sold']);

            $net_internatioal_qty = $market_details['INTERNATIONAL_NON-DIRECT_MARKET_STORES']['qty_sold']+$market_details['INTERNATIONAL_NON-DIRECT_MARKET_SHORTAGES']['qty_sold'];

            echo "<td>";echo $net_internatioal_qty."</td>";

            if(is_float($net_internatioal_revenue) == false){
				$net_internatioal_revenue1= floatval($net_internatioal_revenue);
			}else{
				$net_internatioal_revenue1 = $net_internatioal_revenue;
			}

			$net_internatioal_revenue1 = money_format('%+n', $net_internatioal_revenue1); 
            echo "<td>";echo $net_internatioal_revenue1; echo "</td></tr>";

            #digital
            if($market_details['digital_sales'] != 0 && $market_details['digital_sales'] != ""){
            	echo "<tr><td>Digital Sales</td>";

                echo "<td>";echo $market_details['digital_qty']."</td>";

                if(is_float($market_details['digital_sales']) == false){
					$digi_sales= floatval($market_details['digital_sales']);
				}else{
					$digi_sales = $market_details['digital_sales'];
				}

                echo "<td>";echo money_format('%+n', $digi_sales)."</td>";
            }

            #Oni sales
            echo "<tr><td>Retail (Oni Press)</td>";

            echo "<td>";echo $market_details['oni_qty']."</td>";

            if(is_float($market_details['oni_sales']) == false){
				$oni__sales= floatval($market_details['oni_sales']);
			}else{
				$oni__sales = $market_details['oni_sales'];
			}

            echo "<td>";echo money_format('%+n', $oni__sales)."</td>";

            # s & s sales
            echo "<tr><td>Simon & Schuster Sales</td>";

            echo "<td>";echo $market_details['ss_qty']."</td>";

            if(is_float($market_details['ss_sales']) == false){
				$ss__sales= floatval($market_details['ss_sales']);
			}else{
				$ss__sales = $market_details['ss_sales'];
			}

            echo "<td>";echo money_format('%+n', $ss__sales)."</td>";

            
            #totals
            $gross_sales = $net_return+$net_non_dir_revenue+$net_direct_revenue+$net_internatioal_revenue+$market_details['digital_sales']+$market_details['oni_sales']+$market_details['ss_sales'];
            
            $total_qty = $net_direct_qty+$net_non_dir_qty+$return_qty+$net_internatioal_qty+$market_details['digital_qty']+$market_details['oni_qty']+$market_details['ss_qty'];

            ##TOTAL QUANTITY##
            echo "<tr><td>Total</td>";

            echo "<td>";echo $total_qty."</td>";

            ##TOTAL GROSS SALES
            if(is_float($gross_sales) == false){
			$gross_sales_val= floatval($gross_sales);
			}else{
				$gross_sales_val = $gross_sales;
			}
			$gross_sales_value = money_format('%+n', $gross_sales_val); 
			
            echo "<td>";echo $gross_sales_value."</td>";

            echo '</tbody></table>';
        }

    
    #to add page break before the week , it will add page new page for reach book for the iterations greater than or equal to 1

		#total expense
		foreach( $contributordet['book_details']['expense'] as $book_no_expense => $book_id_expense){
			//echo"<pre> book_id_expense ";print_r($book_id_expense);
			if( $book_no1 == $book_no_expense ) {
				foreach($book_id_expense as $more_singledet){


					if ($selected_year==$more_singledet['year']) { 
					#to select quarter for selected year

						if (in_array($more_singledet['book_id'], $quarter_value)) {
					    continue;
						}
					    $quarter_value[] = $more_singledet['book_id'];

					   	##collecting name and quarter expense in main_quarter array

					    if($selected_quarter == 1){
							$main_quarter[$book_no1][]= array(
							$more_singledet['book_title'],
							$more_singledet['first_quarter']
							);
							$this_quarter = '1st Quarter (Jan-March)';
						}

						if($selected_quarter == 2){
							$main_quarter[$book_no1][]= array(
							$more_singledet['book_title'],
							$more_singledet['second_quarter']
							);
							$this_quarter = '2nd Quarter (Apr-June)';
						}

						if($selected_quarter == 3){
							$main_quarter[$book_no1][]= array(
							$more_singledet['book_title'],
							$more_singledet['third_quarter']
							);
							$this_quarter = '3rd Quarter (July-Sept)';
						}

						if($selected_quarter == 4){
							$main_quarter[$book_no1][]= array(
							$more_singledet['book_title'],
							$more_singledet['fourth_quarter']
							);
							$this_quarter = '4th Quarter (Oct-Dec)';
						}
						if($selected_quarter == 5) {
							$all_qtr_val = array(); #not used
							$all_qtr_sum =0;
							foreach($qtrs_val as $qtr){
								if($qtr == 1){
									$all_qtr_sum +=$more_singledet['first_quarter'];
								}
								if($qtr == 2){
									$all_qtr_sum +=$more_singledet['second_quarter'];
								}
								if($qtr == 3){
									$all_qtr_sum +=$more_singledet['third_quarter'];
								}
								if($qtr == 4){
									$all_qtr_sum +=$more_singledet['fourth_quarter'];
								}
							}
							$main_quarter[$book_no1][]= array(
							$more_singledet['book_title'],
							$all_qtr_sum
							);
							$this_quarter = 'CUSTOM QUARTER ('.$month_name1.'-'.$month_name2.')';
						}
					}
				}
			}
		}

		if(!array_key_exists($book_no1,$main_quarter)){
			$main_quarter[$book_no1][]= array(
			strstr($book_name, '-varprice-', true),0
			);
			if( $selected_quarter == 1){
				$this_quarter = '1st Quarter (Jan-March)';
			}elseif( $selected_quarter == 2){
				$this_quarter = '2nd Quarter (Apr-June)';
			}elseif( $selected_quarter == 3){
				$this_quarter = '3rd Quarter (July-Sept)';
			}elseif( $selected_quarter == 4){
				$this_quarter = '4th Quarter (Oct-Dec)';
			}elseif( $selected_quarter == 5){
				$this_quarter = 'Custom Quarter Selected';
			}
		}

		##EXPENSE##
		echo'<div  style="page-break-inside:avoid"><h4>QUALIFIED EXPENSES, '.$this_quarter.'</h4> 
		<table class="table_view" border="1" cellspacing="0" cellpadding="0"> 
		<tbody>
		<tr>
			<th>Book Title</th>
			<th>Amount</th>
		</tr>';

		foreach($main_quarter[$book_no1] as $t_q){
			echo"<tr>";
			foreach($t_q as $t){

				#if no quarter value
				if($t==""){
					$sum = $t;
					echo"<td>$0</td>";
				}else{
					if(is_numeric($t)){
						if(is_float($t) == false){
							$t_val= floatval($t);
						}else{
							$t_val = $t;
						}
						$t_val_value = money_format('%+n', $t_val); 

						echo"<td>" .$t_val_value."</td>";
						$sum = $t;
					}else{
						echo"<td>" .$t."</td>";
					}
				}
			}
		}

		echo '</tbody></table></div>';

		#ROYALTY CHOICE CHECKS
		if($contributordet["book_details"]["royalty_choice"][$book_no1] == NULL || $contributordet["book_details"]["royalty_choice"][$book_no1] == 1){
			$r_choice = "Net";
		}

		if($contributordet["book_details"]["royalty_choice"][$book_no1] == 2){
			$r_choice = "Gross";
		}

		if($contributordet["book_details"]["royalty_choice"][$book_no1] == 3){
			$r_choice = "Cover Price";
		}

		##ROYALTY CHOICE VALUE
		echo "<br><span class='no_break'><b> ROYALTY CHOICE : </b> ".$r_choice."</span><br>";


		##TOTAL QTY
		echo "<span class='no_break'><b > TOTAL QUANTITY SOLD THIS QUARTER : </b>";echo $total_qty."</span><br>";	

		#GROSS SALE				
		if(is_float($gross_sales) == false){
			$gross_sales_val= floatval($gross_sales);
		}else{
			$gross_sales_val = $gross_sales;
		}
		$gross_sales_value = money_format('%+n', $gross_sales_val); 
		echo "<span class='no_break'><b>TOTAL GROSS SALES THIS QUARTER : </b>";echo  $gross_sales_value."</span><br>";

		#TOTAL EXPENSES
		if(is_float($sum) == false){
			$sum_float= floatval($sum);
		}else{
			$sum_float = $sum;
		}
							
		$sumvalue = money_format('%+n', $sum_float); 
		echo "<span class='no_break'><b >TOTAL EXPENSES THIS QUARTER: </b>". $sumvalue."</span><br>";

		#Total Profit :
		#royalty check : net
		if($contributordet["book_details"]["royalty_choice"][$book_no1] == NULL || $contributordet["book_details"]["royalty_choice"][$book_no1] == 1){
			
			#total profit = gross sales- expense
			$total_profit = $gross_sales_val-$sum;
		}

		#royalty check : gross
		if($contributordet["book_details"]["royalty_choice"][$book_no1] == 2){
			
			#total profit = gross sales- expense
			$total_profit = $gross_sales_val;
		}

		#royalty check : cover price
		if($contributordet["book_details"]["royalty_choice"][$book_no1] == 3){
			
			#total profit = gross sales- expense
			$total_profit = $gross_sales_val-$sum;
		}
		
		if(is_float($total_profit) == false){
			$total_profit_val= floatval($total_profit);
		}else{
			$total_profit_val = $total_profit;
		}
		$total_profit_value = money_format('%+n', $total_profit_val); 
		echo '<span class="no_break"><b>PROFIT THIS QUARTER : </b> '.$total_profit_value."</span>";

		#contributor's portion of profit value : TOTAL PERCENTAGE TO THE BOOK
		if(isset($contributordet['book_details']['percentage_Array'][$book_no1])){
			$divide_by_val = $contributordet['book_details']['percentage_Array'][$book_no1];
		}else{
			$divide_by_val = 1;
		}


		##checking the royalty choice of the book 

		#if choice is net : contributor's portion = directly total profit
		if($contributordet["book_details"]["royalty_choice"][$book_no1] == 1 || $contributordet["book_details"]["royalty_choice"][$book_no1]== NULL || $contributordet["book_details"]["royalty_choice"][$book_no1] == 2){
			$contributor_portion = $total_profit*$divide_by_val/100;
		}

		#if choice is cover price : "Print Price" * "Creators Portion of Profits") * "Total Quantity Sold this Quarter"	
		if($contributordet["book_details"]["royalty_choice"][$book_no1] == 3){
			
			$contributor_portion = $contributordet["book_details"]["print_price"][$book_no1]*$total_qty*($divide_by_val/100);
		}

		
		if(is_float($contributor_portion) == false){
			$contributor_portion_val= floatval($contributor_portion);
		}else{
			$contributor_portion_val = $contributor_portion;
		}
		$contributor_portion_value = money_format('%+n', $contributor_portion_val);


		echo "<br><span class='no_break'><b> CREATORS' PORTION OF PROFITS ".$divide_by_val."%: </b> ".$contributor_portion_value."</span>";
		
	
		##calculating the royalty percentage and royalty due
		#the current quarter
		$royalty_due = 0;
		$contributor_amount = 0;
		foreach($contributordet["user_details"]["percentage"] as $per_key => $percentage){
			if($book_no1 == $per_key){	//match the book id 
				foreach($percentage as $manage_payout)

				#only if the book has more than one contributor assigned else the percentage array totals is enough to show.
		
				if($contributordet['book_details']['contri_count'][$book_no1] > 1){

					echo "<br><span class='no_break'><b>CONTRIBUTOR'S ROYALTY PERCENTAGE : </b> ".$manage_payout."%</span>";
				}
				
				#advance
				echo "<br><span class='no_break'><b>CURRENT ADVANCE BALANCE : </b>".money_format('%+n',array_sum($amount_current_quarter[$book_no1]))."</span>";


				#royalty due = totalprofit-advance
				$royalty_due = $contributor_portion - abs(array_sum($amount_current_quarter[$book_no1]));
				
				#checking if the value is float or not. if not convert it to float
				if(is_float($royalty_due) == false){
					$royalty_due= floatval($royalty_due);
				}elseif($royalty_due == -0){
					$royalty_due = 0;
				}
				else{
					$royalty_due = $royalty_due;
				}
				echo " <br><span class='no_break'><b>TOTAL ROYALTIES DUE : </b> ".  money_format('%+n', $royalty_due)."</span>";


				#contributor's amount : royaltydue *($manage pay % / Full percen %)
				$manage_payout = $manage_payout/100;
				$full_percentage = $divide_by_val/100;

				if($full_percentage == 0){
					$contributor_amount = $royalty_due*(0);
				}else{
					$contributor_amount = $royalty_due*($manage_payout/$full_percentage);
				}
				

				if(is_float($contributor_amount) == false ){
					$contributor_amount= floatval($contributor_amount);
				}elseif($contributor_amount == -0){
					$contributor_amount = 0;
				}
				else{
					$contributor_amount = $contributor_amount;
				}
				echo " <br><span class='no_break'><b>CONTRIBUTOR'S ROYALTY DUE : </b> ".  money_format('%+n', $contributor_amount)."</span>";
			}
		}

		#previous quarter balance
		if(isset($balance_end_q_prev[$book_no1]) && $balance_end_q_prev[$book_no1] != '' && $balance_end_q_prev[$book_no1] !=0 && $balance_end_q_prev[$book_no1] < 0){
			echo "<br><span class='no_break'><b>TOTAL ADVANCE TO CARRY FORWARD : </b>".money_format('%+n',$balance_end_q_prev[$book_no1])."</span>";
		}

		#balance end of current quarter
		if(isset($balance_end_q_prev[$book_no1])){

			if($balance_end_q_prev[$book_no1] > 0){
				$prev_qty = 0;
			}

			else{
				$prev_qty=$balance_end_q_prev[$book_no1];
			}

		}else{
			$prev_qty = 0;
		}

		$iterations++;	
	}
	
?>
	
	<!--Following flow is used-->
	<?php
	/*
	--Gross sales = Total of all the sale (digital + physical + retail)
	
	--Total Sales (Total Profit) 

	IF ROYALTY == NET, COVER PRICE
	Gross sales - Expense (for the selected quarter)
	
	IF ROYALTY == GROSS
	Gross sales

	--CONTRIBUTORS PORTION 
	
	IF ROYALTY == NET
	divide_by_val = total percentage to the book
	total_profit*$divide_by_val/100

	IF ROYALTY == COVER PRICE
	divide_by_val = total percentage to the book
	print_price *$total_qty* ($divide_by_val/100);

	IF ROYALTY == GROSS
	$contributor_portion = $total_profit;
	
	--TOTAL ROYALTIES DUE
	
	IF ROYALTY == NET,COVER PRICE
	contributor_portion - advace

	IF ROYALTY == GROSS
	(total profit & divide_val /100)-advance
	
	
	balance end of quarter = contributor's amount + balance of prev quarter.
	*/


	?>
	
</Body>
<style>
 tr th ,  tr td
 {	
 	padding: 5px;
 }

 h4
 {
 	text-transform: uppercase;
 }
 
 .table_view
 {
 	 width:100%; 
 	 margin-bottom:30px;
 }
 p
 {
 	margin-bottom:5px;
 	display: block;
 }

.no_break_week{
	page-break-before: always;
}

</style>
<script>

</script>
</html> 