<?php
session_start();
include_once('includes/config.php');
include_once('includes/quick-menu.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$currentUserId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle customer form submissions
if ($_POST) {
    $action = $_POST['action'];
    $customerID = mysqli_real_escape_string($con, $_POST['customerID']);
    $customerName = mysqli_real_escape_string($con, $_POST['customerName']);
    $contactPerson = mysqli_real_escape_string($con, $_POST['contactPerson']);
    $mobile = mysqli_real_escape_string($con, $_POST['mobile']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $address = mysqli_real_escape_string($con, $_POST['address']);
    $city = mysqli_real_escape_string($con, $_POST['city']);
    $state = mysqli_real_escape_string($con, $_POST['state']);
    $pinCode = mysqli_real_escape_string($con, $_POST['pinCode']);
    $gstNumber = mysqli_real_escape_string($con, $_POST['gstNumber']);
    $panNumber = mysqli_real_escape_string($con, $_POST['panNumber']);
    $customerType = mysqli_real_escape_string($con, $_POST['customerType']);
    $creditLimit = !empty($_POST['creditLimit']) ? (float)$_POST['creditLimit'] : 0;
    $creditDays = !empty($_POST['creditDays']) ? (int)$_POST['creditDays'] : 0;
    $status = mysqli_real_escape_string($con, $_POST['status']);
    
    if ($action == 'create') {
        // Check if CustomerID already exists
        $checkQuery = "SELECT ID FROM tblcustomers WHERE CustomerID = '$customerID'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $error = "Customer ID already exists!";
        } else {
            $insertQuery = "INSERT INTO tblcustomers (CustomerID, CustomerName, ContactPerson, Mobile, Email, Address, City, State, PinCode, GSTNumber, PANNumber, CustomerType, CreditLimit, CreditDays, Status, DateAdded) 
                           VALUES ('$customerID', '$customerName', '$contactPerson', '$mobile', '$email', '$address', '$city', '$state', '$pinCode', '$gstNumber', '$panNumber', '$customerType', $creditLimit, $creditDays, '$status', NOW())";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "Customer added successfully!";
            } else {
                $error = "Error adding customer: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $id = (int)$_POST['id'];
        
        if ($id <= 0) {
            $error = "Invalid customer ID for update.";
        } else {
            // Check if CustomerID already exists for other customers
            $checkQuery = "SELECT ID FROM tblcustomers WHERE CustomerID = '$customerID' AND ID != $id";
            $checkResult = mysqli_query($con, $checkQuery);
            
            if ($checkResult && mysqli_num_rows($checkResult) > 0) {
                $error = "Customer ID already exists!";
            } else {
                $updateQuery = "UPDATE tblcustomers SET 
                               CustomerID = '$customerID',
                               CustomerName = '$customerName',
                               ContactPerson = '$contactPerson',
                               Mobile = '$mobile',
                               Email = '$email',
                               Address = '$address',
                               City = '$city',
                               State = '$state',
                               PinCode = '$pinCode',
                               GSTNumber = '$gstNumber',
                               PANNumber = '$panNumber',
                               CustomerType = '$customerType',
                               CreditLimit = $creditLimit,
                               CreditDays = $creditDays,
                               Status = '$status',
                               LastUpdated = NOW()
                               WHERE ID = $id";
                
                if (mysqli_query($con, $updateQuery)) {
                    if (mysqli_affected_rows($con) >= 0) {
                        $success = "Customer updated successfully!";
                    } else {
                        $error = "No changes were made to the customer.";
                    }
                } else {
                    $error = "Error updating customer: " . mysqli_error($con);
                }
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $customerId = (int)$_GET['delete'];
    
    $deleteQuery = "DELETE FROM tblcustomers WHERE ID = $customerId";
    
    if (mysqli_query($con, $deleteQuery)) {
        $success = "Customer deleted successfully!";
    } else {
        $error = "Error deleting customer: " . mysqli_error($con);
    }
}

// Get all customers
$customersQuery = "SELECT * FROM tblcustomers ORDER BY CustomerName";
$customersResult = mysqli_query($con, $customersQuery);

$customers = [];
$customerStats = ['total' => 0, 'active' => 0, 'inactive' => 0, 'individual' => 0, 'business' => 0];

if ($customersResult) {
    while ($customer = mysqli_fetch_assoc($customersResult)) {
        $customers[] = $customer;
        $customerStats['total']++;
        
        if ($customer['Status'] == 'Active') {
            $customerStats['active']++;
        } else {
            $customerStats['inactive']++;
        }
        
        if ($customer['CustomerType'] == 'Individual') {
            $customerStats['individual']++;
        } else {
            $customerStats['business']++;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>UZRS Inventory | Customer Management</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">
    <link href="css/modern-messagebox.css" rel="stylesheet">
    <?php renderQuickMenuCSS(); ?>
    <style>
        .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, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 10px;
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
        }
        
        .customer-card-header:hover {
            filter: brightness(1.05);
        }
        
        .customer-card-header.individual {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .customer-card-header.business {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
        
        .customer-card-header.government {
            background: linear-gradient(135deg, #30cfd0 0%, #330867 100%);
        }
        
        .customer-card-header.retailer {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        }
        
        .customer-card-header.wholesaler {
            background: linear-gradient(135deg, #ff9a56 0%, #ff6a88 100%);
        }
        
        .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-card-header .expand-icon {
            transition: transform 0.3s ease;
        }
        
        .customer-card-header.expanded .expand-icon {
            transform: rotate(180deg);
        }
        
        .customer-name {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .customer-badge {
            background: rgba(255,255,255,0.2);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
            margin-right: 4px;
        }
        
        .status-badge {
            background: rgba(255,255,255,0.3);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
        }
        
        .customer-card-body {
            padding: 8px 10px;
            display: none;
        }
        
        .customer-card-body.show {
            display: block;
        }
        
        .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;
        }
        
        .info-item .label {
            color: #6c757d;
            margin-right: 4px;
        }
        
        .customer-actions {
            border-top: 1px solid #f0f0f0;
            padding: 6px 8px;
            background: #fafafa;
            display: none;
            gap: 4px;
        }
        
        .customer-actions.show {
            display: flex;
        }
        
        .edit-btn {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 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;
            cursor: pointer;
        }
        
        .delete-btn {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.78rem;
            cursor: pointer;
        }
        
        .search-box {
            background: white;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 16px;
        }
        
        #customersGrid {
            margin-left: -6px;
            margin-right: -6px;
        }
        
        #customersGrid > .col-6 {
            padding-left: 6px;
            padding-right: 6px;
        }

        .credit-highlight {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-weight: 600;
            display: inline-block;
            font-size: 0.75rem;
        }
    </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');?>
                
                <div class="container-fluid">
                    
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <?php renderQuickMenu("Customer Master", "Manage customer database"); ?>
                    
                    <div class="d-flex justify-content-end mb-3">
                        <button class="btn btn-light btn-sm" onclick="openCustomerModal()">
                            <i class="fas fa-plus mr-1"></i>Add Customer
                        </button>
                    </div>

                    <!-- Customer Statistics -->
                    <div class="row mb-3">
                        <div class="col-3">
                            <div class="text-center">
                                <div class="h5 mb-0 text-primary"><?php echo $customerStats['total']; ?></div>
                                <small class="text-muted">Total</small>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="text-center">
                                <div class="h5 mb-0 text-success"><?php echo $customerStats['active']; ?></div>
                                <small class="text-muted">Active</small>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="text-center">
                                <div class="h5 mb-0 text-info"><?php echo $customerStats['individual']; ?></div>
                                <small class="text-muted">Individual</small>
                            </div>
                        </div>
                        <div class="col-3">
                            <div class="text-center">
                                <div class="h5 mb-0 text-warning"><?php echo $customerStats['business']; ?></div>
                                <small class="text-muted">Business</small>
                            </div>
                        </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...">
                            <i class="fas fa-search search-icon" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%);"></i>
                        </div>
                    </div>

                    <!-- Type Filter Buttons -->
                    <div class="mb-3" style="overflow-x: auto; white-space: nowrap; -webkit-overflow-scrolling: touch;">
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary active" onclick="filterCustomers('all')">All</button>
                            <button class="btn btn-outline-info" onclick="filterCustomers('individual')">Individual</button>
                            <button class="btn btn-outline-warning" onclick="filterCustomers('business')">Business</button>
                            <button class="btn btn-outline-success" onclick="filterCustomers('retailer')">Retailer</button>
                            <button class="btn btn-outline-danger" onclick="filterCustomers('wholesaler')">Wholesaler</button>
                            <button class="btn btn-outline-secondary" onclick="filterCustomers('government')">Government</button>
                        </div>
                    </div>

                    <!-- Customers Grid -->
                    <div class="row" id="customersGrid">
                        <?php foreach($customers as $customer): 
                            $typeClass = strtolower(str_replace([' ', '&'], ['', ''], $customer['CustomerType']));
                        ?>
                        <div class="col-6 customer-item" data-type="<?php echo strtolower($customer['CustomerType']); ?>" data-status="<?php echo strtolower($customer['Status']); ?>">
                            <div class="customer-card">
                                <div class="customer-card-header <?php echo $typeClass; ?>">
                                    <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>
                                            <span class="customer-badge"><?php echo htmlspecialchars($customer['CustomerType']); ?></span>
                                            <span class="status-badge"><?php echo $customer['Status']; ?></span>
                                        </div>
                                    </div>
                                    <div style="margin-left: auto; transition: transform 0.3s ease;">
                                        <i class="fas fa-chevron-down expand-icon" style="font-size: 0.8rem;"></i>
                                    </div>
                                </div>
                                <div class="customer-card-body">
                                    <div class="info-item">
                                        <i class="fas fa-barcode"></i>
                                        <span class="value"><?php echo htmlspecialchars($customer['CustomerID']); ?></span>
                                    </div>
                                    <?php if (!empty($customer['ContactPerson'])): ?>
                                    <div class="info-item">
                                        <i class="fas fa-user-tie"></i>
                                        <span class="value"><?php echo htmlspecialchars($customer['ContactPerson']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if (!empty($customer['Mobile'])): ?>
                                    <div class="info-item">
                                        <i class="fas fa-phone"></i>
                                        <span class="value"><a href="tel:<?php echo $customer['Mobile']; ?>"><?php echo htmlspecialchars($customer['Mobile']); ?></a></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if (!empty($customer['Email'])): ?>
                                    <div class="info-item">
                                        <i class="fas fa-envelope"></i>
                                        <span class="value"><?php echo htmlspecialchars($customer['Email']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if (!empty($customer['City'])): ?>
                                    <div class="info-item">
                                        <i class="fas fa-map-marker-alt"></i>
                                        <span class="value"><?php echo htmlspecialchars($customer['City']); ?><?php echo !empty($customer['State']) ? ', ' . htmlspecialchars($customer['State']) : ''; ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if (!empty($customer['GSTNumber'])): ?>
                                    <div class="info-item">
                                        <i class="fas fa-file-invoice"></i>
                                        <span class="value">GST: <?php echo htmlspecialchars($customer['GSTNumber']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($customer['CreditLimit'] > 0): ?>
                                    <div class="info-item">
                                        <span class="credit-highlight">Credit: ₹<?php echo number_format($customer['CreditLimit'], 2); ?> (<?php echo $customer['CreditDays']; ?> days)</span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="customer-actions">
                                    <button class="edit-btn" onclick="editCustomer(<?php echo $customer['ID']; ?>)">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <button class="delete-btn" onclick="deleteCustomer(<?php echo $customer['ID']; ?>, '<?php echo htmlspecialchars($customer['CustomerName']); ?>')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <?php if (empty($customers)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No customers found</h5>
                        <p class="text-muted">Click "Add Customer" to create your first customer</p>
                    </div>
                    <?php endif; ?>

                </div>
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="logout.php">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Customer Modal -->
    <div class="modal fade" id="customerModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="customerModalLabel">
                        <i class="fas fa-user-plus mr-2"></i>Add New Customer
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form method="POST" id="customerForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="id" id="customerId">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerID">Customer ID <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="customerID" name="customerID" required readonly>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" onclick="generateCustomerID()" title="Generate ID">
                                                <i class="fas fa-sync-alt"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <small class="text-muted">Auto-generated (CUST###)</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerName">Customer Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="customerName" name="customerName" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customerType">Customer Type <span class="text-danger">*</span></label>
                                    <select class="form-control" id="customerType" name="customerType" required>
                                        <option value="Individual">Individual</option>
                                        <option value="Business">Business</option>
                                        <option value="Retailer">Retailer</option>
                                        <option value="Wholesaler">Wholesaler</option>
                                        <option value="Government">Government</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="contactPerson">Contact Person</label>
                                    <input type="text" class="form-control" id="contactPerson" name="contactPerson">
                                </div>
                            </div>
                        </div>
        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="mobile">Mobile <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="mobile" name="mobile" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email">Email</label>
                                    <input type="email" class="form-control" id="email" name="email">
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="address">Address</label>
                            <textarea class="form-control" id="address" name="address" rows="2"></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="city">City</label>
                                    <input type="text" class="form-control" id="city" name="city">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="state">State</label>
                                    <input type="text" class="form-control" id="state" name="state">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="pinCode">Pin Code</label>
                                    <input type="text" class="form-control" id="pinCode" name="pinCode">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="gstNumber">GST Number</label>
                                    <input type="text" class="form-control" id="gstNumber" name="gstNumber">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="panNumber">PAN Number</label>
                                    <input type="text" class="form-control" id="panNumber" name="panNumber">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="creditLimit">Credit Limit (₹)</label>
                                    <input type="number" step="0.01" class="form-control" id="creditLimit" name="creditLimit" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="creditDays">Credit Days</label>
                                    <input type="number" class="form-control" id="creditDays" name="creditDays" value="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="status">Status</label>
                                    <select class="form-control" id="status" name="status">
                                        <option value="Active">Active</option>
                                        <option value="Inactive">Inactive</option>
                                    </select>
                                </div>
                            </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-primary" id="submitBtn">
                            <i class="fas fa-save mr-1"></i>Save Customer
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/modern-messagebox.js"></script>
    <script src="js/messagebox-wrapper.js"></script>
    <?php renderQuickMenuScript(); ?>

    <script>
        $(document).ready(function() {
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');

            $('.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)');
                });
            });
            
            // Toggle customer details on header click
            $(document).on('click', '.customer-card-header', function(e) {
                // Prevent toggling when clicking on buttons
                if ($(e.target).closest('.edit-btn, .delete-btn').length) {
                    return;
                }
                
                const card = $(this).closest('.customer-card');
                const cardBody = card.find('.customer-card-body');
                const cardActions = card.find('.customer-actions');
                const header = $(this);
                
                // Toggle expanded state
                header.toggleClass('expanded');
                cardBody.toggleClass('show');
                cardActions.toggleClass('show');
            });
            
            $('#customerSearch').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.customer-item').each(function() {
                    const customerName = $(this).find('.customer-name').text().toLowerCase();
                    const customerId = $(this).find('.fa-barcode').parent().find('.value').text().toLowerCase();
                    const mobile = $(this).find('.fa-phone').parent().find('.value').text().toLowerCase();
                    const email = $(this).find('.fa-envelope').parent().find('.value').text().toLowerCase();
                    
                    if (customerName.includes(searchTerm) || customerId.includes(searchTerm) || 
                        mobile.includes(searchTerm) || email.includes(searchTerm)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
        });

        function openCustomerModal() {
            clearCustomerForm();
            generateCustomerID();
            $('#customerModal').modal('show');
        }

        function clearCustomerForm() {
            document.getElementById('customerForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('customerId').value = '';
            document.getElementById('customerModalLabel').innerHTML = '<i class="fas fa-user-plus mr-2"></i>Add New Customer';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Save Customer';
        }

        async function generateCustomerID() {
            try {
                const response = await fetch('api/get-next-customer-id.php');
                const data = await response.json();
                if (data.success) {
                    document.getElementById('customerID').value = data.customerID;
                } else {
                    console.error('Error generating Customer ID:', data.error);
                    await MsgBox.alert('Error generating Customer ID. Please try again.', 'Error');
                }
            } catch (error) {
                console.error('Error:', error);
                await MsgBox.alert('Error generating Customer ID. Please try again.', 'Error');
            }
        }

        async function editCustomer(customerId) {
            try {
                const response = await fetch('api/get-customer.php?id=' + customerId);
                const data = await response.json();
                if (data.success) {
                    const customer = data.customer;
                    document.getElementById('formAction').value = 'update';
                    document.getElementById('customerId').value = customer.ID;
                    document.getElementById('customerID').value = customer.CustomerID;
                    document.getElementById('customerID').removeAttribute('readonly');
                    document.getElementById('customerName').value = customer.CustomerName;
                    document.getElementById('customerType').value = customer.CustomerType || 'Individual';
                    document.getElementById('contactPerson').value = customer.ContactPerson || '';
                    document.getElementById('mobile').value = customer.Mobile || '';
                    document.getElementById('email').value = customer.Email || '';
                    document.getElementById('address').value = customer.Address || '';
                    document.getElementById('city').value = customer.City || '';
                    document.getElementById('state').value = customer.State || '';
                    document.getElementById('pinCode').value = customer.PinCode || '';
                    document.getElementById('gstNumber').value = customer.GSTNumber || '';
                    document.getElementById('panNumber').value = customer.PANNumber || '';
                    document.getElementById('creditLimit').value = customer.CreditLimit || '0';
                    document.getElementById('creditDays').value = customer.CreditDays || '0';
                    document.getElementById('status').value = customer.Status || 'Active';
                    
                    document.getElementById('customerModalLabel').innerHTML = '<i class="fas fa-user-edit mr-2"></i>Edit Customer';
                    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Update Customer';
                    
                    $('#customerModal').modal('show');
                } else {
                    await MsgBox.alert('Error fetching customer data: ' + data.message);
                }
            } catch (error) {
                console.error('Error:', error);
                await MsgBox.alert('Error fetching customer data');
            }
        }

        async function deleteCustomer(customerId, customerName) {
            const result = await MsgBox.confirm(`Are you sure you want to delete customer "${customerName}"?`);
            if (result) {
                window.location.href = 'customer-management.php?delete=' + customerId;
            }
        }

        function filterCustomers(type) {
            $('.btn-group .btn').removeClass('active');
            event.target.classList.add('active');
            
            $('.customer-item').each(function() {
                if (type === 'all') {
                    $(this).show();
                } else {
                    const itemType = $(this).data('type');
                    if (itemType === type) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                }
            });
        }

        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);
    </script>
</body>
</html>
