<?php include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user role and permissions
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;

// Check if user has permission to manage users
if (!in_array($user_role, ['Administrator', 'Support Agent', 'Sales Manager'])) {
    $_SESSION['error'] = "You don't have permission to access this page.";
    header('Location: dashboard.php');
    exit();
}

// Include database connection
require_once 'layouts/dbconn.php';

// Test database connection
if (!isset($conn) || $conn->connect_error) {
    die("Database connection failed: " . ($conn->connect_error ?? 'Connection variable not set'));
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'verify_customer':
            $customer_id = (int)$_POST['customer_id'];
            $stmt = $conn->prepare("UPDATE users SET verified = 1 WHERE user_id = ? AND role_id = (SELECT role_id FROM user_roles WHERE role_name = 'Customer')");
            $stmt->bind_param("i", $customer_id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Customer verified successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to verify customer']);
            }
            $stmt->close();
            exit();
            
        case 'block_customer':
            $customer_id = (int)$_POST['customer_id'];
            $stmt = $conn->prepare("UPDATE users SET failed_attempts = 10 WHERE user_id = ? AND role_id = (SELECT role_id FROM user_roles WHERE role_name = 'Customer')");
            $stmt->bind_param("i", $customer_id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Customer blocked successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to block customer']);
            }
            $stmt->close();
            exit();
            
        case 'unblock_customer':
            $customer_id = (int)$_POST['customer_id'];
            $stmt = $conn->prepare("UPDATE users SET failed_attempts = 0 WHERE user_id = ? AND role_id = (SELECT role_id FROM user_roles WHERE role_name = 'Customer')");
            $stmt->bind_param("i", $customer_id);
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Customer unblocked successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to unblock customer']);
            }
            $stmt->close();
            exit();
    }
}

// Get filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$country_filter = isset($_GET['country']) ? $_GET['country'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Pagination
$records_per_page = 25;
$current_page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($current_page - 1) * $records_per_page;

// Build WHERE conditions
$where_conditions = ["u.role_id = (SELECT role_id FROM user_roles WHERE role_name = 'Customer')"];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(u.full_name LIKE ? OR u.email LIKE ? OR u.username LIKE ? OR u.company_name LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $param_types .= 'ssss';
}

if (!empty($status_filter)) {
    if ($status_filter === 'verified') {
        $where_conditions[] = "u.verified = 1";
    } elseif ($status_filter === 'unverified') {
        $where_conditions[] = "u.verified = 0";
    } elseif ($status_filter === 'blocked') {
        $where_conditions[] = "u.failed_attempts >= 5";
    }
}

