<?php include 'db.php'; ?>
<?php include 'layout.php'; ?>

<body>
<div class="main-wrapper">
	<div class="page-wrapper">
		<div class="content">
			<div class="page-header">
				<div class="page-title">
					<h4>Customer Payments</h4>
					<h6>Enter payments per invoice or as total</h6>
				</div>
			</div>

			<!-- Customer Selection -->
			<div class="row mb-3">
				<div class="col-md-6">
					<div class="d-flex gap-2">
						<?php if (!empty($_GET['customer_id'])): ?>
						<?php
							$cid = intval($_GET['customer_id']);
							$customer = $conn->query("SELECT * FROM customers WHERE id = $cid")->fetch_assoc();
							?>
							<span class="badge bg-success fs-6 d-flex align-items-center">
								<i class="fa fa-user me-1"></i> <?= htmlspecialchars($customer['name']) ?>
							</span>
							<a href="customer_payments.php" class="btn btn-outline-secondary btn-sm">
								<i class="fa fa-times"></i> Clear
							</a>
						<?php else: ?>
							<div class="alert alert-info mb-0 d-flex align-items-center">
								<i class="fa fa-info-circle me-2"></i>
								<span>Please select a customer to view their outstanding payments</span>
							</div>
						<?php endif; ?>
					</div>
				</div>
				</div>

			<?php if (!empty($_GET['customer_id'])): ?>
			<?php
			$cid = intval($_GET['customer_id']);
			$customer = $conn->query("SELECT * FROM customers WHERE id = $cid")->fetch_assoc();
			$outstanding = $conn->query("SELECT * FROM cus_outstanding WHERE customer_id = $cid AND status != 'paid' ORDER BY sale_id ASC");

			$rows = [];
			$total_outstanding = 0;
			while ($row = $outstanding->fetch_assoc()) {
				$rows[] = $row;
				$total_outstanding += $row['amount'];
			}
			?>

			<div class="card">
				<div class="card-header">
					<h5>Outstanding for: <?php echo $customer['name']; ?></h5>
					<p>Total Outstanding: <strong>Rs <?php echo number_format($total_outstanding, 2); ?></strong></p>
				</div>
				<div class="card-body">
					<?php if (count($rows)): ?>
					<form method="POST" action="make_group_payment.php">
						<input type="hidden" name="customer_id" value="<?php echo $cid; ?>">

						<table class="table table-bordered">
							<thead>
								<tr>
									<th>Invoice</th>
									<th>Outstanding</th>
									<th>Status</th>
									<th>Enter Payment (Optional)</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ($rows as $row): ?>
								<tr>
									<td>#<?php echo $row['sale_id']; ?></td>
									<td>Rs <?php echo number_format($row['amount'], 2); ?></td>
									<td><?php echo ucfirst($row['status']); ?></td>
									<td>
										<input type="hidden" name="sale_ids[]" value="<?php echo $row['sale_id']; ?>">
										<input type="hidden" name="sale_amounts[<?php echo $row['sale_id']; ?>]" value="<?php echo $row['amount']; ?>">
										<input type="number" step="0.01" name="invoice_payments[<?php echo $row['sale_id']; ?>]" class="form-control" placeholder="Rs">
									</td>
								</tr>
								<?php endforeach; ?>
							</tbody>
						</table>

						<div class="row">
							<div class="col-md-4 mb-3">
								<label>Total Amount (Optional)</label>
								<input type="number" step="0.01" name="amount_paid" class="form-control" placeholder="If not entered above">
							</div>
							<div class="col-md-8 mb-3">
								<label>Remarks</label>
								<input type="text" name="remarks" class="form-control" placeholder="Payment remarks">
							</div>
						</div>
<div class="row">
	<div class="col-md-4 mb-3">
		<label>Payment Method</label>
		<select name="payment_method" class="form-select" onchange="toggleBankAccount(this.value)">
			<option value="cash">Cash</option>
			<option value="bank">Bank</option>
			<option value="card">Card</option>
			<option value="upi">UPI</option>
			<option value="credit">Credit</option>
		</select>
	</div>

	<div class="col-md-4 mb-3 d-none" id="bank-account-wrapper">
		<label>Bank Account</label>
		<select name="bank_account_id" class="form-select">
			<option value="">-- Select Bank --</option>
			<?php
			$banks = $conn->query("SELECT id, bank_name FROM bank_accounts WHERE is_active = 1");
			while ($b = $banks->fetch_assoc()) {
				echo "<option value='{$b['id']}'>" . htmlspecialchars($b['bank_name']) . "</option>";
			}
			?>
		</select>
	</div>
