<?php
	if(isset($_GET['update'])){$getExpensesId = $_GET['update'];}
?>

<div class="right_col" role="main">
    <div class="">
        <div class="page-title">
            <div class="title_left">
            <h3>Users <small>Some examples to get you started</small></h3>
            </div>

            <div class="title_right">
            <div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search">
                <div class="input-group">
                <input type="text" class="form-control" placeholder="Search for...">
                <span class="input-group-btn">
                    <button class="btn btn-default" type="button">Go!</button>
                </span>
                </div>
            </div>
            </div>
        </div>

        <div class="clearfix"></div>

        <div class="row">
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="x_panel">
                <div class="x_title">
                    <h2>By Author</h2>
                    <ul class="nav navbar-right panel_toolbox">
                    <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                        <ul class="dropdown-menu" role="menu">
                        <li><a href="#">Settings 1</a>
                        </li>
                        <li><a href="#">Settings 2</a>
                        </li>
                        </ul>
                    </li>
                    <li><a class="close-link"><i class="fa fa-close"></i></a>
                    </li>
                    </ul>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">

                    <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                        <th>#</th>
                        <th>Author</th>
                        <th>Total</th>
                        <th>Unpaid</th>
                        <th>Paid</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            $sql = "SELECT SUM(re_amount) AS total, a_id, re_claim_by FROM room_expenses WHERE re_claim_by IS NOT NULL AND re_claim_by!=0 GROUP BY re_claim_by";
                            $result = mysqli_query($conn,$sql);
                            while($row = mysqli_fetch_assoc($result)){
                        ?>
                        <tr>
                        <th scope="row"><?php echo ++$no; ?></th>
                        <td><a href="?pagecontent=expenses_report&claimby=<?php echo $row['re_claim_by']; ?>"><?php echo getDetailByTable('staffs',$row['re_claim_by'])['s_nickname']; ?></a></td>
                        <td><?php echo "RM ".$row['total']; ?></td>
                        <td><a href="?pagecontent=expenses_report&claimby=<?php echo $row['re_claim_by']; ?>"><span style="color: red; font-weight: bold;"><?php echo totalExpensesUnpaid($row['re_claim_by']); ?></span></a></td>
                        <td><?php echo totalExpensesPaid($row['re_claim_by']); ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                    </table>

                </div>
                </div>
            </div> 
        </div>

        <?php if(isset($_POST['payselected'])){ ?>
        <div class="row">
            <div class="col-md-6 col-sm-6 col-xs-12">
                <div class="x_panel">
                <div class="x_title">
                    <h2>Selected</h2>
                    <ul class="nav navbar-right panel_toolbox">
                    <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                    </li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                        <ul class="dropdown-menu" role="menu">
                        <li><a href="#">Settings 1</a>
                        </li>
                        <li><a href="#">Settings 2</a>
                        </li>
                        </ul>
                    </li>
                    <li><a class="close-link"><i class="fa fa-close"></i></a>
                    </li>
                    </ul>
                    <div class="clearfix"></div>
                </div>
                <div class="x_content">

                    <table class="table table-striped">
                    <thead>
                        <tr>
                        <th>#</th>
                        <th>Author</th>
                        <th>Total</th>
                        <th>Room</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            $no = 0;
                            $totalAmount = 0;
                            $options = $_POST['option']; $_SESSION['option'] = $options;
                            foreach($options AS $option){
                        ?>
                        <tr>
                        <th scope="row"><?php echo ++$no; ?></th>
                        <td><?php echo urldecode(getDetailByTable('room_expenses',$option)['re_title']); ?></td>
                        <td><?php echo "RM ".$amount = getDetailByTable('room_expenses',$option)['re_amount']; $totalAmount += $amount;?></td>
                        <td><?php if($row['r_id']){echo getDetailByTable('rooms',getDetailByTable('room_expenses',$option)['r_id'])['r_no'];}else{echo "GENERAL";} ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                    <tfoot>
                        <tr>
                        <th></th>
                        <th>TOTAL</th>
                        <th><?php if($totalAmount){echo "RM ".$totalAmount;} ?></th>
                        <th></th>
                        </tr>
                    </tfoot>
                    </table>

                </div>
                </div>
            </div> 
        
                <div class="col-md-6 col-sm-12 col-xs-12">
                    <div class="x_panel">
                        <div class="x_title">
                            <h2>Claim</h2>
                            <div class="clearfix"></div>
                        </div>
                        <div class="x_content">
                            <form class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
                                <input type="hidden" name="option" value="<?php echo $_POST['option']; ?>">
                                
                                <div class="item form-group">
                                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="price">Amount 
                                    </label>
                                    <div class="col-md-4 col-sm-3 col-xs-12">
                                        <?php echo "RM ".$totalAmount; ?>
                                    </div>
                                </div>
                                
                                <div class="item form-group">
                                    <label class="control-label col-md-3 col-sm-3 col-xs-12" for="upload">Upload 
                                    </label>
                                    <div class="col-md-4 col-sm-3 col-xs-12">
                                        <input id="upload" class="form-control col-md-3 col-xs-12" name="fileToUpload" type="file" value="">
                                    </div>
                                </div>

                                <div class="ln_solid"></div>

                                <div class="form-group">
                                    <div class="col-md-6 col-md-offset-3">
                                        <input type="submit" class="btn btn-success" name="uploadBtn" value="Submit">
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
        </div>
        <?php } ?>
        
        <?php
        //UPLOAD RECEIPT
        if(isset($_POST['uploadBtn'])){

            if(getDetailByTable("room_expenses",$getExpensesId)['re_claim_file']){
                $expensesFilename = getDetailByTable("room_expenses",$getExpensesId)['re_claim_file'];
                unlink("uploads/claim/".$expensesFilename);
            }

            //image resize
            if(is_array($_FILES)) {

                $uploadedFile = $_FILES['fileToUpload']['tmp_name']; 
                $sourceProperties = getimagesize($uploadedFile);
                $imageType = $sourceProperties[2];

                switch ($imageType) {

                    case IMAGETYPE_PNG:
                        $imageSrc = imagecreatefrompng($uploadedFile); 
                        imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
                        break;           

                    case IMAGETYPE_JPEG:
                        $imageSrc = imagecreatefromjpeg($uploadedFile); 
                        imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
                        break;

                    case IMAGETYPE_GIF:
                        $imageSrc = imagecreatefromgif($uploadedFile); 
                        imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
                        break;

                    default:
                        echo "Invalid Image type.";
                        exit;
                        break;
                }
            }

            //upload receipt
            $errors = array();
            $file_name = $_FILES['fileToUpload']['name'];
            $file_size =$_FILES['fileToUpload']['size'];
            $file_tmp = $_FILES['fileToUpload']['tmp_name'];
            $file_type = $_FILES['fileToUpload']['type'];

            $file_ext = strtolower(end(explode('.',$_FILES['fileToUpload']['name'])));

            $extensions = array("jpeg","jpg","png");
            
                $claimDate = date('Y-m-d');

            if(in_array($file_ext,$extensions)=== false){
                $errors[] = "extension not allowed, please choose a JPEG or PNG file.";
            }

            if($file_size > 2097152){
                $errors[] = 'File size must be excately 2 MB';
            }

                $file_name = "MUL_".time().".".$file_ext;
                $filePath = "uploads/claim/".$file_name;

            if(empty($errors) == true){

                if(move_uploaded_file($file_tmp,$filePath)){

                    foreach($_SESSION['option'] AS $getExpensesId){
                        mysqli_query($conn, "UPDATE room_expenses SET re_claim_file='$file_name', re_claim_status=1, re_claimed_at='$claimDate' WHERE re_id=$getExpensesId");
                    }

                    $adminName = $_SESSION['admin'][1] ?: $_SESSION['staff']['s_nickname'];

                    foreach($_SESSION['option'] AS $getExpensesId){
                        $list = getDetailByTable("room_expenses",$getExpensesId)['re_title'].",";
                    }

                    sendMessage2(-1001209156913,$adminName." upload claim for

    Title : ".urldecode($list)."
    ");
                    sendPhoto(-1001209156913,"https://admin.homestay.dzvisual.my/production/".$filePath);

                    // expensesLog($getRoomId,0,$adminName." upload claim record for ".$expensesTitle);
                }
            }

            $claimBy = getDetailByTable("room_expenses",$getExpensesId)['re_claim_by'];
            header("Location: ?pagecontent=expenses_report&claimby=$claimBy"); 
        }
        ?>

        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12">
				<div class="x_panel">
					<div class="x_content">
                        <form method="post">
						<table id="datatable" class="table table-striped">
							<thead>
								<tr>
                                    <th>C/K</th>
                                    <th>Date</th>
									<th>Title</th>
									<th>Room</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Claim By</th>
                                    <th>Action</th>
								</tr>
							</thead>
							<tbody>
								<?php
                                    $totalAmount = 0;

                                    $sql = "SELECT * FROM room_expenses WHERE re_claim_by IS NOT NULL AND re_claim_by!=0";

                                    if(isset($_GET['claimby'])){
                                        $adminId = $_GET['claimby'];
                                        $sql = "SELECT * FROM room_expenses WHERE re_claim_by=$adminId ORDER BY re_claim_status ASC";
                                    }

									$result = mysqli_query($conn,$sql);
									while($row = mysqli_fetch_assoc($result)){
								?>
								<tr>
									<td>
                                        <?php if($row['re_claim_status'] == 0){ ?>
                                        <input type="checkbox" name="option[]" value="<?php echo $row['re_id'];?>"></td>
                                        <?php } ?>
									<td><?php echo $row['re_date'];?></td>
									<td><?php echo urldecode($row['re_title']);?></td>
									<td>
                                        <a href="?pagecontent=expenses&room=<?php echo $row['r_id']; ?>">
                                            <?php if($row['r_id']){echo getDetailByTable('rooms',$row['r_id'])['r_no'];}else{echo "GENERAL";} ?>
                                        </a>
                                    </td>
									<td>RM <?php echo $amount = $row['re_amount']; $totalAmount += $amount; ?></td>
									<td>
										<?php 
											switch($row['re_claim_status']){
												case 0: $title = "NO RECORD"; $color="red"; break;
												case 1: $title = "SENT"; $color="blue"; break;
											}
										?>
										<span style="font-weight: bold; color: <?php echo $color; ?>;"><?php echo $title; ?></span>
									</td>
									<td><?php echo getDetailFromTable('staffs',$row['re_claim_by'])['s_nickname']; ?></td>
									<td>
										<a href="?pagecontent=expenses_claim&update=<?php echo $row['re_id']; ?>" class="btn btn-primary btn-xs">UPDATE</a>
									</td>
								</tr>
								<?php
									}
										?>
                                        
								<tr>
									<th colspan="3">Total</th>
									<th>RM <?php echo $totalAmount ? $totalAmount : 0; ?></th>
									<th colspan="2">
										<button name="payselected" class="btn btn-xs btn-primary">PAY SELECTED</button>
                                    </th>
								</tr>
						</table>
                        </form>
					</div>
				</div>
			</div>


        </div>
    </div>
</div>

<?php
	if(isset($_REQUEST['withdraw'])){
		
		$expensesFilename = getDetailByTable("room_expenses",$expensesId)['re_claim_file'];
		unlink("uploads/claim/".$expensesFilename);
		
		$expensesId = $_REQUEST['withdraw'];
		mysqli_query($conn,"UPDATE room_expenses SET re_claim_file=NULL, re_claim_status=0, re_claimed_at=NULL WHERE re_id=$expensesId");
		
		header("Location: ?pagecontent=expenses_claim&payback=$expensesId");
	}

	function imageResize($imageSrc,$imageWidth,$imageHeight){

		$newImageWidth =200;
		$newImageHeight =200;

		$newImageLayer=imagecreatetruecolor($newImageWidth,$newImageHeight);
		imagecopyresampled($newImageLayer,$imageSrc,0,0,0,0,$newImageWidth,$newImageHeight,$imageWidth,$imageHeight);

		return $newImageLayer;
	}

    function totalExpensesUnpaid($userId){
        global $conn;
        $result = mysqli_query($conn,"SELECT SUM(re_amount) AS total FROM room_expenses WHERE re_claim_by=$userId AND re_claim_status IS NULL");
        $total = mysqli_fetch_assoc($result)['total'];
        return $total ? "RM ".$total : "-";
    }

    function totalExpensesPaid($userId){
        global $conn;
        $result = mysqli_query($conn,"SELECT SUM(re_amount) AS total FROM room_expenses WHERE re_claim_by=$userId AND re_claim_status IS NOT NULL");
        $total = mysqli_fetch_assoc($result)['total'];
        return $total ? "RM ".$total : "-";
    }
?>