if (!empty($country_filter)) {
    $where_conditions[] = "u.country = ?";
    $params[] = $country_filter;
    $param_types .= 's';
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(u.created_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(u.created_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = implode(' AND ', $where_conditions);

// Get total count for pagination
$count_query = "SELECT COUNT(*) as total FROM users u WHERE $where_clause";
$stmt = $conn->prepare($count_query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['total'];
$stmt->close();

// Calculate total pages
$total_pages = ceil($total_records / $records_per_page);

// SIMPLIFIED VERSION - Use this if the complex query fails
$customers_query = "
    SELECT 
        u.user_id,
        u.username,
        u.email,
        u.full_name,
        u.company_name,
        u.country,
        u.phone,
        u.verified,
        u.failed_attempts,
        u.last_login,
        u.created_at,
        ur.role_name,
        0 as total_licenses,
        0 as active_licenses,
        0 as total_orders,
        0 as total_spent,
        0 as wallet_balance,
        0 as open_tickets
    FROM users u
    LEFT JOIN user_roles ur ON u.role_id = ur.role_id
    WHERE $where_clause
    ORDER BY u.created_at DESC
    LIMIT ? OFFSET ?
";

// Add pagination parameters
$params[] = $records_per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($customers_query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$customers_result = $stmt->get_result();
$stmt->close();

// Get summary stats
$stats_query = "
    SELECT 
        COUNT(*) as total_customers,
        SUM(CASE WHEN verified = 1 THEN 1 ELSE 0 END) as verified_customers,
        SUM(CASE WHEN failed_attempts >= 5 THEN 1 ELSE 0 END) as blocked_customers,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_today
    FROM users 
    WHERE role_id = (SELECT role_id FROM user_roles WHERE role_name = 'Customer')
";

$stats_result = $conn->query($stats_query);
if ($stats_result) {
    $stats = $stats_result->fetch_assoc();
} else {
    $stats = [
        'total_customers' => 0, 
        'verified_customers' => 0, 
        'blocked_customers' => 0, 
        'new_today' => 0
    ];
}

// Get countries for filter dropdown
$countries_query = "SELECT DISTINCT country FROM users WHERE country IS NOT NULL AND country != '' ORDER BY country";
$countries_result = $conn->query($countries_query);

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php $title = "Manage Customers";
    include 'partials/title-meta.php'; ?>

    <!-- SweetAlert2 -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">

    <?php include 'partials/head-css.php'; ?>
</head>

<?php include 'partials/body.php'; ?>

<!-- Begin page -->
<div id="wrapper">

    <?php $pagetitle = "Manage Customers";
    include 'partials/menu.php'; ?>

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="content-page">
        <div class="content">

            <!-- Start Content-->
            <div class="container-fluid">
                
                <!-- start page title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="admin-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item"><a href="#">Users & Customers</a></li>
                                    <li class="breadcrumb-item active">Customers</li>
                                </ol>
                            </div>
                            <h4 class="page-title">Manage Customers</h4>
                        </div>
                    </div>
                </div>
                <!-- end page title -->

                <!-- Summary Stats -->
                <div class="row">
                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-account-multiple widget-icon"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Total Customers">Total Customers</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['total_customers']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-success me-2"><i class="mdi mdi-arrow-up-bold"></i> <?php echo $stats['new_today']; ?></span>
                                    <span class="text-nowrap">New today</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-shield-check widget-icon bg-success-lighten text-success"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Verified Customers">Verified</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['verified_customers']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-success me-2">
                                        <?php echo $stats['total_customers'] > 0 ? round(($stats['verified_customers'] / $stats['total_customers']) * 100, 1) : 0; ?>%
                                    </span>
                                    <span class="text-nowrap">Verification rate</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-account-off widget-icon bg-danger-lighten text-danger"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Blocked Customers">Blocked</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['blocked_customers']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-danger me-2">
                                        <?php echo $stats['total_customers'] > 0 ? round(($stats['blocked_customers'] / $stats['total_customers']) * 100, 1) : 0; ?>%
                                    </span>
                                    <span class="text-nowrap">Block rate</span>
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-3">
                        <div class="card widget-flat">
                            <div class="card-body">
                                <div class="float-end">
                                    <i class="mdi mdi-currency-usd widget-icon bg-info-lighten text-info"></i>
                                </div>
                                <h5 class="text-muted fw-normal mt-0" title="Active Customers">Active</h5>
                                <h3 class="mt-3 mb-3"><?php echo number_format($stats['total_customers'] - $stats['blocked_customers']); ?></h3>
                                <p class="mb-0 text-muted">
                                    <span class="text-info me-2">
                                        <?php echo $stats['total_customers'] > 0 ? round((($stats['total_customers'] - $stats['blocked_customers']) / $stats['total_customers']) * 100, 1) : 0; ?>%
                                    </span>
                                    <span class="text-nowrap">Active rate</span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters and Search -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <form method="GET" id="filterForm">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="mb-3">
                                                <label for="search" class="form-label">Search</label>
                                                <input type="text" class="form-control" id="search" name="search" 
                                                       value="<?php echo htmlspecialchars($search); ?>" 
                                                       placeholder="Name, email, username, company...">
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="mb-3">
                                                <label for="status" class="form-label">Status</label>
                                                <select class="form-select" id="status" name="status">
                                                    <option value="">All Status</option>
                                                    <option value="verified" <?php echo $status_filter === 'verified' ? 'selected' : ''; ?>>Verified</option>
                                                    <option value="unverified" <?php echo $status_filter === 'unverified' ? 'selected' : ''; ?>>Unverified</option>
                                                    <option value="blocked" <?php echo $status_filter === 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="mb-3">
                                                <label for="country" class="form-label">Country</label>
                                                <select class="form-select" id="country" name="country">
                                                    <option value="">All Countries</option>
                                                    <?php if ($countries_result && $countries_result->num_rows > 0): ?>
                                                        <?php while ($country = $countries_result->fetch_assoc()): ?>
                                                            <option value="<?php echo htmlspecialchars($country['country']); ?>" 
                                                                    <?php echo $country_filter === $country['country'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($country['country']); ?>
                                                            </option>
                                                        <?php endwhile; ?>
                                                    <?php endif; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="mb-3">
                                                <label for="date_from" class="form-label">From Date</label>
                                                <input type="date" class="form-control" id="date_from" name="date_from" 
                                                       value="<?php echo htmlspecialchars($date_from); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="mb-3">
                                                <label for="date_to" class="form-label">To Date</label>
                                                <input type="date" class="form-control" id="date_to" name="date_to" 
                                                       value="<?php echo htmlspecialchars($date_to); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-1">
                                            <div class="mb-3">
                                                <label class="form-label">&nbsp;</label>
                                                <div class="d-grid">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="mdi mdi-magnify"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                                
                                <?php if (!empty($search) || !empty($status_filter) || !empty($country_filter) || !empty($date_from) || !empty($date_to)): ?>
                                <div class="row">
                                    <div class="col-12">
                                        <div class="alert alert-info">
                                            <i class="mdi mdi-information"></i>
                                            Showing filtered results. 
                                            <a href="manage-customers.php" class="alert-link">Clear all filters</a>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Customers Table -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover table-nowrap">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Customer</th>
                                                <th>Contact</th>
                                                <th>Status</th>
                                                <th>Licenses</th>
                                                <th>Orders</th>
                                                <th>Wallet</th>
                                                <th>Tickets</th>
                                                <th>Joined</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($customers_result && $customers_result->num_rows > 0): ?>
                                                <?php while ($customer = $customers_result->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="avatar-sm bg-primary rounded-circle d-flex align-items-center justify-content-center me-2">
                                                                    <span class="text-white fw-bold">
                                                                        <?php echo strtoupper(substr($customer['full_name'], 0, 2)); ?>
                                                                    </span>
                                                                </div>
                                                                <div>
                                                                    <h6 class="mb-1 fw-semibold"><?php echo htmlspecialchars($customer['full_name']); ?></h6>
                                                                    <p class="mb-0 text-muted small">@<?php echo htmlspecialchars($customer['username']); ?></p>
                                                                    <?php if (!empty($customer['company_name'])): ?>
                                                                        <p class="mb-0 text-muted small"><?php echo htmlspecialchars($customer['company_name']); ?></p>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <div>
                                                                <i class="mdi mdi-email-outline me-1"></i>
                                                                <span class="small"><?php echo htmlspecialchars($customer['email']); ?></span>
                                                            </div>
                                                            <?php if (!empty($customer['phone'])): ?>
                                                                <div class="mt-1">
                                                                    <i class="mdi mdi-phone me-1"></i>
                                                                    <span class="small"><?php echo htmlspecialchars($customer['phone']); ?></span>
                                                                </div>
                                                            <?php endif; ?>
                                                            <?php if (!empty($customer['country'])): ?>
                                                                <div class="mt-1">
                                                                    <i class="mdi mdi-map-marker me-1"></i>
                                                                    <span class="small"><?php echo htmlspecialchars($customer['country']); ?></span>
                                                                </div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($customer['failed_attempts'] >= 5): ?>
                                                                <span class="badge bg-danger">Blocked</span>
                                                            <?php elseif ($customer['verified']): ?>
                                                                <span class="badge bg-success">Verified</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-warning">Unverified</span>
                                                            <?php endif; ?>
                                                            
                                                            <?php if ($customer['last_login']): ?>
                                                                <div class="small text-muted mt-1">
                                                                    Last: <?php echo date('M j, Y', strtotime($customer['last_login'])); ?>
                                                                </div>
                                                            <?php else: ?>
                                                                <div class="small text-muted mt-1">Never logged in</div>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <span class="me-2"><?php echo $customer['active_licenses']; ?>/<?php echo $customer['total_licenses']; ?></span>
                                                                <?php if ($customer['active_licenses'] > 0): ?>
                                                                    <span class="badge bg-success-lighten text-success">Active</span>
                                                                <?php endif; ?>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <div><?php echo $customer['total_orders']; ?> orders</div>
                                                            <div class="small text-muted">$<?php echo number_format($customer['total_spent'], 2); ?> spent</div>
                                                        </td>
                                                        <td>
                                                            <span class="fw-semibold">$<?php echo number_format($customer['wallet_balance'], 2); ?></span>
                                                        </td>
                                                        <td>
                                                            <?php if ($customer['open_tickets'] > 0): ?>
                                                                <span class="badge bg-warning"><?php echo $customer['open_tickets']; ?></span>
                                                            <?php else: ?>
                                                                <span class="text-muted">0</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="small"><?php echo date('M j, Y', strtotime($customer['created_at'])); ?></span>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <button type="button" class="btn btn-sm btn-light dropdown-toggle" 
                                                                        data-bs-toggle="dropdown" aria-expanded="false">
                                                                    <i class="mdi mdi-dots-horizontal"></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li><a class="dropdown-item" href="customer-detail.php?id=<?php echo $customer['user_id']; ?>">
                                                                        <i class="mdi mdi-eye me-2"></i>View Details</a></li>
                                                                    <li><a class="dropdown-item" href="customer-licenses.php?id=<?php echo $customer['user_id']; ?>">
                                                                        <i class="mdi mdi-key me-2"></i>Licenses</a></li>
                                                                    <li><a class="dropdown-item" href="customer-orders.php?id=<?php echo $customer['user_id']; ?>">
                                                                        <i class="mdi mdi-cart me-2"></i>Orders</a></li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    
                                                                    <?php if (!$customer['verified']): ?>
                                                                        <li><a class="dropdown-item text-success customer-action" href="#" 
                                                                               data-action="verify_customer" data-id="<?php echo $customer['user_id']; ?>">
                                                                            <i class="mdi mdi-shield-check me-2"></i>Verify Account</a></li>
                                                                    <?php endif; ?>
                                                                    
                                                                    <?php if ($customer['failed_attempts'] >= 5): ?>
                                                                        <li><a class="dropdown-item text-info customer-action" href="#" 
                                                                               data-action="unblock_customer" data-id="<?php echo $customer['user_id']; ?>">
                                                                            <i class="mdi mdi-shield-check me-2"></i>Unblock Account</a></li>
                                                                    <?php else: ?>
                                                                        <li><a class="dropdown-item text-danger customer-action" href="#" 
                                                                               data-action="block_customer" data-id="<?php echo $customer['user_id']; ?>">
                                                                            <i class="mdi mdi-shield-off me-2"></i>Block Account</a></li>
                                                                    <?php endif; ?>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="9" class="text-center py-5">
                                                        <div class="text-muted">
                                                            <i class="mdi mdi-account-search display-4"></i>
                                                           <p class="mt-3">No customers found matching your criteria.</p>
                                                           <a href="manage-customers.php" class="btn btn-primary btn-sm">Reset Filters</a>
                                                       </div>
                                                   </td>
                                               </tr>
                                           <?php endif; ?>
                                       </tbody>
                                   </table>
                               </div>

                               <!-- Pagination -->
                               <?php if ($total_pages > 1): ?>
                                   <div class="row">
                                       <div class="col-12">
                                           <div class="d-flex justify-content-between align-items-center mt-3">
                                               <div class="text-muted">
                                                   Showing <?php echo (($current_page - 1) * $records_per_page + 1); ?> to 
                                                   <?php echo min($current_page * $records_per_page, $total_records); ?> of 
                                                   <?php echo $total_records; ?> customers
                                               </div>
                                               <nav aria-label="Page navigation">
                                                   <ul class="pagination pagination-sm mb-0">
                                                       <?php if ($current_page > 1): ?>
                                                           <li class="page-item">
                                                               <a class="page-link" href="?page=<?php echo ($current_page - 1); ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                                   <i class="mdi mdi-chevron-left"></i>
                                                               </a>
                                                           </li>
                                                       <?php endif; ?>

                                                       <?php
                                                       $start_page = max(1, $current_page - 2);
                                                       $end_page = min($total_pages, $current_page + 2);
                                                       
                                                       for ($i = $start_page; $i <= $end_page; $i++):
                                                       ?>
                                                           <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                                                               <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                                   <?php echo $i; ?>
                                                               </a>
                                                           </li>
                                                       <?php endfor; ?>

                                                       <?php if ($current_page < $total_pages): ?>
                                                           <li class="page-item">
                                                               <a class="page-link" href="?page=<?php echo ($current_page + 1); ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                                   <i class="mdi mdi-chevron-right"></i>
                                                               </a>
                                                           </li>
                                                       <?php endif; ?>
                                                   </ul>
                                               </nav>
                                           </div>
                                       </div>
                                   </div>
                               <?php endif; ?>
                           </div>
                       </div>
                   </div>
               </div>

           </div> <!-- container -->

       </div> <!-- content -->

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

   </div>

   <!-- ============================================================== -->
   <!-- End Page content -->
   <!-- ============================================================== -->

</div>
<!-- END wrapper -->

<?php include 'partials/right-sidebar.php'; ?>

<?php include 'partials/footer-scripts.php'; ?>

<!-- SweetAlert2 -->
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>

<!-- App js -->
<script src="assets/js/app.min.js"></script>

<script>
   $(document).ready(function() {
       // Handle customer actions
       $('.customer-action').on('click', function(e) {
           e.preventDefault();
           
           const action = $(this).data('action');
           const customerId = $(this).data('id');
           
           let title = '';
           let text = '';
           let confirmButtonText = '';
           let icon = 'warning';
           
           switch(action) {
               case 'verify_customer':
                   title = 'Verify Customer?';
                   text = 'This will mark the customer account as verified.';
                   confirmButtonText = 'Yes, Verify';
                   icon = 'question';
                   break;
               case 'block_customer':
                   title = 'Block Customer?';
                   text = 'This will block the customer from accessing their account.';
                   confirmButtonText = 'Yes, Block';
                   icon = 'warning';
                   break;
               case 'unblock_customer':
                   title = 'Unblock Customer?';
                   text = 'This will restore access to the customer account.';
                   confirmButtonText = 'Yes, Unblock';
                   icon = 'question';
                   break;
           }
           
           Swal.fire({
               title: title,
               text: text,
               icon: icon,
               showCancelButton: true,
               confirmButtonColor: '#3085d6',
               cancelButtonColor: '#6c757d',
               confirmButtonText: confirmButtonText,
               cancelButtonText: 'Cancel'
           }).then((result) => {
               if (result.isConfirmed) {
                   performCustomerAction(action, customerId);
               }
           });
       });
       
       function performCustomerAction(action, customerId) {
           $.ajax({
               url: 'manage-customers.php',
               type: 'POST',
               data: {
                   action: action,
                   customer_id: customerId
               },
               dataType: 'json',
               success: function(response) {
                   if (response.success) {
                       Swal.fire({
                           title: 'Success!',
                           text: response.message,
                           icon: 'success',
                           timer: 2000,
                           showConfirmButton: false
                       }).then(() => {
                           location.reload();
                       });
                   } else {
                       Swal.fire({
                           title: 'Error!',
                           text: response.message,
                           icon: 'error'
                       });
                   }
               },
               error: function() {
                   Swal.fire({
                       title: 'Error!',
                       text: 'An error occurred while processing the request.',
                       icon: 'error'
                   });
               }
           });
       }
       
       // Auto-submit form when filters change
       $('#status, #country').on('change', function() {
           $('#filterForm').submit();
       });
       
       // Real-time search with debounce
       let searchTimeout;
       $('#search').on('input', function() {
           clearTimeout(searchTimeout);
           searchTimeout = setTimeout(function() {
               $('#filterForm').submit();
           }, 500);
       });
   });
</script>

</body>
</html>