<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

session_start();

// Check if config file exists
if (!file_exists('includes/config.php')) {
    die('Error: config.php file not found');
}

include_once('includes/config.php');

// Check database connection
if (!isset($con) || !$con) {
    die('Error: Database connection not established');
}

if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$area = isset($_GET['area']) ? trim($_GET['area']) : '';
$customerType = isset($_GET['type']) ? trim($_GET['type']) : 'Retail';

// Validate customer type
if (!in_array($customerType, ['Retail', 'Shop'])) {
    $customerType = 'Retail';
}

// Validate area parameter
if (empty($area)) {
    error_log('Area parameter is empty, redirecting to customer-areas.php');
    header('location: customer-areas.php?type=' . urlencode($customerType));
    exit();
}

// Simplified query without window functions - should work on older MySQL versions
$customersQuery = "
    SELECT 
        c.ID,
        c.CustomerName,
        c.Mobile,
        c.AlternativePhone,
        c.Area,
        c.Address,
        c.CustomerType,
        c.CreatedDate,
        COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0) as TotalCredit,
        COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) as TotalDebit,
        (COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) - 
         COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0)) as OutstandingAmount
    FROM tblcustomers c
    LEFT JOIN tblcustomerpayments p ON c.ID = p.CustomerID AND p.IsActive = 1
    WHERE c.Area = ? AND c.CustomerType = ? AND c.IsActive = 1 
    GROUP BY c.ID, c.CustomerName, c.Mobile, c.AlternativePhone, c.Area, c.Address, c.CustomerType, c.CreatedDate
    ORDER BY c.CustomerName
";

// Add comprehensive error handling for the database query
try {
    error_log("Preparing customer query for area: '$area', type: '$customerType'");
    
    $stmt = mysqli_prepare($con, $customersQuery);
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . mysqli_error($con));
    }
    
    $bindResult = mysqli_stmt_bind_param($stmt, "ss", $area, $customerType);
    if (!$bindResult) {
        throw new Exception('Bind param failed: ' . mysqli_stmt_error($stmt));
    }
    
    $executeResult = mysqli_stmt_execute($stmt);
    if (!$executeResult) {
        throw new Exception('Execute failed: ' . mysqli_stmt_error($stmt));
    }
    
    $customersResult = mysqli_stmt_get_result($stmt);
    if (!$customersResult) {
        throw new Exception('Get result failed: ' . mysqli_stmt_error($stmt));
    }
    
    error_log("Customer query executed successfully");
    
} catch (Exception $e) {
    error_log('Database query error in area-customers-simple.php: ' . $e->getMessage());
    die('Database query failed: ' . htmlspecialchars($e->getMessage()));
}

// Get customer count and outstanding summary
$customerCount = mysqli_num_rows($customersResult);
error_log("Found $customerCount customers for area '$area'");

// Calculate summary statistics
$totalOutstanding = 0;
$totalAdvance = 0;
$outstandingCustomers = 0;
$advanceCustomers = 0;

