<? include "top.php"; ?>
<!DOCTYPE html>
<html>
<head>
	<?php include('include/head.php'); ?>
	<title>Financial Year Master</title>
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/jquery.dataTables.css">
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/dataTables.bootstrap4.css">
	<link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/responsive.dataTables.css">
</head>
<body>
	<?php include('include/header.php'); ?>

	<?php include('include/sidebar.php');

	$action=$_REQUEST['action'];
	
	// Handle Save Action
	if($action=='save'){
		if($psave==1){
			$fy_start_date=$_POST['fy_start_date'];
			$fy_end_date=$_POST['fy_end_date'];
			$fy_label=$_POST['fy_label'];
			
			// Check if label already exists
			$check_label=f(q("SELECT * FROM tbl_financial_year_master WHERE fy_label='$fy_label'"));
			if($check_label){
				echo "<script>alert('Financial Year with this label already exists!');</script>";
			}else{
				q("INSERT INTO tbl_financial_year_master SET 
					fy_start_date='$fy_start_date',
					fy_end_date='$fy_end_date',
					fy_label='$fy_label',
					fy_is_active='0'");
				echo "<script>alert('Financial Year added successfully!');</script>";
			}
		}else{
			echo "<script>alert('You are not authorized to Save!');</script>";
		}
		
	// Handle Update Action
	}elseif($action=='update'){
		if($pupdate==1){
			$fy_id=$_REQUEST['fy_id'];
			$fy_start_date=$_POST['fy_start_date'];
			$fy_end_date=$_POST['fy_end_date'];
			$fy_label=$_POST['fy_label'];
			
			// Check if label already exists for other records
			$check_label=f(q("SELECT * FROM tbl_financial_year_master WHERE fy_label='$fy_label' AND fy_id!='$fy_id'"));
			if($check_label){
				echo "<script>alert('Financial Year with this label already exists!');</script>";
			}else{
				q("UPDATE tbl_financial_year_master SET 
					fy_start_date='$fy_start_date',
					fy_end_date='$fy_end_date',
					fy_label='$fy_label'
					WHERE fy_id='$fy_id'");
				echo "<script>alert('Financial Year updated successfully!');</script>";
			}
		}else{
			echo "<script>alert('You are not authorized to Update!');</script>";
		}
		
	// Handle Activate Action
	}elseif($action=='activate'){
		if($psave==1 || $pupdate==1){
			$fy_id=$_REQUEST['fy_id'];
			
			// Deactivate all financial years first
			q("UPDATE tbl_financial_year_master SET fy_is_active='0'");
			
			// Activate the selected financial year
			q("UPDATE tbl_financial_year_master SET fy_is_active='1' WHERE fy_id='$fy_id'");
			
			echo "<script>alert('Financial Year activated successfully!');</script>";
		}else{
			echo "<script>alert('You are not authorized to perform this action!');</script>";
		}
		
	// Handle Delete Action
	}elseif($action=='delete'){
		if($psave==1 || $pupdate==1){
			$fy_id=$_REQUEST['fy_id'];
			
			// Check if this is the active financial year
			$check_active=f(q("SELECT * FROM tbl_financial_year_master WHERE fy_id='$fy_id' AND fy_is_active='1'"));
			if($check_active){
				echo "<script>alert('Cannot delete the active financial year. Please activate another financial year first.');</script>";
			}else{
				q("DELETE FROM tbl_financial_year_master WHERE fy_id='$fy_id'");
				echo "<script>alert('Financial Year deleted successfully!');</script>";
			}
		}else{
			echo "<script>alert('You are not authorized to delete!');</script>";
		}
	}
	
	// Handle Edit Action
	if($action=='edit'){
		$fy_id=$_REQUEST['fy_id'];
		$edit=f(q("SELECT * FROM tbl_financial_year_master WHERE fy_id='$fy_id'"));
	}
	?>
	<div class="main-container">
		<div class="pd-ltr-20 customscroll customscroll-10-p height-100-p xs-pd-20-10">
			<div="min-height-200px">
				<div class="page-header">
					<div class="row">
						<div class="col-md-6 col-sm-12">
							<div class="title">
								<h4>Financial Year Master</h4>
							</div>
							<nav aria-label="breadcrumb" role="navigation">
								<ol class="breadcrumb">
									<li class="breadcrumb-item"><a href="index.php">Home</a></li>
									<li class="breadcrumb-item"><a href="javascript:;">Masters</a></li>
									<li class="breadcrumb-item active" aria-current="page">Financial Year Master</li>
								</ol>
							</nav>
						</div>
						<div class="col-md-6 col-sm-12 text-right">
						</div>
					</div>
				</div>
				
				<!-- Form Section Start -->
				<div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
					<form action="<?=$_SERVER['PHP_SELF']?>?action=<?php if($action=='edit'){?>update&fy_id=<?php echo $fy_id?><?php }else{?>save<?php } ?>" method="POST">
						<div class="clearfix" style="min-height: 30px;"></div>
						
						<div class="form-group row">
							<label class="col-sm-12 col-md-3 col-form-label">Financial Year Label</label>
							<div class="col-sm-12 col-md-9">
								<input class="form-control" type="text" name="fy_label" placeholder="e.g., 2025-2026" value="<?=$edit['fy_label']?>" required>
								<small class="text-muted">Format: YYYY-YYYY (e.g., 2025-2026)</small>
							</div>
						</div>
						
						<div class="form-group row">
							<label class="col-sm-12 col-md-3 col-form-label">Start Date</label>
							<div class="col-sm-12 col-md-9">
								<input class="form-control date-picker" type="text" name="fy_start_date" placeholder="Select Start Date" value="<?=$edit['fy_start_date']?>" required>
								<small class="text-muted">Typically April 1st of the starting year</small>
							</div>
						</div>
						
						<div class="form-group row">
							<label class="col-sm-12 col-md-3 col-form-label">End Date</label>
							<div class="col-sm-12 col-md-9">
								<input class="form-control date-picker" type="text" name="fy_end_date" placeholder="Select End Date" value="<?=$edit['fy_end_date']?>" required>
								<small class="text-muted">Typically March 31st of the ending year</small>
							</div>
						</div>
						
						<?php if($edit['fy_is_active']=='1'){ ?>
						<div class="form-group row">
							<label class="col-sm-12 col-md-3 col-form-label">Status</label>
							<div class="col-sm-12 col-md-9">
								<span class="badge badge-success">Active</span>
								<small class="text-muted">This is the currently active financial year</small>
							</div>
						</div>
						<?php } ?>
						
						<div class="clearfix">
							<div class="pull-left">
							</div>
							<div class="pull-right">
								<button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-save"></i> Save / Update</button>
								<?php if($action=='edit'){ ?>
								<a href="<?=$_SERVER['PHP_SELF']?>" class="btn btn-secondary btn-sm"><i class="fa fa-times"></i> Cancel</a>
								<?php } ?>
							</div>
						</div>
					</form>
				</div>
				<!-- Form Section End -->
				
				<!-- List Section Start -->
				<div class="pd-20 bg-white border-radius-4 box-shadow mb-30">
					<div class="clearfix mb-20">
						<div class="pull-left">
							<h5 class="text-blue">Financial Year List</h5>
						</div>
					</div>
					<div class="row">
						<table class="stripe hover multiple-select-row data-table-export nowrap">
							<thead>
								<tr>
									<th class="table-plus datatable-nosort">Label</th>
									<th>Start Date</th>
									<th>End Date</th>
									<th>Status</th>
									<th>Created Date</th>
									<th>Action</th>
								</tr>
							</thead>
							<tbody>
								<?
									$getfy=mysqli_query($con,"SELECT * FROM tbl_financial_year_master ORDER BY fy_start_date DESC");
									while($arr=mysqli_fetch_array($getfy)){
										$status_badge = $arr['fy_is_active']=='1' ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-secondary">Inactive</span>';
										$activate_btn = $arr['fy_is_active']!='1' ? '<a href="'.$_SERVER['PHP_SELF'].'?action=activate&fy_id='.$arr['fy_id'].'" onclick="return confirm(\'Activate this financial year? Bills will be filtered based on this selection.\');" class="btn btn-success btn-sm">Activate</a>' : '';
								?>
								<tr>
									<td class="table-plus"><?=$arr['fy_label']?></td>
									<td><?=date('d-M-Y', strtotime($arr['fy_start_date']))?></td>
									<td><?=date('d-M-Y', strtotime($arr['fy_end_date']))?></td>
									<td><?=$status_badge?></td>
									<td><?=date('d-M-Y H:i', strtotime($arr['fy_created_at']))?></td>
									<td>
										<?=$activate_btn?>
										<a href="<?=$_SERVER['PHP_SELF']?>?action=edit&fy_id=<?=$arr['fy_id']?>" class="btn btn-primary btn-sm">Edit</a>
										<?php if($arr['fy_is_active']!='1'){ ?>
										<a href="<?=$_SERVER['PHP_SELF']?>?action=delete&fy_id=<?=$arr['fy_id']?>" onclick="return confirm('Are you sure you want to delete this financial year?');" class="btn btn-danger btn-sm">Delete</a>
										<?php } ?>
									</td>
								</tr>
								<? } ?>
							</tbody>
						</table>
					</div>
				</div>
				<!-- List Section End -->

			</div>
			<?php include('include/footer.php'); ?>
		</div>
	</div>
	<?php include('include/script.php'); ?>
	<script src="src/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
	<script src="src/plugins/datatables/media/js/dataTables.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/dataTables.responsive.js"></script>
	<script src="src/plugins/datatables/media/js/responsive.bootstrap4.js"></script>
	<!-- buttons for Export datatable -->
	<script src="src/plugins/datatables/media/js/button/dataTables.buttons.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.bootstrap4.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.print.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.html5.js"></script>
	<script src="src/plugins/datatables/media/js/button/buttons.flash.js"></script>
	<script src="src/plugins/datatables/media/js/button/pdfmake.min.js"></script>
	<script src="src/plugins/datatables/media/js/button/vfs_fonts.js"></script>
	<script>
		$('document').ready(function(){
			$('.data-table').DataTable({
				scrollCollapse: true,
				autoWidth: false,
				responsive: true,
				columnDefs: [{
					targets: "datatable-nosort",
					orderable: false,
				}],
				"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
				"language": {
					"info": "_START_-_END_ of _TOTAL_ entries",
					searchPlaceholder: "Search"
				},
			});
			$('.data-table-export').DataTable({
				scrollCollapse: true,
				autoWidth: false,
				responsive: true,
				columnDefs: [{
					targets: "datatable-nosort",
					orderable: false,
				}],
				"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
				"language": {
					"info": "_START_-_END_ of _TOTAL_ entries",
					searchPlaceholder: "Search"
				},
				dom: 'Bfrtip',
				buttons: [
				'copy', 'csv', 'pdf', 'print'
				]
			});
			var table = $('.select-row').DataTable();
			$('.select-row tbody').on('click', 'tr', function () {
				if ($(this).hasClass('selected')) {
					$(this).removeClass('selected');
				}
				else {
					table.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			});
			var multipletable = $('.multiple-select-row').DataTable();
			$('.multiple-select-row tbody').on('click', 'tr', function () {
				$(this).toggleClass('selected');
			});
		});
	</script>
</body>
</html>