</div>

<script>
function toggleBankAccount(method) {
	const wrapper = document.getElementById('bank-account-wrapper');
	const show = ['bank', 'card', 'upi'].includes(method);
	wrapper.classList.toggle('d-none', !show);
}
</script>

						<button type="submit" class="btn btn-success">Submit Payment</button>
					</form>
					<?php else: ?>
						<p>No outstanding dues for this customer.</p>
					<?php endif; ?>
				</div>
			</div>
			<?php endif; ?>
		</div>
	</div>
</div>

<!-- Customer Search Modal -->
<div class="modal fade" id="customerSearchModal" tabindex="-1" aria-labelledby="customerSearchModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="customerSearchModalLabel">
                    <i class="fa fa-search me-2"></i>Search Customer
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="customerSearchInput" class="form-label">Search by Name or Phone</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="customerSearchInput" placeholder="Type customer name or phone number..." autofocus>
                        <button class="btn btn-outline-secondary" type="button" id="clearSearchBtn">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>
                
                <!-- Search Status -->
                <div id="searchStatus" class="alert alert-info" style="display: none;">
                    <i class="fa fa-info-circle me-2"></i>
                    <span id="searchStatusMessage">Type to search customers...</span>
                </div>
                
                <!-- Recent Customers -->
                <div id="recentCustomers" style="display: none;">
                    <h6 class="mb-3">Recent Customers</h6>
                    <div id="recentCustomersList" class="list-group">
                        <!-- Recent customers will be populated here -->
                    </div>
                </div>
                
                <!-- Search Results -->
                <div id="searchResults" style="display: none;">
                    <h6 class="mb-3">Search Results (<span id="resultCount">0</span>)</h6>
                    <div id="customerResultsList" class="list-group">
                        <!-- Results will be populated here -->
                    </div>
                </div>
                
                <!-- Loading Indicator -->
                <div id="searchLoading" class="text-center" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 text-muted">Searching customers...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

<?php if (isset($_GET['success'])): ?>
<script>
Swal.fire({
	title: 'Payment Successful',
	text: 'Customer payments recorded.',
	icon: 'success',
	timer: 2500,
	showConfirmButton: false
});
</script>
<?php endif; ?>

