<?php include 'db_connect.php';

// Get debt statistics
$total_debt = $conn->query("SELECT SUM(balance) as total FROM debt_list WHERE status != 'paid'")->fetch_assoc()['total'] ?? 0;
$pending_count = $conn->query("SELECT COUNT(*) as count FROM debt_list WHERE status = 'pending'")->fetch_assoc()['count'] ?? 0;
$partial_count = $conn->query("SELECT COUNT(*) as count FROM debt_list WHERE status = 'partial'")->fetch_assoc()['count'] ?? 0;
$paid_today = $conn->query("SELECT SUM(amount) as total FROM debt_payments WHERE DATE(date_created) = CURDATE()")->fetch_assoc()['total'] ?? 0;

// Get customers for lookup
$customers = [];
$cust_qry = $conn->query("SELECT * FROM customer_list ORDER BY name ASC");
while($row = $cust_qry->fetch_assoc()){
	$customers[$row['id']] = $row;
}
?>

<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);">
				<i class="fas fa-file-invoice-dollar mr-2"></i>Debt Management
			</h2>
			<p class="text-muted mb-0">Track and manage customer debts (Madeni)</p>
		</div>
	</div>

	<!-- Stats Cards -->
	<div class="row mb-4">
		<div class="col-md-3">
			<div class="modern-card" style="border-left: 4px solid var(--danger);">
				<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(239, 68, 68, 0.15), rgba(239, 68, 68, 0.05)); color: var(--danger); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
							<i class="fas fa-money-bill-wave"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700; color: var(--danger);">TZS <?php echo number_format($total_debt, 0); ?></h3>
							<small class="text-muted">Total Outstanding Debt</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; background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(245, 158, 11, 0.05)); color: var(--warning); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
							<i class="fas fa-clock"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;"><?php echo number_format($pending_count); ?></h3>
							<small class="text-muted">Pending Debts</small>
						</div>
					</div>
				</div>
			</div>
		</div>
		<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; background: linear-gradient(135deg, rgba(99, 102, 241, 0.15), rgba(99, 102, 241, 0.05)); color: var(--primary); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
							<i class="fas fa-hourglass-half"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;"><?php echo number_format($partial_count); ?></h3>
							<small class="text-muted">Partial Payments</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; background: linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(34, 197, 94, 0.05)); color: var(--success); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
							<i class="fas fa-check-circle"></i>
						</div>
						<div>
							<h3 class="mb-0" style="font-weight: 700;">TZS <?php echo number_format($paid_today, 0); ?></h3>
							<small class="text-muted">Collected Today</small>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Debts Table -->
	<div class="modern-card">
		<div class="card-header">
			<h3 class="card-title">
				<i class="fas fa-list mr-2"></i>
				Outstanding Debts
			</h3>
			<div class="d-flex">
				<select id="filter_status" class="form-control form-control-sm mr-2" style="width: 150px;">
					<option value="">All Status</option>
					<option value="pending">Pending</option>
					<option value="partial">Partial</option>
					<option value="paid">Paid</option>
				</select>
			</div>
		</div>
		<div class="card-body p-0">
			<div class="table-responsive">
				<table class="table table-hover mb-0" id="debts-table">
					<thead>
						<tr>
							<th style="padding-left: 24px;">Customer</th>
							<th>Sale Ref#</th>
							<th>Date</th>
							<th class="text-right">Total Amount</th>
							<th class="text-right">Paid</th>
							<th class="text-right">Balance</th>
							<th class="text-center">Status</th>
							<th class="text-center" style="padding-right: 24px;">Actions</th>
						</tr>
					</thead>
					<tbody>
						<?php
						$debts = $conn->query("SELECT d.*, s.ref_no, s.date_updated as sale_date
							FROM debt_list d
							INNER JOIN sales_list s ON s.id = d.sales_id
							ORDER BY d.status ASC, d.date_created DESC");
						while($row = $debts->fetch_assoc()):
							$status_class = $row['status'] == 'paid' ? 'success' : ($row['status'] == 'partial' ? 'primary' : 'warning');
							$status_icon = $row['status'] == 'paid' ? 'check-circle' : ($row['status'] == 'partial' ? 'hourglass-half' : 'clock');
						?>
						<tr data-status="<?php echo $row['status']; ?>">
							<td style="padding-left: 24px;">
								<div class="d-flex align-items-center">
									<div class="customer-avatar mr-3" style="width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, var(--primary), #4f46e5); display: flex; align-items: center; justify-content: center; color: white; font-weight: 600;">
										<?php echo strtoupper(substr($customers[$row['customer_id']]['name'] ?? 'U', 0, 1)); ?>
									</div>
									<div>
										<strong><?php echo htmlspecialchars($customers[$row['customer_id']]['name'] ?? 'Unknown'); ?></strong>
										<?php if(isset($customers[$row['customer_id']]['contact'])): ?>
										<br><small class="text-muted"><i class="fas fa-phone mr-1"></i><?php echo htmlspecialchars($customers[$row['customer_id']]['contact']); ?></small>
										<?php endif; ?>
									</div>
								</div>
							</td>
							<td>
								<code class="text-primary"><?php echo htmlspecialchars($row['ref_no']); ?></code>
							</td>
							<td>
								<div><?php echo date("M d, Y", strtotime($row['sale_date'])); ?></div>
								<small class="text-muted"><?php echo date("h:i A", strtotime($row['sale_date'])); ?></small>
							</td>
							<td class="text-right">
								<strong>TZS <?php echo number_format($row['total_amount'], 0); ?></strong>
							</td>
							<td class="text-right">
								<span class="text-success">TZS <?php echo number_format($row['amount_paid'], 0); ?></span>
							</td>
							<td class="text-right">
								<strong class="text-danger" style="font-size: 1.1rem;">TZS <?php echo number_format($row['balance'], 0); ?></strong>
							</td>
							<td class="text-center">
								<span class="badge badge-<?php echo $status_class; ?>" style="padding: 6px 12px;">
									<i class="fas fa-<?php echo $status_icon; ?> mr-1"></i>
									<?php echo ucfirst($row['status']); ?>
								</span>
							</td>
							<td class="text-center" style="padding-right: 24px;">
								<div class="btn-group">
									<?php if($row['status'] != 'paid'): ?>
									<button class="btn btn-sm btn-success pay_debt" data-id="<?php echo $row['id']; ?>" data-balance="<?php echo $row['balance']; ?>" data-customer="<?php echo htmlspecialchars($customers[$row['customer_id']]['name'] ?? 'Unknown'); ?>" title="Make Payment">
										<i class="fas fa-money-bill-wave"></i>
									</button>
									<?php endif; ?>
									<button class="btn btn-sm btn-light view_history" data-id="<?php echo $row['id']; ?>" title="View Payment History">
										<i class="fas fa-history"></i>
									</button>
									<a href="index.php?page=pos&id=<?php echo $row['sales_id']; ?>" class="btn btn-sm btn-light" title="View Sale">
										<i class="fas fa-eye"></i>
									</a>
								</div>
							</td>
						</tr>
						<?php endwhile; ?>
					</tbody>
				</table>
			</div>
		</div>
	</div>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
	<div class="modal-dialog" role="document">
		<div class="modal-content" style="border-radius: 16px; border: none;">
			<div class="modal-header" style="background: linear-gradient(135deg, var(--success), #16a34a); color: white; border-radius: 16px 16px 0 0;">
				<h5 class="modal-title"><i class="fas fa-money-bill-wave mr-2"></i>Make Payment</h5>
				<button type="button" class="close text-white" data-dismiss="modal">
					<span>&times;</span>
				</button>
			</div>
			<form id="payment-form">
				<div class="modal-body">
					<input type="hidden" name="debt_id" id="debt_id">

					<div class="text-center mb-4 p-3" style="background: var(--gray-100); border-radius: 12px;">
						<small class="text-muted d-block">Customer</small>
						<h5 class="mb-2" id="modal_customer"></h5>
						<small class="text-muted d-block">Outstanding Balance</small>
						<h3 class="text-danger mb-0" id="modal_balance"></h3>
					</div>

					<div class="form-group">
						<label class="form-label">Payment Amount <span class="text-danger">*</span></label>
						<div class="input-group input-group-lg">
							<div class="input-group-prepend">
								<span class="input-group-text">TZS</span>
							</div>
							<input type="number" name="amount" id="payment_amount" class="form-control text-right" step="1" min="1" required style="font-size: 1.5rem; font-weight: 600;">
						</div>
					</div>

					<div class="form-group">
						<label class="form-label">Payment Method</label>
						<select name="payment_method" class="form-control">
							<option value="cash">Cash</option>
							<option value="bank_transfer">Bank Transfer</option>
							<option value="mobile_money">Mobile Money</option>
						</select>
					</div>

					<div class="form-group">
						<label class="form-label">Remarks (Optional)</label>
						<textarea name="remarks" class="form-control" rows="2" placeholder="Any notes about this payment..."></textarea>
					</div>

					<!-- Quick Amount Buttons -->
					<div class="mb-3">
						<label class="form-label">Quick Amount</label>
						<div class="d-flex flex-wrap">
							<button type="button" class="btn btn-outline-secondary btn-sm m-1 quick-pay" data-amount="1000">1,000</button>
							<button type="button" class="btn btn-outline-secondary btn-sm m-1 quick-pay" data-amount="2000">2,000</button>
							<button type="button" class="btn btn-outline-secondary btn-sm m-1 quick-pay" data-amount="5000">5,000</button>
							<button type="button" class="btn btn-outline-secondary btn-sm m-1 quick-pay" data-amount="10000">10,000</button>
							<button type="button" class="btn btn-outline-primary btn-sm m-1" id="pay_full">Full Amount</button>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
					<button type="submit" class="btn btn-success">
						<i class="fas fa-check mr-1"></i> Process Payment
					</button>
				</div>
			</form>
		</div>
	</div>
</div>

<!-- History Modal -->
<div class="modal fade" id="historyModal" tabindex="-1" role="dialog">
	<div class="modal-dialog modal-lg" role="document">
		<div class="modal-content" style="border-radius: 16px; border: none;">
			<div class="modal-header" style="background: var(--gray-100); border-radius: 16px 16px 0 0;">
				<h5 class="modal-title"><i class="fas fa-history mr-2"></i>Payment History</h5>
				<button type="button" class="close" data-dismiss="modal">
					<span>&times;</span>
				</button>
			</div>
			<div class="modal-body" id="history_content">
				<div class="text-center py-4">
					<i class="fas fa-spinner fa-spin fa-2x"></i>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
			</div>
		</div>
	</div>
</div>

<style>
	#debts-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;
	}

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

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

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

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

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

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

