<?php
// admin/customers.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Sync customers from orders
if (isset($_GET['sync'])) {
    $stmt = $pdo->query("SELECT DISTINCT name, phone, email, address, city 
                         FROM orders WHERE name IS NOT NULL AND name != ''");
    $order_customers = $stmt->fetchAll();
    
    foreach ($order_customers as $oc) {
        // Check if customer exists
        $stmt = $pdo->prepare("SELECT id FROM customers WHERE phone = ?");
        $stmt->execute([$oc['phone']]);
        if (!$stmt->fetch()) {
            $customer_code = 'CUS-' . date('Ymd') . '-' . rand(1000, 9999);
            $stmt = $pdo->prepare("INSERT INTO customers 
                (customer_code, name, email, phone, address, city) 
                VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$customer_code, $oc['name'], $oc['email'], $oc['phone'], $oc['address'], $oc['city']]);
        }
    }
    $_SESSION['success_msg'] = 'Customers synced successfully!';
    header('Location: customers.php');
    exit;
}

// Update customer stats (orders count and total spent)
$stmt = $pdo->query("UPDATE customers c 
                     SET total_orders = (SELECT COUNT(*) FROM orders WHERE customer_id = c.id),
                         total_spent = (SELECT COALESCE(SUM(total), 0) FROM orders WHERE customer_id = c.id)
                     WHERE c.id IN (SELECT DISTINCT customer_id FROM orders WHERE customer_id IS NOT NULL)");
$stmt->execute();

// Get customers with order counts
$stmt = $pdo->prepare("SELECT c.*, 
                       (SELECT COUNT(*) FROM orders WHERE customer_id = c.id) as order_count,
                       (SELECT COALESCE(SUM(total), 0) FROM orders WHERE customer_id = c.id) as total_spent,
                       (SELECT MAX(created_at) FROM orders WHERE customer_id = c.id) as last_order
                       FROM customers c 
                       ORDER BY c.created_at DESC");
$stmt->execute();
$customers = $stmt->fetchAll();

// Also get customers from orders that are not in customers table
$stmt = $pdo->query("SELECT DISTINCT o.name, o.phone, o.email, o.address, o.city,
                     COUNT(o.id) as order_count,
                     SUM(o.total) as total_spent,
                     MAX(o.created_at) as last_order
                     FROM orders o
                     LEFT JOIN customers c ON o.customer_id = c.id
                     WHERE c.id IS NULL
                     GROUP BY o.name, o.phone, o.email, o.address, o.city
                     ORDER BY order_count DESC");
$order_only_customers = $stmt->fetchAll();

// Get stats
$total_customers = count($customers) + count($order_only_customers);
$stmt = $pdo->query("SELECT COUNT(*) as total FROM orders WHERE customer_id IS NOT NULL");
$total_orders = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COALESCE(SUM(total), 0) as total FROM orders");
$total_spent_all = $stmt->fetch()['total'];

$success_msg = $_SESSION['success_msg'] ?? '';
unset($_SESSION['success_msg']);

include 'header.php';
?>

<style>
.customer-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.customer-card .card-title {
    font-weight: 600;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f5f9;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.active {
    background: #86efac;
    color: #166534;
}

.status-badge.inactive {
    background: #fca5a5;
    color: #991b1b;
}

.customer-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.stat-box .stat-number {
    font-size: 28px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
}

.stat-box .stat-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.table td {
    vertical-align: middle;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-users me-2"></i> Customers</h2>
        <div>
            <a href="?sync=1" class="btn btn-info" onclick="return confirm('Sync customers from orders?')">
                <i class="fa-solid fa-sync"></i> Sync
            </a>
            <a href="/admin/add-customer.php" class="btn btn-primary">
                <i class="fa-solid fa-plus"></i> Add Customer
            </a>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="customer-stats">
        <div class="stat-box">
            <div class="stat-icon text-primary"><i class="fa-solid fa-users"></i></div>
            <div class="stat-number text-primary"><?php echo $total_customers; ?></div>
            <div class="stat-label">Total Customers</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-info"><i class="fa-solid fa-shopping-cart"></i></div>
            <div class="stat-number text-info"><?php echo $total_orders; ?></div>
            <div class="stat-label">Total Orders</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-success"><i class="fa-solid fa-dollar-sign"></i></div>
            <div class="stat-number text-success"><?php echo number_format($total_spent_all); ?> TK</div>
            <div class="stat-label">Total Spent</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-warning"><i class="fa-solid fa-user-check"></i></div>
            <div class="stat-number text-warning">
                <?php 
                $active = array_filter($customers, function($c) { return $c['status'] == 1; });
                echo count($active);
                ?>
            </div>
            <div class="stat-label">Active Customers</div>
        </div>
    </div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo $success_msg; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Customers Table -->
    <div class="customer-card">
        <h5 class="card-title">All Customers (<?php echo $total_customers; ?>)</h5>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Customer Name</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Orders</th>
                        <th>Total Spent</th>
                        <th>Last Order</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="customersTableBody">
                    <?php if (empty($customers) && empty($order_only_customers)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fa-regular fa-users fa-2x text-muted d-block mb-2"></i>
                            No customers found. Click "Sync" to import from orders.
                        </td>
                    </tr>
                    <?php else: ?>
                    
                    <!-- Customers from customers table -->
                    <?php foreach ($customers as $customer): ?>
                    <tr id="customerRow_<?php echo $customer['id']; ?>">
                        <td><code><?php echo $customer['customer_code']; ?></code></td>
                        <td>
                            <strong><?php echo htmlspecialchars($customer['name']); ?></strong>
                            <?php if ($customer['address']): ?>
                            <br><small class="text-muted"><?php echo substr(htmlspecialchars($customer['address']), 0, 30) . (strlen($customer['address']) > 30 ? '...' : ''); ?></small>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($customer['phone']); ?></td>
                        <td><?php echo htmlspecialchars($customer['email'] ?? '-'); ?></td>
                        <td>
                            <span class="badge bg-primary"><?php echo $customer['order_count']; ?></span>
                        </td>
                        <td>
                            <span class="fw-bold text-success"><?php echo number_format($customer['total_spent']); ?> TK</span>
                        </td>
                        <td>
                            <?php if ($customer['last_order']): ?>
                            <?php echo date('d M Y', strtotime($customer['last_order'])); ?>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="status-badge <?php echo $customer['status'] ? 'active' : 'inactive'; ?>">
                                <?php echo $customer['status'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-btns">
                                <a href="view-customer.php?id=<?php echo $customer['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                               
                                <button onclick="deleteCustomer(<?php echo $customer['id']; ?>)" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <!-- Customers only from orders -->
                    <?php foreach ($order_only_customers as $oc): ?>
                    <tr class="table-info">
                        <td><code class="text-muted">Not Synced</code></td>
                        <td>
                            <strong><?php echo htmlspecialchars($oc['name']); ?></strong>
                            <?php if ($oc['address']): ?>
                            <br><small class="text-muted"><?php echo substr(htmlspecialchars($oc['address']), 0, 30) . (strlen($oc['address']) > 30 ? '...' : ''); ?></small>
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($oc['phone']); ?></td>
                        <td><?php echo htmlspecialchars($oc['email'] ?? '-'); ?></td>
                        <td>
                            <span class="badge bg-primary"><?php echo $oc['order_count']; ?></span>
                        </td>
                        <td>
                            <span class="fw-bold text-success"><?php echo number_format($oc['total_spent']); ?> TK</span>
                        </td>
                        <td>
                            <?php if ($oc['last_order']): ?>
                            <?php echo date('d M Y', strtotime($oc['last_order'])); ?>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="status-badge active">From Orders</span>
                        </td>
                        <td>
                            <button onclick="syncCustomer('<?php echo addslashes($oc['name']); ?>', '<?php echo addslashes($oc['phone']); ?>')" class="btn btn-sm btn-success">
                                <i class="fa-solid fa-sync"></i> Sync
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// ========================================
// DELETE CUSTOMER
// ========================================
function deleteCustomer(id) {
    if (!confirm('Are you sure you want to delete this customer?')) return;
    
    var formData = new FormData();
    formData.append('delete_id', id);
    
    fetch('delete-customer.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('customerRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    showToast('Customer deleted successfully!', 'success');
                }, 500);
            }
        } else {
            showToast(data.message || 'Failed to delete', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Something went wrong', 'error');
    });
}

// ========================================
// SYNC CUSTOMER FROM ORDERS
// ========================================
function syncCustomer(name, phone) {
    if (!confirm('Sync this customer from orders?')) return;
    
    var formData = new FormData();
    formData.append('name', name);
    formData.append('phone', phone);
    
    fetch('sync-customer.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Customer synced successfully!', 'success');
            setTimeout(function() {
                location.reload();
            }, 1000);
        } else {
            showToast(data.message || 'Failed to sync', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Something went wrong', 'error');
    });
}

// ========================================
// SHOW TOAST
// ========================================
function showToast(message, type) {
    var colors = {
        success: '#22c55e',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };
    
    var existingToast = document.querySelector('.toast-message');
    if (existingToast) existingToast.remove();
    
    var toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 24px;
        background: ${colors[type] || colors.info};
        color: #fff;
        border-radius: 8px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
        max-width: 400px;
        font-size: 14px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(function() {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity 0.3s ease';
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

// ========================================
// AUTO HIDE ALERTS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
    
    // Add CSS for toast animation
    var style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0%); opacity: 1; }
        }
    `;
    document.head.appendChild(style);
});
</script>

<?php include 'footer.php'; ?>