<script>
$(document).ready(function() {
    let searchTimeout = null;
    
    // Auto-open search modal if no customer is selected
    <?php if (empty($_GET['customer_id'])): ?>
        $('#customerSearchModal').modal('show');
    <?php endif; ?>
    
    // Clear search input
    $('#clearSearchBtn').click(function() {
        $('#customerSearchInput').val('').focus();
        hideAllElements();
        loadRecentCustomers();
    });
    
    // Handle search input
    $('#customerSearchInput').on('input', function() {
        const searchTerm = $(this).val().trim();
        
        // Clear previous timeout
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }
        
        if (!searchTerm) {
            hideAllElements();
            loadRecentCustomers();
            return;
        }
        
        // Show loading
        showSearchLoading();
        
        // Set timeout for search (debounce)
        searchTimeout = setTimeout(() => {
            performCustomerSearch(searchTerm);
        }, 300);
    });
    
    // Handle Enter key
    $('#customerSearchInput').on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            const searchTerm = $(this).val().trim();
            if (searchTerm) {
                performCustomerSearch(searchTerm);
            }
        }
    });
    
    // Perform customer search
    function performCustomerSearch(searchTerm) {
        const formData = new FormData();
        formData.append('action', 'search');
        formData.append('search_term', searchTerm);
        
        fetch('ajax/pos_customer_search.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            hideSearchLoading();
            
            if (data.success) {
                displaySearchResults(data.customers, data.count);
            } else {
                showSearchStatus('Error: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            hideSearchLoading();
            showSearchStatus('Error occurred while searching customers.', 'danger');
            console.error('Error:', error);
        });
    }
    
    // Display search results
    function displaySearchResults(customers, count) {
        const resultsList = $('#customerResultsList');
        resultsList.empty();
        
        if (count === 0) {
            showSearchStatus('No customers found matching your search.', 'warning');
            return;
        }
        
        customers.forEach(customer => {
            const customerItem = $(`
                <div class="list-group-item list-group-item-action customer-result-item" 
                     data-customer-id="${customer.id}" 
                     data-customer-name="${customer.name}">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${customer.name}</h6>
                        <small class="text-muted">ID: ${customer.id}</small>
                    </div>
                    <div class="mb-1">
                        ${customer.phone ? `<i class="fa fa-phone me-1"></i>${customer.phone}` : ''}
                        ${customer.email ? `<i class="fa fa-envelope me-1 ms-2"></i>${customer.email}` : ''}
                    </div>
                    ${customer.address ? `<small class="text-muted"><i class="fa fa-map-marker-alt me-1"></i>${customer.address}</small>` : ''}
                </div>
            `);
            
            resultsList.append(customerItem);
        });
        
        // Add click handler for results
        $('.customer-result-item').click(function() {
            const customerId = $(this).data('customer-id');
            const customerName = $(this).data('customer-name');
            
            // Redirect to payments with selected customer
            window.location.href = `customer_payments.php?customer_id=${customerId}`;
        });
        
        showSearchResults(count);
    }
    
    // Load recent customers
    function loadRecentCustomers() {
        const formData = new FormData();
        formData.append('action', 'search');
        formData.append('search_term', ''); // Empty search term to get recent customers
        
        fetch('ajax/pos_customer_search.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayRecentCustomers(data.customers);
            } else {
                showSearchStatus('Error: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showSearchStatus('Error occurred while loading customers.', 'danger');
            console.error('Error:', error);
        });
    }
    
    // Display recent customers
    function displayRecentCustomers(customers) {
        const recentList = $('#recentCustomersList');
        recentList.empty();
        
        if (customers.length === 0) {
            showSearchStatus('No customers found.', 'warning');
            return;
        }
        
        // Show only first 10 customers
        const recentCustomers = customers.slice(0, 10);
        
        recentCustomers.forEach(customer => {
            const customerItem = $(`
                <div class="list-group-item list-group-item-action customer-result-item" 
                     data-customer-id="${customer.id}" 
                     data-customer-name="${customer.name}">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${customer.name}</h6>
                        <small class="text-muted">ID: ${customer.id}</small>
                    </div>
                    <div class="mb-1">
                        ${customer.phone ? `<i class="fa fa-phone me-1"></i>${customer.phone}` : ''}
                        ${customer.email ? `<i class="fa fa-envelope me-1 ms-2"></i>${customer.email}` : ''}
                    </div>
                    ${customer.address ? `<small class="text-muted"><i class="fa fa-map-marker-alt me-1"></i>${customer.address}</small>` : ''}
                </div>
            `);
            
            recentList.append(customerItem);
        });
        
        // Add click handler for recent customers
        $('.customer-result-item').click(function() {
            const customerId = $(this).data('customer-id');
            const customerName = $(this).data('customer-name');
            
            // Redirect to payments with selected customer
            window.location.href = `customer_payments.php?customer_id=${customerId}`;
        });
        
        showRecentCustomers();
    }
    
    // Show/hide functions
    function showSearchLoading() {
        hideAllElements();
        $('#searchLoading').show();
    }
    
    function hideSearchLoading() {
        $('#searchLoading').hide();
    }
    
    function showSearchResults(count) {
        hideAllElements();
        $('#resultCount').text(count);
        $('#searchResults').show();
    }
    
    function showRecentCustomers() {
        hideAllElements();
        $('#recentCustomers').show();
    }
    
    function showSearchStatus(message, type) {
        hideAllElements();
        $('#searchStatusMessage').text(message);
        $('#searchStatus').removeClass('alert-info alert-warning alert-danger').addClass(`alert-${type}`).show();
    }
    
    function hideAllElements() {
        $('#searchLoading').hide();
        $('#searchResults').hide();
        $('#recentCustomers').hide();
        $('#searchStatus').hide();
    }
    
    // Focus input when modal is shown
    $('#customerSearchModal').on('shown.bs.modal', function() {
        $('#customerSearchInput').focus();
        // Load recent customers when modal opens
        loadRecentCustomers();
    });
    
    // Clear search when modal is hidden
    $('#customerSearchModal').on('hidden.bs.modal', function() {
        $('#customerSearchInput').val('');
        hideAllElements();
        
        // If no customer is selected and modal is closed, redirect to prevent empty state
        <?php if (empty($_GET['customer_id'])): ?>
            // Optional: You can redirect or show a message here
            // window.location.href = 'index.php';
        <?php endif; ?>
    });
});
</script>
</body>
</html>
