<?php
// manage-customers.php
session_start();
require_once 'includes/db.php';

// Handle customer deletion
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    
    // Check if customer has any bills
    $check_sql = "SELECT COUNT(*) as bill_count FROM bills WHERE customer_id = ?";
    $check_stmt = mysqli_prepare($conn, $check_sql);
    mysqli_stmt_bind_param($check_stmt, "i", $delete_id);
    mysqli_stmt_execute($check_stmt);
    $check_result = mysqli_stmt_get_result($check_stmt);
    $bill_count = mysqli_fetch_assoc($check_result)['bill_count'];
    
    if ($bill_count > 0) {
        $_SESSION['message'] = '<div class="alert alert-danger">Cannot delete customer. They have ' . $bill_count . ' bill(s) in the system.</div>';
    } else {
        $delete_sql = "DELETE FROM customers WHERE id = ?";
        $delete_stmt = mysqli_prepare($conn, $delete_sql);
        mysqli_stmt_bind_param($delete_stmt, "i", $delete_id);
        
        if (mysqli_stmt_execute($delete_stmt)) {
            $_SESSION['message'] = '<div class="alert alert-success">Customer deleted successfully!</div>';
        } else {
            $_SESSION['message'] = '<div class="alert alert-danger">Error deleting customer: ' . mysqli_error($conn) . '</div>';
        }
    }
    
    header('Location: manage-customers.php');
    exit();
}

// Get filter parameters
$search_query = isset($_GET['search']) ? trim($_GET['search']) : '';

// Build WHERE conditions
$where_conditions = [];
$params = [];
$types = '';