// Reset result pointer to calculate statistics
try {
    mysqli_data_seek($customersResult, 0);
    while ($row = mysqli_fetch_assoc($customersResult)) {
        $outstanding = floatval($row['OutstandingAmount'] ?? 0);
        if ($outstanding > 0) {
            $totalOutstanding += $outstanding;
            $outstandingCustomers++;
        } elseif ($outstanding < 0) {
            $totalAdvance += abs($outstanding);
            $advanceCustomers++;
        }
    }
    
    // Reset result pointer for main loop
    mysqli_data_seek($customersResult, 0);
    error_log("Statistics calculated successfully");
    
} catch (Exception $e) {
    error_log('Error calculating statistics: ' . $e->getMessage());
    // Continue execution even if statistics fail
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mariyappa Nadar Ricemill | <?php echo htmlspecialchars($area); ?> - <?php echo $customerType; ?> Customers</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <style>
        /* Full-height layout to utilize viewport height */
        html, body, #wrapper, #content-wrapper, #content {
            height: 100%;
        }

        /* Compact global paddings */
        .container-fluid {
            padding: 8px 10px;
        }

        .customer-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 8px;
            overflow: hidden;
        }
        
        .customer-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .customer-card-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            padding: 8px 10px;
            position: relative;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .customer-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border: 1px solid rgba(255,255,255,0.3);
            flex-shrink: 0;
        }
        
        .customer-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .customer-name {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .customer-type-badge {
            background: rgba(255,255,255,0.2);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
        }
        
        .customer-card-body {
            padding: 8px 10px;
        }
        
        .customer-info {
            margin-bottom: 6px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 0.78rem;
        }
        
        .info-item i {
            width: 14px;
            color: #6c757d;
            margin-right: 8px;
            font-size: 0.75rem;
        }
        
        .info-item .value {
            color: #495057;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .outstanding-amount {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-block;
            margin-top: 4px;
            min-width: 60px;
            text-align: center;
        }
        
        .outstanding-amount.advance {
            background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
        }
        
        .outstanding-amount.zero {
            background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
        }
        
        .customer-actions {
            border-top: 1px solid #f0f0f0;
            padding: 6px 8px;
            background: #fafafa;
            display: flex;
            gap: 6px;
        }
        
        .pos-btn {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        
        .pos-btn:hover {
            background: linear-gradient(135deg, #218838 0%, #1e7e34 100%);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .details-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .details-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }

        .collect-btn {
            background: linear-gradient(135deg, #ff9900 0%, #ff8c00 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        .collect-btn:hover { filter: brightness(0.95); color: #fff; text-decoration: none; transform: translateY(-1px); }
        
        .back-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 6px 10px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            margin-bottom: 12px;
            font-size: 0.85rem;
        }
        
        .back-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        
        .search-box {
            background: white;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .search-input {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 30px 6px 10px;
            font-size: 0.85rem;
            transition: all 0.2s ease;
        }
        
        .search-input:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78,115,223,0.25);
        }
        
        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        /* Tighter grid gutters for compact look */
        #customersGrid {
            margin-left: -6px;
            margin-right: -6px;
        }
        #customersGrid > .col-6 {
            padding-left: 6px;
            padding-right: 6px;
        }

        @media (max-width: 768px) {
            .customer-card-body {
                padding: 8px;
            }
            
            .customer-actions {
                padding: 6px 8px;
                gap: 4px;
            }
            
            .pos-btn {
                flex: 2;
                padding: 6px 8px;
                font-size: 0.74rem;
            }
            
            .details-btn {
                flex: 1;
                padding: 6px 6px;
                font-size: 0.74rem;
            }
            
            .customer-name {
                font-size: 0.82rem;
            }
            
            .info-item {
                font-size: 0.75rem;
                margin-bottom: 4px;
            }
            
            .page-header {
                padding: 10px 12px;
            }
            
            .search-box {
                padding: 8px;
                margin-bottom: 10px;
            }

            /* Show only icons on very small screens for ultra-compact look */
            .pos-btn .btn-text { display: none; }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Back Button -->
                    <a href="customer-areas.php?type=<?php echo $customerType; ?>" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to Areas
                    </a>
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h1 class="h5 mb-1">
                                    <i class="fas fa-users mr-2"></i>
                                    <?php echo htmlspecialchars($area); ?> - <?php echo $customerType; ?>
                                </h1>
                                <p class="mb-0" style="font-size: 0.85rem; opacity: 0.9;">
                                    <?php echo number_format($customerCount); ?> customer<?php echo $customerCount != 1 ? 's' : ''; ?> found
                                </p>
                            </div>
                            <a href="customer-management.php" class="btn btn-light btn-sm">
                                <i class="fas fa-plus mr-1"></i>Add
                            </a>
                        </div>
                    </div>

                    <!-- Search Box -->
                    <div class="search-box">
                        <div class="position-relative">
                            <input type="text" class="form-control search-input" id="customerSearch" placeholder="Search customers, mobile, or outstanding amount...">
                            <i class="fas fa-search search-icon"></i>
                        </div>
                        <div class="mt-2 text-center">
                            <button type="button" class="btn btn-warning btn-sm mr-2" onclick="filterOutstandingCustomers()">
                                <i class="fas fa-exclamation-triangle mr-1"></i>Outstanding Only
                            </button>
                            <button type="button" class="btn btn-success btn-sm mr-2" onclick="filterAdvanceCustomers()">
                                <i class="fas fa-arrow-down mr-1"></i>Advance Only
                            </button>
                            <button type="button" class="btn btn-secondary btn-sm" onclick="showAllCustomers()">
                                <i class="fas fa-users mr-1"></i>Show All
                            </button>
                        </div>
                    </div>

                    <!-- Customers Grid -->
                    <div class="row" id="customersGrid">
                        <?php if ($customerCount > 0): ?>
                            <?php while ($customer = mysqli_fetch_assoc($customersResult)): ?>
                            <div class="col-6 customer-item" 
                                 id="customer-item-<?php echo $customer['ID']; ?>"
                                 data-name="<?php echo strtolower(htmlspecialchars($customer['CustomerName'])); ?>"
                                 data-mobile="<?php echo htmlspecialchars($customer['Mobile']); ?>"
                                 data-alt-phone="<?php echo htmlspecialchars($customer['AlternativePhone'] ?? ''); ?>"
                                 data-outstanding="<?php echo $customer['OutstandingAmount']; ?>">
                                <div class="customer-card">
                                    <div class="customer-card-header">
                                        <div class="customer-avatar">
                                            <i class="fas fa-user"></i>
                                        </div>
                                        <div class="customer-header-info">
                                            <div class="customer-name"><?php echo htmlspecialchars($customer['CustomerName']); ?></div>
                                            <div class="customer-type-badge"><?php echo substr($customer['CustomerType'], 0, 1); ?></div>
                                        </div>
                                    </div>
                                    
                                    <div class="customer-card-body">
                                        <div class="customer-info">
                                            <div class="info-item">
                                                <i class="fas fa-phone"></i>
                                                <span class="value"><?php echo htmlspecialchars($customer['Mobile']); ?></span>
                                            </div>
                                            
                                            <div class="info-item">
                                                <i class="fas fa-map-marker-alt"></i>
                                                <span class="value"><?php echo htmlspecialchars($customer['Area']); ?></span>
                                            </div>
                                            
                                            <div class="info-item">
                                                <i class="fas fa-home"></i>
                                                <span class="value"><?php echo htmlspecialchars(substr($customer['Address'], 0, 25)); ?><?php echo strlen($customer['Address']) > 25 ? '...' : ''; ?></span>
                                            </div>
                                            
                                            <div class="info-item">
                                                <i class="fas fa-balance-scale"></i>
                                                <span class="value">
                                                    <?php 
                                                    $outstandingAmount = $customer['OutstandingAmount'];
                                                    if ($outstandingAmount > 0): ?>
                                                        <span class="outstanding-amount" id="outstanding-amt-<?php echo $customer['ID']; ?>">₹<?php echo number_format($outstandingAmount, 0); ?></span>
                                                    <?php elseif ($outstandingAmount < 0): ?>
                                                        <span class="outstanding-amount advance" id="outstanding-amt-<?php echo $customer['ID']; ?>">₹<?php echo number_format(abs($outstandingAmount), 0); ?> Adv</span>
                                                    <?php else: ?>
                                                        <span class="outstanding-amount zero" id="outstanding-amt-<?php echo $customer['ID']; ?>">₹0</span>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="customer-actions">
                                        <a href="pos.php?customer_id=<?php echo $customer['ID']; ?>" class="pos-btn">
                                            <i class="fas fa-cash-register"></i><span class="btn-text">POS</span>
                                        </a>
                                        <button type="button" class="collect-btn" onclick="openPaymentCollectModal(<?php echo $customer['ID']; ?>, '<?php echo htmlspecialchars($customer['CustomerName'], ENT_QUOTES); ?>')">
                                            <i class="fas fa-rupee-sign"></i><span class="btn-text">Collect</span>
                                        </button>
                                        <a href="transaction-history.php?customer_id=<?php echo $customer['ID']; ?>" class="details-btn">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="text-center py-4">
                                    <i class="fas fa-users fa-2x text-muted mb-2"></i>
                                    <h5 class="text-muted">No Customers Found</h5>
                                    <p class="text-muted mb-3">No <?php echo strtolower($customerType); ?> customers in <?php echo htmlspecialchars($area); ?>.</p>
                                    <a href="customer-management.php" class="btn btn-primary btn-sm">
                                        <i class="fas fa-plus mr-1"></i>Add Customer
                                    </a>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>
    <?php include_once('includes/footer2.php');?>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>

    <script>
        $(document).ready(function() {
            // Hide sidebar on load for a focused, full-width mobile-like view
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            if ($('.sidebar').hasClass('toggled')) {
                $('.sidebar .collapse').collapse('hide');
            }

            // Add animation on page load
            $('.customer-card').each(function(index) {
                $(this).css('opacity', '0').css('transform', 'translateY(30px)');
                $(this).delay(index * 50).animate({
                    opacity: 1
                }, 400, function() {
                    $(this).css('transform', 'translateY(0)');
                });
            });
            
            // Search functionality
            $('#customerSearch').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.customer-item').each(function() {
                    const customerName = $(this).data('name') || '';
                    const mobile = $(this).data('mobile') || '';
                    const altPhone = $(this).data('alt-phone') || '';
                    const outstanding = $(this).data('outstanding') || 0;
                    
                    const isMatch = customerName.toString().toLowerCase().includes(searchTerm) || 
                                   mobile.toString().toLowerCase().includes(searchTerm) || 
                                   altPhone.toString().toLowerCase().includes(searchTerm) ||
                                   outstanding.toString().includes(searchTerm);
                    
                    if (isMatch) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
            
            // POS button click effect
            $('.pos-btn').on('click', function() {
                $(this).html('<i class="fas fa-spinner fa-spin mr-2"></i>Loading POS...');
            });
        });
        
        // Filter functions
        function filterOutstandingCustomers() {
            $('.customer-item').each(function() {
                const outstanding = parseFloat($(this).data('outstanding')) || 0;
                if (outstanding > 0) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
        
        function filterAdvanceCustomers() {
            $('.customer-item').each(function() {
                const outstanding = parseFloat($(this).data('outstanding')) || 0;
                if (outstanding < 0) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
        
        function showAllCustomers() {
            $('.customer-item').show();
            $('#customerSearch').val('');
        }

        // Open Collect Payment modal for a customer
        function openPaymentCollectModal(customerId, customerName) {
            alert('Payment collection feature requires the full modal implementation. Customer: ' + customerName);
        }
    </script>
</body>
</html>
