<?php include 'db_connect.php';

// Get sales statistics
$today_sales = $conn->query("SELECT COUNT(*) as count, SUM(total_amount) as total FROM sales_list WHERE DATE(date_updated) = CURDATE()")->fetch_assoc();
$month_sales = $conn->query("SELECT COUNT(*) as count, SUM(total_amount) as total FROM sales_list WHERE MONTH(date_updated) = MONTH(CURDATE()) AND YEAR(date_updated) = YEAR(CURDATE())")->fetch_assoc();

// Get customers for lookup
$customer = $conn->query("SELECT * FROM customer_list order by name asc");
while($row=$customer->fetch_assoc()):
	$cus_arr[$row['id']] = $row['name'];
endwhile;
$cus_arr[0] = "Walk-in Customer";
?>

<div class="container-fluid">
	<!-- Page Header -->
	<div class="d-flex justify-content-between align-items-center mb-4">
		<div>
			<h2 class="mb-1" style="font-weight: 700; color: var(--gray-800);">Sales Management</h2>
			<p class="text-muted mb-0">Track and manage all sales transactions</p>
		</div>
		<button class="btn btn-primary btn-lg" id="new_sales" style="border-radius: 12px; padding: 12px 24px;">
			<i class="fas fa-plus mr-2"></i> New Sale
		</button>
	</div>

	<!-- Stats Cards -->
	<div class="row mb-4">
		<div class="col-md-3">
			<div class="modern-card" style="border-left: 4px solid var(--primary);">
				<div class="card-body">
					<div class="d-flex align-items-center">
						<div class="stat-icon primary mr-3" style="width: 50px; height: 50px; font-size: 1.2rem;">
							<i class="fas fa-shopping-cart"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;"><?php echo number_format($today_sales['count'] ?? 0); ?></h3>
							<small class="text-muted">Today's Transactions</small>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="modern-card" style="border-left: 4px solid var(--success);">
				<div class="card-body">
					<div class="d-flex align-items-center">
						<div class="stat-icon success mr-3" style="width: 50px; height: 50px; font-size: 1.2rem;">
							<i class="fas fa-peso-sign"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;"><?php echo number_format($today_sales['total'] ?? 0, 2); ?></h3>
							<small class="text-muted">Today's Revenue</small>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="modern-card" style="border-left: 4px solid var(--warning);">
				<div class="card-body">
					<div class="d-flex align-items-center">
						<div class="stat-icon warning mr-3" style="width: 50px; height: 50px; font-size: 1.2rem;">
							<i class="fas fa-calendar-alt"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;"><?php echo number_format($month_sales['count'] ?? 0); ?></h3>
							<small class="text-muted">This Month</small>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-3">
			<div class="modern-card" style="border-left: 4px solid #06b6d4;">
				<div class="card-body">
					<div class="d-flex align-items-center">
						<div class="stat-icon mr-3" style="width: 50px; height: 50px; font-size: 1.2rem; background: linear-gradient(135deg, rgba(6, 182, 212, 0.15), rgba(6, 182, 212, 0.05)); color: #06b6d4;">
							<i class="fas fa-chart-line"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;"><?php echo number_format($month_sales['total'] ?? 0, 2); ?></h3>
							<small class="text-muted">Monthly Revenue</small>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Sales Table -->
	<div class="modern-card">
		<div class="card-header">
			<h3 class="card-title">
				<i class="fas fa-receipt mr-2"></i>
				Sales History
			</h3>
		</div>
		<div class="card-body p-0">
			<div class="table-responsive">
				<table class="table table-hover mb-0" id="sales-table">
					<thead>
						<tr>
							<th style="padding-left: 24px;">Reference #</th>
							<th>Date & Time</th>
							<th class="d-none">Sort Date</th>
							<th>Customer</th>
							<th>Items</th>
							<th class="text-right">Amount</th>
							<th class="text-center">Status</th>
							<th class="text-center" style="padding-right: 24px;">Actions</th>
						</tr>
					</thead>
					<tbody>
					<?php
						$sales = $conn->query("SELECT s.*,
							(SELECT COUNT(*) FROM inventory WHERE type=2 AND form_id = s.id) as item_count
							FROM sales_list s ORDER BY s.date_updated DESC");
						while($row=$sales->fetch_assoc()):
					?>
						<tr>
							<td style="padding-left: 24px;">
								<div class="d-flex align-items-center">
									<div class="sale-icon mr-3" style="width: 40px; height: 40px; border-radius: 10px; background: linear-gradient(135deg, var(--primary), #4f46e5); display: flex; align-items: center; justify-content: center;">
										<i class="fas fa-receipt text-white"></i>
									</div>
									<div>
										<strong style="font-size: 0.95rem;"><?php echo htmlspecialchars($row['ref_no']); ?></strong>
									</div>
								</div>
							</td>
							<td>
								<div><?php echo date("M d, Y", strtotime($row['date_updated'])); ?></div>
								<small class="text-muted"><?php echo date("h:i A", strtotime($row['date_updated'])); ?></small>
							</td>
							<td class="d-none"><?php echo strtotime($row['date_updated']); ?></td>
							<td>
								<div class="d-flex align-items-center">
									<div class="customer-avatar mr-2" style="width: 32px; height: 32px; border-radius: 50%; background: var(--gray-200); display: flex; align-items: center; justify-content: center;">
										<i class="fas fa-user text-muted" style="font-size: 0.8rem;"></i>
									</div>
									<span><?php echo isset($cus_arr[$row['customer_id']]) ? htmlspecialchars($cus_arr[$row['customer_id']]) : 'N/A'; ?></span>
								</div>
							</td>
							<td>
								<span class="badge badge-light" style="font-size: 0.85rem; padding: 6px 12px;">
									<?php echo $row['item_count']; ?> item<?php echo $row['item_count'] != 1 ? 's' : ''; ?>
								</span>
							</td>
							<td class="text-right">
								<strong style="color: var(--success); font-size: 1rem;">
									<?php echo number_format($row['total_amount'], 2); ?>
								</strong>
							</td>
							<td class="text-center">
								<span class="badge badge-success" style="padding: 6px 12px;">
									<i class="fas fa-check-circle mr-1"></i> Completed
								</span>
							</td>
							<td class="text-center" style="padding-right: 24px;">
								<div class="btn-group">
									<a class="btn btn-sm btn-light" href="index.php?page=pos&id=<?php echo $row['id']; ?>" title="View/Edit">
										<i class="fas fa-eye"></i>
									</a>
									<button class="btn btn-sm btn-light print_receipt" data-id="<?php echo $row['id']; ?>" title="Print Receipt">
										<i class="fas fa-print"></i>
									</button>
									<button class="btn btn-sm btn-light text-danger delete_sales" data-id="<?php echo $row['id']; ?>" title="Delete">
										<i class="fas fa-trash"></i>
									</button>
								</div>
							</td>
						</tr>
					<?php endwhile; ?>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<style>
	#sales-table thead th {
		background: var(--gray-50);
		border-bottom: 2px solid var(--gray-200);
		font-weight: 600;
		font-size: 0.75rem;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--gray-600);
		padding: 16px 12px;
	}

	#sales-table tbody td {
		padding: 16px 12px;
		vertical-align: middle;
		border-bottom: 1px solid var(--gray-100);
	}

	#sales-table tbody tr:hover {
		background: var(--gray-50);
	}

	.btn-group .btn {
		border-radius: 8px !important;
		margin: 0 2px;
		padding: 8px 12px;
	}

	.btn-group .btn:hover {
		background: var(--gray-200);
	}

	.stat-icon {
		border-radius: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.stat-icon.primary {
		background: linear-gradient(135deg, rgba(99, 102, 241, 0.15), rgba(99, 102, 241, 0.05));
		color: var(--primary);
	}

	.stat-icon.success {
		background: linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(34, 197, 94, 0.05));
		color: var(--success);
	}

	.stat-icon.warning {
		background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(245, 158, 11, 0.05));
		color: var(--warning);
	}

	@media (max-width: 768px) {
		.d-flex.justify-content-between {
			flex-direction: column;
			gap: 1rem;
		}

		.d-flex.justify-content-between > div:first-child {
			text-align: center;
		}

		#new_sales {
			width: 100%;
		}

		.row.mb-4 .col-md-3 {
			margin-bottom: 1rem;
		}
	}