if (!empty($search_query)) {
    $where_conditions[] = "(c.name LIKE ? OR c.phone LIKE ? OR c.address LIKE ?)";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
    $params[] = "%$search_query%";
    $types .= 'sss';
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Get customers with statistics
$sql = "SELECT c.*, 
               COUNT(b.id) as total_orders,
               COALESCE(SUM(b.total_amount), 0) as total_spent,
               MAX(b.created_at) as last_order_date
        FROM customers c 
        LEFT JOIN bills b ON c.id = b.customer_id 
        $where_clause 
        GROUP BY c.id 
        ORDER BY c.name";

$stmt = mysqli_prepare($conn, $sql);
if (!empty($params)) {
    mysqli_stmt_bind_param($stmt, $types, ...$params);
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

// Get customer statistics
$stats_sql = "SELECT 
                COUNT(*) as total_customers,
                COUNT(DISTINCT b.customer_id) as customers_with_orders,
                SUM(b.total_amount) as total_revenue,
                AVG(b.total_amount) as avg_order_value
              FROM customers c 
              LEFT JOIN bills b ON c.id = b.customer_id";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Display message if exists
$message = '';
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}
?>
<!doctype html>
<html lang="en">
<?php include('includes/head.php')?>
<body data-sidebar="dark">
<?php include('includes/pre-loader.php')?>
<div id="layout-wrapper">
    <?php include('includes/topbar.php')?>
    <div class="vertical-menu">
        <div data-simplebar class="h-100">
            <?php include('includes/sidebar.php')?>
        </div>
    </div>

    <div class="main-content">
        <div class="page-content">
            <div class="container-fluid">

                <!-- Page Header -->
                <div class="row align-items-center mb-3">
                    <div class="col-12 d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <h4 class="mb-0">Customers / Manage Customers</h4>
                        <div class="d-flex flex-wrap gap-2">
                            <a href="new-bill.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-plus me-1"></i>New Bill
                            </a>
                            <a href="manage-orders.php" class="btn btn-success btn-sm">Manage Orders</a>
                        </div>
                    </div>
                </div>

                <!-- Stats Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center p-3">
                                <h4 class="mb-0"><?php echo $stats['total_customers']; ?></h4>
                                <small>Total Customers</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body text-center p-3">
                                <h4 class="mb-0"><?php echo $stats['customers_with_orders']; ?></h4>
                                <small>Active Customers</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body text-center p-3">
                                <h4 class="mb-0">₹<?php echo number_format($stats['total_revenue'] ?? 0, 2); ?></h4>
                                <small>Total Revenue</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body text-center p-3">
                                <h4 class="mb-0">₹<?php echo number_format($stats['avg_order_value'] ?? 0, 2); ?></h4>
                                <small>Avg Order Value</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-8">
                                <label class="form-label">Search Customers</label>
                                <input type="text" name="search" class="form-control" 
                                       value="<?php echo htmlspecialchars($search_query); ?>" 
                                       placeholder="Search by name, phone, or address...">
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">Search</button>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <a href="manage-customers.php" class="btn btn-secondary w-100">Clear</a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Customers Table -->
                <div class="card">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">Customers List</h5>
                        <div>
                            <span class="text-muted">
                                Showing <?php echo mysqli_num_rows($result); ?> customer(s)
                            </span>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php echo $message; ?>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>#</th>
                                        <th>Customer</th>
                                        <th>Contact</th>
                                        <th>Address</th>
                                        <th>Orders</th>
                                        <th>Total Spent</th>
                                        <th>Last Order</th>
                                        <th>Registered</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($result) > 0): ?>
                                        <?php $counter = 1; ?>
                                        <?php while ($customer = mysqli_fetch_assoc($result)): ?>
                                            <tr>
                                                <td><?php echo $counter++; ?></td>
                                                <td>
                                                    <div class="fw-semibold"><?php echo htmlspecialchars($customer['name']); ?></div>
                                                    <?php if ($customer['total_orders'] > 0): ?>
                                                        <small class="text-success">
                                                            <i class="fas fa-star me-1"></i>Regular Customer
                                                        </small>
                                                    <?php else: ?>
                                                        <small class="text-muted">New Customer</small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div class="fw-semibold"><?php echo htmlspecialchars($customer['phone']); ?></div>
                                                    <?php if (!empty($customer['email'])): ?>
                                                        <small class="text-muted"><?php echo htmlspecialchars($customer['email']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if (!empty($customer['address'])): ?>
                                                        <small><?php echo htmlspecialchars($customer['address']); ?></small>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($customer['total_orders'] > 0): ?>
                                                        <span class="badge bg-primary"><?php echo $customer['total_orders']; ?> orders</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-secondary">No orders</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($customer['total_spent'] > 0): ?>
                                                        <div class="fw-semibold text-success">₹<?php echo number_format($customer['total_spent'], 2); ?></div>
                                                        <small class="text-muted">
                                                            ₹<?php echo $customer['total_orders'] > 0 ? number_format($customer['total_spent'] / $customer['total_orders'], 2) : '0.00'; ?> avg
                                                        </small>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if (!empty($customer['last_order_date'])): ?>
                                                        <small><?php echo date('M j, Y', strtotime($customer['last_order_date'])); ?></small>
                                                        <br>
                                                        <small class="text-muted">
                                                            <?php echo date('g:i A', strtotime($customer['last_order_date'])); ?>
                                                        </small>
                                                    <?php else: ?>
                                                        <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <small><?php echo date('M j, Y', strtotime($customer['created_at'])); ?></small>
                                                    <br>
                                                    <small class="text-muted">
                                                        <?php echo date('g:i A', strtotime($customer['created_at'])); ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="view-customer.php?id=<?php echo $customer['id']; ?>" class="btn btn-info" title="View Customer">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="new-bill.php?customer_phone=<?php echo urlencode($customer['phone']); ?>" class="btn btn-success" title="New Bill">
                                                            <i class="fas fa-receipt"></i>
                                                        </a>
                                                        <a href="edit-customer.php?id=<?php echo $customer['id']; ?>" class="btn btn-warning" title="Edit Customer">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <button type="button" class="btn btn-danger" 
                                                                onclick="confirmDelete(<?php echo $customer['id']; ?>, '<?php echo htmlspecialchars($customer['name']); ?>', <?php echo $customer['total_orders']; ?>)"
                                                                title="Delete Customer">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="9" class="text-center py-4">
                                                <div class="text-muted">
                                                    <i class="fas fa-users fa-3x mb-3"></i>
                                                    <h5>No customers found</h5>
                                                    <p>
                                                        <?php echo !empty($search_query) 
                                                            ? 'No customers match your search criteria.' 
                                                            : 'No customers found in the system.'; ?>
                                                    </p>
                                                    <?php if (empty($search_query)): ?>
                                                        <a href="new-bill.php" class="btn btn-primary">Create First Customer</a>
                                                    <?php else: ?>
                                                        <a href="manage-customers.php" class="btn btn-secondary">Clear Search</a>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <?php include('includes/footer.php')?>
    </div>
</div>

<?php include('includes/rightbar.php')?>
<?php include('includes/scripts.php')?>

<script>
function confirmDelete(customerId, customerName, orderCount) {
    if (orderCount > 0) {
        alert(`Cannot delete customer "${customerName}". They have ${orderCount} order(s) in the system.`);
        return;
    }
    
    if (confirm(`Are you sure you want to delete customer "${customerName}"? This action cannot be undone.`)) {
        window.location.href = `manage-customers.php?delete_id=${customerId}`;
    }
}

// Auto-close alerts after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.remove();
        }, 5000);
    });
});

// Quick search functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('input[name="search"]');
    if (searchInput) {
        searchInput.focus();
        
        // Clear search when Escape key is pressed
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                this.value = '';
                this.form.submit();
            }
        });
    }
});
</script>
</body>
</html>