<script>
	$(document).ready(function(){
		$('#debts-table').DataTable({
			"order": [[6, "asc"], [2, "desc"]],
			"pageLength": 15,
			"language": {
				"search": "",
				"searchPlaceholder": "Search debts...",
				"lengthMenu": "Show _MENU_",
				"info": "Showing _START_ to _END_ of _TOTAL_ debts",
				"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'
		});
	});

	// Filter by status
	$('#filter_status').on('change', function(){
		var status = $(this).val();
		if(status == ''){
			$('#debts-table tbody tr').show();
		} else {
			$('#debts-table tbody tr').hide();
			$('#debts-table tbody tr[data-status="'+status+'"]').show();
		}
	});

	// Pay debt
	$('.pay_debt').click(function(){
		var id = $(this).data('id');
		var balance = $(this).data('balance');
		var customer = $(this).data('customer');

		$('#debt_id').val(id);
		$('#modal_customer').text(customer);
		$('#modal_balance').text(parseFloat(balance).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
		$('#payment_amount').attr('max', balance).val('');

		$('#paymentModal').modal('show');
	});

	// Quick pay buttons
	$('.quick-pay').click(function(){
		var amount = parseFloat($(this).data('amount'));
		var max = parseFloat($('#payment_amount').attr('max'));
		$('#payment_amount').val(Math.min(amount, max));
	});

	$('#pay_full').click(function(){
		var max = parseFloat($('#payment_amount').attr('max'));
		$('#payment_amount').val(max);
	});

	// Submit payment
	$('#payment-form').submit(function(e){
		e.preventDefault();

		var amount = parseFloat($('#payment_amount').val());
		var max = parseFloat($('#payment_amount').attr('max'));

		if(amount <= 0){
			alert_toast("Please enter a valid amount", 'danger');
			return false;
		}

		if(amount > max){
			alert_toast("Amount cannot exceed balance of " + max.toLocaleString('en-US', {minimumFractionDigits: 2}), 'danger');
			return false;
		}

		start_load();
		$.ajax({
			url: 'ajax.php?action=pay_debt',
			method: 'POST',
			data: $(this).serialize(),
			success: function(resp){
				if(resp == 1){
					alert_toast("Payment recorded successfully!", 'success');
					setTimeout(function(){
						location.reload();
					}, 1500);
				} else {
					alert_toast("Error processing payment", 'danger');
					end_load();
				}
			},
			error: function(){
				alert_toast("Connection error", 'danger');
				end_load();
			}
		});
	});

	// View payment history
	$('.view_history').click(function(){
		var id = $(this).data('id');
		$('#history_content').html('<div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x"></i></div>');
		$('#historyModal').modal('show');

		$.ajax({
			url: 'get_debt_history.php?id=' + id,
			success: function(resp){
				$('#history_content').html(resp);
			}
		});
	});
</script>