</style>

<script>
	$(document).ready(function(){
		$('#sales-table').DataTable({
			"order": [[2, "desc"]],
			"pageLength": 15,
			"columnDefs": [
				{ "targets": 2, "visible": false }
			],
			"language": {
				"search": "",
				"searchPlaceholder": "Search sales...",
				"lengthMenu": "Show _MENU_",
				"info": "Showing _START_ to _END_ of _TOTAL_ sales",
				"paginate": {
					"previous": "<i class='fas fa-chevron-left'></i>",
					"next": "<i class='fas fa-chevron-right'></i>"
				}
			}
		});

		$('.dataTables_filter input').addClass('form-control').css({
			'width': '250px',
			'display': 'inline-block',
			'border-radius': '10px'
		});
	});

	$('#new_sales').click(function(){
		location.href = "index.php?page=pos";
	});

	$('.print_receipt').click(function(){
		var id = $(this).attr('data-id');
		var nw = window.open("print_sales.php?id=" + id, "_blank", "height=700,width=900");
		nw.print();
	});

	$('.delete_sales').click(function(){
		_conf("Are you sure you want to delete this sale?", "delete_sales", [$(this).attr('data-id')]);
	});

	function delete_sales($id){
		start_load();
		$.ajax({
			url: 'ajax.php?action=delete_sales',
			method: 'POST',
			data: {id: $id},
			success: function(resp){
				if(resp == 1){
					alert_toast("Sale deleted successfully", 'success');
					setTimeout(function(){
						location.reload();
					}, 1500);
				}
			}
		});
	}
</script>
