<?php
// shops.php
declare(strict_types=1);
session_start();

require_once '../config/db_connect.php';

// Start output buffering
ob_start();

require_once 'header.php';
require_once 'sidebar.php';


// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Authentication check - only admin can access
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') { 
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'><div class='alert alert-danger'>Access denied. Admin only.</div></div>";
    require_once '../includes/footer.php';
    exit; 
}

$user_id = (int)$_SESSION['user']['id'];

// Debug logging function
function log_action($action, $data = []) {
    $log = date('Y-m-d H:i:s') . " - $action: " . json_encode($data) . PHP_EOL;
    @file_put_contents('shops_debug.log', $log, FILE_APPEND);
}

/* ---- HANDLE FORM SUBMISSIONS ---- */
$message = '';
$message_type = '';

// Check if this is a redirect after success (to prevent loops)
$is_redirect = isset($_GET['redirect']) && $_GET['redirect'] == 'success';

// Add new shop
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_shop'])) {
    log_action('Add shop attempt', $_POST);
    
    try {
        $name = trim($_POST['name']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        $status = isset($_POST['is_active']) ? 1 : 0;
        
        // Validate
        if (empty($name)) {
            throw new Exception('Shop name is required');
        }
        
        $stmt = $pdo->prepare("INSERT INTO shops (name, phone, address, is_active, created_by, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$name, $phone, $address, $status, $user_id]);
        
        // Redirect to prevent form resubmission
        header("Location: shops.php?success=shop_added");
        exit;
        
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
        log_action('Add shop error', ['error' => $e->getMessage()]);
    }
}

// Update shop
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_shop'])) {
    log_action('Update shop attempt', $_POST);
    
    try {
        $shop_id = (int)$_POST['shop_id'];
        $name = trim($_POST['name']);
        $phone = trim($_POST['phone']);
        $address = trim($_POST['address']);
        $status = isset($_POST['is_active']) ? 1 : 0;
        
        log_action("Data received", ['id' => $shop_id, 'name' => $name, 'status' => $status]);
        
        if (empty($name)) {
            throw new Exception('Shop name is required');
        }
        
        // First, check if shop exists
        $stmt = $pdo->prepare("SELECT id FROM shops WHERE id = ?");
        $stmt->execute([$shop_id]);
        if (!$stmt->fetch()) {
            throw new Exception('Shop not found');
        }
        
        $stmt = $pdo->prepare("UPDATE shops SET name = ?, phone = ?, address = ?, is_active = ?, updated_at = NOW(), updated_by = ? WHERE id = ?");
        $result = $stmt->execute([$name, $phone, $address, $status, $user_id, $shop_id]);
        
        $affected_rows = $stmt->rowCount();
        log_action("Update executed", ['rows_affected' => $affected_rows]);
        
        // Redirect to prevent form resubmission
        header("Location: shops.php?success=shop_updated");
        exit;
        
    } catch (Exception $e) {
        log_action("Update error", ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Delete shop
if (isset($_GET['delete'])) {
    log_action('Delete shop attempt', ['id' => $_GET['delete']]);
    
    try {
        $shop_id = (int)$_GET['delete'];
        
        // Check if shop has any data
        $check_sql = "
            SELECT (
                SELECT COUNT(*) FROM products WHERE shop_id = ?
                UNION ALL


                SELECT COUNT(*) FROM users WHERE shop_id = ?
                UNION ALL
                SELECT COUNT(*) FROM sales WHERE shop_id = ?
            ) as counts
        ";
        
        $stmt = $pdo->prepare($check_sql);
        $stmt->execute([$shop_id, $shop_id, $shop_id]);
        $counts = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        $total = array_sum($counts);
        
        if ($total > 0) {
            $message = 'Cannot delete shop. It has associated products, users, or sales records.';
            $message_type = 'warning';
        } else {
            $stmt = $pdo->prepare("DELETE FROM shops WHERE id = ?");
            $stmt->execute([$shop_id]);
            
            // Redirect to prevent resubmission
            header("Location: shops.php?success=shop_deleted");
            exit;
        }
        
    } catch (Exception $e) {
        log_action('Delete error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Toggle shop status
if (isset($_GET['toggle'])) {
    log_action('Toggle shop status', ['id' => $_GET['toggle']]);
    
    try {
        $shop_id = (int)$_GET['toggle'];
        
        $stmt = $pdo->prepare("UPDATE shops SET is_active = NOT is_active, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$shop_id]);
        
        // Redirect to show success message WITHOUT JavaScript auto-refresh
        header("Location: shops.php?success=shop_toggled");
        exit;
        
    } catch (Exception $e) {
        log_action('Toggle error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

/* ---- USER MANAGEMENT HANDLERS ---- */

// Check if is_active column exists in users table
try {
    $check_column = $pdo->query("SHOW COLUMNS FROM users LIKE 'is_active'")->fetch();
    if (!$check_column) {
        // Add the column if it doesn't exist
        $pdo->exec("ALTER TABLE users ADD COLUMN is_active TINYINT(1) DEFAULT 1 AFTER role");
        log_action('Added is_active column to users table');
    }
} catch (Exception $e) {
    log_action("Column check error: " . $e->getMessage());
}

// Disable/Enable user
if (isset($_GET['toggle_user'])) {
    log_action('Toggle user attempt', ['id' => $_GET['toggle_user']]);
    
    try {
        $toggle_user_id = (int)$_GET['toggle_user'];
        
        // Check if trying to disable self
        if ($toggle_user_id == $user_id) {
            throw new Exception('You cannot disable your own account');
        }
        
        // Get current status
        $stmt = $pdo->prepare("SELECT id, is_active FROM users WHERE id = ?");
        $stmt->execute([$toggle_user_id]);
        $user = $stmt->fetch();
        
        if (!$user) {
            throw new Exception('User not found');
        }
        
        // Toggle is_active status
        $new_status = $user['is_active'] ? 0 : 1;
        $stmt = $pdo->prepare("UPDATE users SET is_active = ?, updated_at = ? WHERE id = ?");
        $updated_at = date('Y-m-d H:i:s');
        $stmt->execute([$new_status, $updated_at, $toggle_user_id]);
        
        // Redirect
        header("Location: shops.php?success=user_toggled");
        exit;
        
    } catch (Exception $e) {
        log_action('Toggle user error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Reset user password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    log_action('Reset password attempt', $_POST);
    
    try {
        $reset_user_id = (int)$_POST['user_id'];
        $new_password = trim($_POST['new_password']);
        $confirm_password = trim($_POST['confirm_password']);
        
        if (empty($new_password)) {
            throw new Exception('New password is required');
        }
        
        if ($new_password !== $confirm_password) {
            throw new Exception('Passwords do not match');
        }
        
        if (strlen($new_password) < 6) {
            throw new Exception('Password must be at least 6 characters long');
        }
        
        // Check if trying to reset own password
        if ($reset_user_id == $user_id) {
            throw new Exception('You cannot reset your own password here. Use profile settings instead.');
        }
        
        // Hash the new password
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        
        $stmt = $pdo->prepare("UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?");
        $updated_at = date('Y-m-d H:i:s');
        $stmt->execute([$hashed_password, $updated_at, $reset_user_id]);
        
        // Redirect
        header("Location: shops.php?success=password_reset");
        exit;
        
    } catch (Exception $e) {
        log_action('Reset password error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Reassign user to shop - FIXED VERSION
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reassign_user'])) {
    log_action('Reassign user attempt', $_POST);
    
    try {
        $reassign_user_id = (int)$_POST['reassign_user_id'];
        $new_shop_id = !empty($_POST['new_shop_id']) ? (int)$_POST['new_shop_id'] : null;
        $new_role = $_POST['new_role'];
        
        log_action('Reassign data', [
            'user_id' => $reassign_user_id,
            'new_shop_id' => $new_shop_id,
            'new_role' => $new_role
        ]);
        
        // First, check if user exists
        $stmt = $pdo->prepare("SELECT id, username FROM users WHERE id = ?");
        $stmt->execute([$reassign_user_id]);
        $user = $stmt->fetch();
        
        if (!$user) {
            throw new Exception("User with ID $reassign_user_id does not exist");
        }
        
        // Check if trying to reassign self
        if ($reassign_user_id == $user_id) {
            throw new Exception('You cannot reassign your own account');
        }
        
        // Update user with fixed SQL (using proper updated_at format)
        $updated_at = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("UPDATE users SET shop_id = ?, role = ?, updated_at = ? WHERE id = ?");
        $result = $stmt->execute([$new_shop_id, $new_role, $updated_at, $reassign_user_id]);
        
        $affected_rows = $stmt->rowCount();
        log_action('Update result', [
            'result' => $result,
            'affected_rows' => $affected_rows,
            'sql_state' => $stmt->errorInfo()
        ]);
        
        if ($affected_rows === 0) {
            throw new Exception('No changes made. User data might be the same.');
        }
        
        // Verify the update
        $verify_stmt = $pdo->prepare("SELECT shop_id, role, updated_at FROM users WHERE id = ?");
        $verify_stmt->execute([$reassign_user_id]);
        $verified_data = $verify_stmt->fetch();
        
        log_action('Verified update', $verified_data);
        
        // Redirect
        header("Location: shops.php?success=user_reassigned");
        exit;
        
    } catch (Exception $e) {
        log_action('Reassign user error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Create new user
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_user'])) {
    log_action('Create user attempt', $_POST);
    
    try {
        $new_username = trim($_POST['new_username']);
        $new_fullname = trim($_POST['new_fullname']);
        $new_password = trim($_POST['new_password']);
        $confirm_password = trim($_POST['confirm_password']);
        $new_role = $_POST['new_role'];
        $new_shop_id = !empty($_POST['new_shop_id']) ? (int)$_POST['new_shop_id'] : null;
        
        if (empty($new_username) || empty($new_fullname) || empty($new_password)) {
            throw new Exception('All fields are required');
        }
        
        if ($new_password !== $confirm_password) {
            throw new Exception('Passwords do not match');
        }
        
        // Check if username already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$new_username]);
        
        if ($stmt->fetch()) {
            throw new Exception('Username already exists');
        }
        
        // Hash password
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $created_at = date('Y-m-d H:i:s');
        
        $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, fullname, role, shop_id, created_at, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
        $stmt->execute([$new_username, $hashed_password, $new_fullname, $new_role, $new_shop_id, $created_at]);
        
        // Redirect
        header("Location: shops.php?success=user_created");
        exit;
        
    } catch (Exception $e) {
        log_action('Create user error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

/* ---- HANDLE USER ASSIGNMENT ---- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_user'])) {
    log_action('Assign user attempt', $_POST);
    
    try {
        $user_id_assign = (int)$_POST['user_id'];
        $shop_id_assign = !empty($_POST['shop_id']) ? (int)$_POST['shop_id'] : null;
        $role = $_POST['role'];
        
        // Don't allow reassigning self
        if ($user_id_assign == $user_id) {
            throw new Exception('You cannot reassign your own account');
        }
        
        $updated_at = date('Y-m-d H:i:s');
        $stmt = $pdo->prepare("UPDATE users SET shop_id = ?, role = ?, updated_at = ? WHERE id = ?");
        $stmt->execute([$shop_id_assign, $role, $updated_at, $user_id_assign]);
        
        // Redirect
        header("Location: shops.php?success=user_assigned");
        exit;
        
    } catch (Exception $e) {
        log_action('Assign user error', ['error' => $e->getMessage()]);
        $message = 'Error: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Check for success messages from redirects
if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case 'shop_toggled':
            $message = 'Shop status updated successfully!';
            $message_type = 'success';
            break;
        case 'shop_added':
            $message = 'Shop added successfully!';
            $message_type = 'success';
            break;
        case 'shop_updated':
            $message = 'Shop updated successfully!';
            $message_type = 'success';
            break;
        case 'shop_deleted':
            $message = 'Shop deleted successfully!';
            $message_type = 'success';
            break;
        case 'user_toggled':
            $message = 'User status updated successfully!';
            $message_type = 'success';
            break;
        case 'password_reset':
            $message = 'Password reset successfully!';
            $message_type = 'success';
            break;
        case 'user_reassigned':
            $message = 'User reassigned successfully!';
            $message_type = 'success';
            break;
        case 'user_created':
            $message = 'User created successfully!';
            $message_type = 'success';
            break;
        case 'user_assigned':
            $message = 'User assigned successfully!';
            $message_type = 'success';
            break;
    }
}

/* ---- FETCH DATA ---- */
// Get all shops with user counts
$shops_sql = "
    SELECT 
        s.*,
        COALESCE(u.user_count, 0) as user_count,
        COALESCE(p.product_count, 0) as product_count,
        COALESCE(sl.sale_count, 0) as sale_count,
        CONCAT(creator.fullname, ' (', creator.username, ')') as created_by_name,
        COALESCE(updater.fullname, '') as updated_by_name
    FROM shops s
    LEFT JOIN (
        SELECT shop_id, COUNT(*) as user_count 
        FROM users 
        GROUP BY shop_id
    ) u ON s.id = u.shop_id
    LEFT JOIN (
        SELECT shop_id, COUNT(*) as product_count 
        FROM products 
        GROUP BY shop_id
    ) p ON s.id = p.shop_id
    LEFT JOIN (
        SELECT shop_id, COUNT(*) as sale_count 
        FROM sales 
        GROUP BY shop_id
    ) sl ON s.id = sl.shop_id
    LEFT JOIN users creator ON s.created_by = creator.id
    LEFT JOIN users updater ON s.updated_by = updater.id
    ORDER BY s.is_active DESC, s.name ASC
";

$shops = $pdo->query($shops_sql)->fetchAll(PDO::FETCH_ASSOC);

// Get all users for assignment with shop names and status
$users_sql = "
    SELECT u.*, s.name as shop_name,
           CASE WHEN u.is_active IS NULL THEN 1 ELSE u.is_active END as is_active
    FROM users u 
    LEFT JOIN shops s ON u.shop_id = s.id 
    ORDER BY u.role, u.fullname
";
$users = $pdo->query($users_sql)->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- CSS Styles -->
<style>
/* Modern Card Design */
.shop-card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    overflow: hidden;
    margin-bottom: 20px;
}

.shop-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.shop-card.active {
    border-left: 5px solid #28a745;
}

.shop-card.inactive {
    border-left: 5px solid #6c757d;
    opacity: 0.8;
}

.shop-card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 20px;
    border-bottom: none;
}

.shop-card-header h5 {
    margin: 0;
    font-weight: 600;
}

/* Stats Cards */
.stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 3px 15px rgba(0, 0, 0, 0.05);
    margin-bottom: 15px;
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    margin-bottom: 15px;
}

.stat-icon.users { background: rgba(40, 167, 69, 0.1); color: #28a745; }
.stat-icon.products { background: rgba(0, 123, 255, 0.1); color: #007bff; }
.stat-icon.sales { background: rgba(255, 193, 7, 0.1); color: #ffc107; }

.stat-number {
    font-size: 24px;
    font-weight: 700;
    color: #2c3e50;
}

.stat-label {
    font-size: 14px;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Badge Styles */
.status-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    letter-spacing: 0.3px;
}

.badge-active { background: #d4edda; color: #155724; }
.badge-inactive { background: #e2e3e5; color: #383d41; }

/* User Status Badges */
.badge-user-active { background: #28a745; color: white; }
.badge-user-inactive { background: #dc3545; color: white; }

/* Action Buttons */
.action-btn {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin: 2px;
    transition: all 0.2s ease;
    border: none;
    font-size: 14px;
}

.action-btn:hover {
    transform: scale(1.1);
}

.btn-edit { background: #17a2b8; color: white; }
.btn-delete { background: #dc3545; color: white; }
.btn-toggle { background: #ffc107; color: #212529; }
.btn-view { background: #6c757d; color: white; }
.btn-reset { background: #6f42c1; color: white; }
.btn-reassign { background: #20c997; color: white; }
.btn-disable { background: #fd7e14; color: white; }

/* Form Styles */
.modern-form {
    background: white;
    border-radius: 15px;
    padding: 30px;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.08);
}

.form-control-modern {
    border: 2px solid #e9ecef;
    border-radius: 10px;
    padding: 12px 15px;
    font-size: 14px;
    transition: all 0.3s ease;
}

.form-control-modern:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* Tab Navigation */
.nav-modern {
    border-bottom: 2px solid #e9ecef;
}

.nav-modern .nav-link {
    border: none;
    color: #6c757d;
    font-weight: 500;
    padding: 12px 24px;
    border-radius: 10px 10px 0 0;
    margin-right: 5px;
    transition: all 0.3s ease;
}

.nav-modern .nav-link:hover {
    color: #495057;
    background: #f8f9fa;
}

.nav-modern .nav-link.active {
    color: #667eea;
    background: white;
    border-bottom: 3px solid #667eea;
}

/* Animation */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

.fade-in {
    animation: fadeIn 0.5s ease;
}

/* User Table Styles */
.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 16px;
}

.user-row-disabled {
    background-color: #f8f9fa;
    opacity: 0.7;
}

.user-row-disabled td {
    color: #6c757d !important;
}

/* Toast Notification */
.toast {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    min-width: 300px;
}

/* Modal Styles */
.modal-xl-custom {
    max-width: 1200px;
}

/* Edit Shop Modal Statistics */
#editShopModal .stat-number {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 5px;
}

#editShopModal .stat-label {
    font-size: 12px;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}


/* Edit button hover effect */
.edit-shop-btn {
    cursor: pointer;
}

/* Responsive Design */
@media (max-width: 768px) {
    .shop-card {
        margin-bottom: 15px;
    }
    
    .stat-card {
        margin-bottom: 10px;
    }
    
    .action-btn {
        width: 32px;
        height: 32px;
        font-size: 12px;
    }
    
    .user-avatar {
        width: 32px;
        height: 32px;
        font-size: 14px;
    }
}
</style>
<style>
/* Custom Toast Styles */
.custom-toast {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    min-width: 300px;
    max-width: 350px;
}

.toast-item {
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    margin-bottom: 10px;
    padding: 15px;
    display: flex;
    align-items: center;
    animation: slideInRight 0.3s ease, fadeOut 0.5s ease 3s forwards;
    border-left: 4px solid;
}

.toast-item.success {
    border-left-color: #28a745;
    background-color: #d4edda;
    color: #155724;
}

.toast-item.error {
    border-left-color: #dc3545;
    background-color: #f8d7da;
    color: #721c24;
}

.toast-item.warning {
    border-left-color: #ffc107;
    background-color: #fff3cd;
    color: #856404;
}

.toast-item.info {
    border-left-color: #17a2b8;
    background-color: #d1ecf1;
    color: #0c5460;
}

.toast-icon {
    margin-right: 10px;
    font-size: 1.2em;
}

.toast-close {
    margin-left: auto;
    background: none;
    border: none;
    color: inherit;
    cursor: pointer;
    font-size: 1.5em;
    line-height: 1;
    opacity: 0.7;
}

.toast-close:hover {
    opacity: 1;
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes fadeOut {
    from {
        opacity: 1;
        transform: translateX(0);
    }
    to {
        opacity: 0;
        transform: translateX(100%);
    }
}
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <!-- Header Section -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="text-gradient mb-2">Shop & User Management</h2>
            <p class="text-muted">Manage pharmacy branches and user accounts</p>
        </div>
        <div>
            <button class="btn btn-primary btn-lg mr-2" data-toggle="modal" data-target="#addShopModal">
                <i class="fas fa-store mr-2"></i> Add Shop
            </button>
            <!-- <button class="btn btn-success btn-lg" data-toggle="modal" data-target="#createUserModal">
                <i class="fas fa-user-plus mr-2"></i> Create User
            </button> -->
            <a href="register_user.php" class="btn btn-success btn-lg">
                <i class="fas fa-user-plus mr-2"></i> Create User
            </a>
        </div>
    </div>

    <!-- Message Alert -->
    <?php if ($message): ?>
    <div class="alert alert-<?= $message_type ?> alert-dismissible fade show fade-in" role="alert">
        <?= htmlspecialchars($message) ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <?php endif; ?>

    <!-- Tab Navigation -->
    <ul class="nav nav-modern mb-4" id="shopTabs" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="shops-tab" data-toggle="tab" href="#shops" role="tab">
                <i class="fas fa-store mr-2"></i> All Shops
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="users-tab" data-toggle="tab" href="#users" role="tab">
                <i class="fas fa-users mr-2"></i> User Management
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="stats-tab" data-toggle="tab" href="#stats" role="tab">
                <i class="fas fa-chart-bar mr-2"></i> Statistics
            </a>
        </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content" id="shopTabsContent">
        
        <!-- Shops Tab -->
        <div class="tab-pane fade show active" id="shops" role="tabpanel">
            <div class="row">
                <?php if (empty($shops)): ?>
                <div class="col-12">
                    <div class="text-center py-5">
                        <i class="fas fa-store fa-3x text-muted mb-3"></i>
                        <h4 class="text-muted">No shops found</h4>
                        <p class="text-muted">Add your first pharmacy branch to get started</p>
                        <button class="btn btn-primary" data-toggle="modal" data-target="#addShopModal">
                            <i class="fas fa-plus mr-2"></i> Create First Shop
                        </button>
                    </div>
                </div>
                <?php else: ?>
                    <?php foreach($shops as $shop): ?>
                    <div class="col-md-6 col-lg-4 fade-in">
                        <div class="shop-card <?= $shop['is_active'] ? 'active' : 'inactive' ?>">
                            <div class="shop-card-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5><?= htmlspecialchars($shop['name']) ?></h5>
                                    <span class="status-badge <?= $shop['is_active'] ? 'badge-active' : 'badge-inactive' ?>">
                                        <?= $shop['is_active'] ? 'ACTIVE' : 'INACTIVE' ?>
                                    </span>
                                </div>
                                <small class="text-white-50">
                                    <i class="fas fa-map-marker-alt mr-1"></i>
                                    <?= htmlspecialchars($shop['address'] ?: 'No address') ?>
                                </small>
                            </div>
                            
                            <div class="card-body">
                                <!-- Shop Stats -->
                                <div class="row mb-3">
                                    <div class="col-4">
                                        <div class="stat-card">
                                            <div class="stat-icon users">
                                                <i class="fas fa-users"></i>
                                            </div>
                                            <div class="stat-number"><?= $shop['user_count'] ?></div>
                                            <div class="stat-label">Users</div>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-card">
                                            <div class="stat-icon products">
                                                <i class="fas fa-pills"></i>
                                            </div>
                                            <div class="stat-number"><?= $shop['product_count'] ?></div>
                                            <div class="stat-label">Products</div>
                                        </div>
                                    </div>
                                    <div class="col-4">
                                        <div class="stat-card">
                                            <div class="stat-icon sales">
                                                <i class="fas fa-shopping-cart"></i>
                                            </div>
                                            <div class="stat-number"><?= $shop['sale_count'] ?></div>
                                            <div class="stat-label">Sales</div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Contact Info -->
                                <div class="mb-3">
                                    <?php if ($shop['phone']): ?>
                                    <p class="mb-1">
                                        <i class="fas fa-phone text-primary mr-2"></i>
                                        <small><?= htmlspecialchars($shop['phone']) ?></small>
                                    </p>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Actions -->
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <button type="button" class="action-btn btn-edit edit-shop-btn"
                                                data-toggle="modal" data-target="#editShopModal"
                                                data-shop-id="<?= $shop['id'] ?>"
                                                data-shop-name="<?= htmlspecialchars($shop['name']) ?>"
                                                data-shop-phone="<?= htmlspecialchars($shop['phone']) ?>"
                                                data-shop-address="<?= htmlspecialchars($shop['address']) ?>"
                                                data-shop-active="<?= $shop['is_active'] ?>"
                                                data-user-count="<?= $shop['user_count'] ?>"
                                                data-product-count="<?= $shop['product_count'] ?>"
                                                data-sale-count="<?= $shop['sale_count'] ?>"
                                                title="Edit Shop">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        
                                        <?php if ($shop['user_count'] == 0 && $shop['product_count'] == 0 && $shop['sale_count'] == 0): ?>
                                        <a href="?delete=<?= $shop['id'] ?>" 
                                           class="action-btn btn-delete"
                                           onclick="return confirm('Are you sure you want to delete this shop?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                        <?php endif; ?>
                                        
                                        <a href="?toggle=<?= $shop['id'] ?>" class="action-btn btn-toggle">
                                            <i class="fas fa-power-off"></i>
                                        </a>
                                    </div>
                                </div>
                                
                                <!-- Meta Info -->
                                <div class="mt-3 pt-3 border-top">
                                    <small class="text-muted">
                                        <i class="fas fa-user-plus mr-1"></i>
                                        Created by: <?= htmlspecialchars($shop['created_by_name'] ?? 'System') ?>
                                        <br>
                                        <?php if ($shop['updated_by_name']): ?>
                                        <i class="fas fa-user-edit mr-1"></i>
                                        Last updated by: <?= htmlspecialchars($shop['updated_by_name']) ?>
                                        <?php endif; ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- User Management Tab -->
        <div class="tab-pane fade" id="users" role="tabpanel">
            <div class="row mb-4">
                <div class="col-12">
                    <div class="modern-form">
                        <h4 class="mb-4"><i class="fas fa-user-cog mr-2"></i> User Management Dashboard</h4>
                        <p class="text-muted">Manage user accounts, reset passwords, and assign roles</p>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-lg-8">
                    <!-- User List Table -->
                    <div class="modern-form">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5><i class="fas fa-list mr-2"></i> All Users (<?= count($users) ?>)</h5>
                            <div>
                                <button class="btn btn-sm btn-outline-primary" onclick="filterUsers('all')">All</button>
                                <button class="btn btn-sm btn-outline-success" onclick="filterUsers('active')">Active</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="filterUsers('inactive')">Inactive</button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover" id="usersTable">
                                <thead class="thead-light">
                                    <tr>
                                        <th>User</th>
                                        <th>Username</th>
                                        <th>Role</th>
                                        <th>Shop</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($users as $user): ?>
                                    <tr class="<?= !$user['is_active'] ? 'user-row-disabled' : '' ?>" data-status="<?= $user['is_active'] ? 'active' : 'inactive' ?>">
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="user-avatar mr-2">
                                                    <?= strtoupper(substr($user['fullname'] ?: $user['username'], 0, 1)) ?>
                                                </div>
                                                <div>
                                                    <div class="font-weight-bold"><?= htmlspecialchars($user['fullname']) ?></div>
                                                    <small class="text-muted">ID: <?= $user['id'] ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="align-middle">@<?= htmlspecialchars($user['username']) ?></td>
                                        <td class="align-middle">
                                            <span class="badge 
                                                <?= $user['role'] === 'admin' ? 'badge-danger' : 
                                                   ($user['role'] === 'pharmacist' ? 'badge-info' : 'badge-primary') ?>">
                                                <?= strtoupper($user['role']) ?>
                                            </span>
                                        </td>
                                        <td class="align-middle">
                                            <?php if ($user['shop_name']): ?>
                                            <span class="badge badge-secondary"><?= htmlspecialchars($user['shop_name']) ?></span>
                                            <?php else: ?>
                                            <span class="text-muted">Not assigned</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="align-middle">
                                            <span class="badge <?= $user['is_active'] ? 'badge-user-active' : 'badge-user-inactive' ?>">
                                                <?= $user['is_active'] ? 'ACTIVE' : 'INACTIVE' ?>
                                            </span>
                                        </td>
                                        <td class="align-middle">
                                            <div class="btn-group" role="group">
                                                <?php if ($user['id'] != $user_id): ?>
                                                <button type="button" class="action-btn btn-reset" 
                                                        data-toggle="modal" data-target="#resetPasswordModal"
                                                        data-user-id="<?= $user['id'] ?>"
                                                        data-user-name="<?= htmlspecialchars($user['fullname']) ?>"
                                                        title="Reset Password">
                                                    <i class="fas fa-key"></i>
                                                </button>
                                                
                                                <button type="button" class="action-btn btn-reassign"
                                                        data-toggle="modal" data-target="#reassignUserModal"
                                                        data-user-id="<?= $user['id'] ?>"
                                                        data-user-name="<?= htmlspecialchars($user['fullname']) ?>"
                                                        data-current-shop="<?= $user['shop_name'] ?>"
                                                        data-current-role="<?= $user['role'] ?>"
                                                        title="Reassign Shop/Role">
                                                    <i class="fas fa-exchange-alt"></i>
                                                </button>
                                                
                                                <a href="?toggle_user=<?= $user['id'] ?>" 
                                                   class="action-btn btn-disable"
                                                   onclick="return confirm('Are you sure you want to <?= $user['is_active'] ? 'disable' : 'enable' ?> this user?')"
                                                   title="<?= $user['is_active'] ? 'Disable User' : 'Enable User' ?>">
                                                    <i class="fas fa-<?= $user['is_active'] ? 'user-slash' : 'user-check' ?>"></i>
                                                </a>
                                                <?php else: ?>
                                                <span class="text-muted small">Current User</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-4">
                    <!-- Quick User Assignment -->
                    <div class="modern-form mb-4">

                        <h5 class="mb-3"><i class="fas fa-user-tag mr-2"></i> Quick Assignment</h5>
                        <form method="POST" action="">
                            <div class="form-group">
                                <label class="font-weight-bold small">Select User</label>
                                <select id="user_id" class="form-control form-control-modern form-control-sm" required>
                                    <option value="">Choose user...</option>
                                    <?php foreach($users as $user): ?>
                                        <?php if ($user['is_active'] && $user['id'] != $user_id): ?>
                                        <option value="<?= $user['id'] ?>">
                                            <?= htmlspecialchars($user['fullname']) ?> (@<?= htmlspecialchars($user['username']) ?>)
                                        </option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="font-weight-bold small">Select Shop</label>
                                <select id="shop_id" class="form-control form-control-modern form-control-sm" required>
                                    <option value="">Choose shop...</option>
                                    <?php foreach($shops as $shop): ?>
                                        <?php if ($shop['is_active']): ?>
                                        <option value="<?= $shop['id'] ?>">
                                            <?= htmlspecialchars($shop['name']) ?>
                                        </option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label class="font-weight-bold small">Role</label>
                                <select id="role" class="form-control form-control-modern form-control-sm" required>
                                    <option value="cashier">Cashier</option>
                                    <option value="pharmacist">Pharmacist</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                            
                            <button type="button" id="assign_user" class="btn btn-success btn-block btn-sm">
                                <i class="fas fa-save mr-1"></i> Assign User
                            </button>
                        </form>
                    </div>
                    
                    <!-- Role Permissions -->
                    <div class="modern-form">
                        <h6 class="mb-3"><i class="fas fa-info-circle mr-2"></i> Role Permissions</h6>
                        
                        <div class="mb-3">
                            <h6 class="text-danger small"><i class="fas fa-user-shield mr-2"></i> Admin</h6>
                            <ul class="small text-muted">
                                <li>Full system access</li>
                                <li>Manage all shops & users</li>
                                <li>View all reports</li>
                            </ul>
                        </div>
                        
                        <div class="mb-3">
                            <h6 class="text-info small"><i class="fas fa-user-md mr-2"></i> Pharmacist</h6>
                            <ul class="small text-muted">
                                <li>Manage inventory</li>
                                <li>Process sales</li>
                                <li>View stock reports</li>
                            </ul>
                        </div>
                        
                        <div class="mb-3">
                            <h6 class="text-primary small"><i class="fas fa-cash-register mr-2"></i> Cashier</h6>
                            <ul class="small text-muted">
                                <li>Process sales only</li>
                                <li>View product prices</li>
                                <li>No inventory changes</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Statistics Tab -->
        <div class="tab-pane fade" id="stats" role="tabpanel">
            <div class="row">
                <div class="col-md-4">
                    <div class="stat-card">
                        <div class="d-flex align-items-center">
                            <div class="stat-icon users" style="background: rgba(102, 126, 234, 0.1); color: #667eea;">
                                <i class="fas fa-store"></i>
                            </div>
                            <div class="ml-3">
                                <div class="stat-number"><?= count($shops) ?></div>
                                <div class="stat-label">Total Shops</div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <small class="text-muted">
                                <?= count(array_filter($shops, function($s) { return $s['is_active']; })) ?> active,
                                <?= count(array_filter($shops, function($s) { return !$s['is_active']; })) ?> inactive
                            </small>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="stat-card">
                        <div class="d-flex align-items-center">
                            <div class="stat-icon users" style="background: rgba(40, 167, 69, 0.1); color: #28a745;">
                                <i class="fas fa-users"></i>
                            </div>
                            <div class="ml-3">
                                <div class="stat-number"><?= count($users) ?></div>
                                <div class="stat-label">Total Users</div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <small class="text-muted">
                                <?= count(array_filter($users, function($u) { return $u['is_active']; })) ?> active,
                                <?= count(array_filter($users, function($u) { return !$u['is_active']; })) ?> inactive
                            </small>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="stat-card">
                        <div class="d-flex align-items-center">
                            <div class="stat-icon sales" style="background: rgba(255, 193, 7, 0.1); color: #ffc107;">
                                <i class="fas fa-chart-line"></i>
                            </div>
                            <div class="ml-3">
                                <div class="stat-number"><?= array_sum(array_column($shops, 'sale_count')) ?></div>
                                <div class="stat-label">Total Sales</div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <small class="text-muted">
                                Across all pharmacy branches
                            </small>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Statistics Breakdown -->
            <div class="modern-form mt-4">
                <h5 class="mb-3"><i class="fas fa-chart-pie mr-2"></i> Statistics Breakdown</h5>
                <div class="row">
                    <div class="col-md-6">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Shop</th>
                                        <th>Users</th>
                                        <th>Products</th>
                                        <th>Sales</th>
                                        <th>Activity</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $total_users = array_sum(array_column($shops, 'user_count'));
                                    $total_products = array_sum(array_column($shops, 'product_count'));
                                    $total_sales = array_sum(array_column($shops, 'sale_count'));
                                    ?>
                                    <?php foreach($shops as $shop): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($shop['name']) ?></td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="progress flex-grow-1 mr-2" style="height: 6px;">
                                                    <div class="progress-bar bg-success" 
                                                         style="width: <?= $total_users > 0 ? ($shop['user_count'] / $total_users * 100) : 0 ?>%">
                                                    </div>
                                                </div>
                                                <?= $shop['user_count'] ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="progress flex-grow-1 mr-2" style="height: 6px;">
                                                    <div class="progress-bar bg-info" 
                                                         style="width: <?= $total_products > 0 ? ($shop['product_count'] / $total_products * 100) : 0 ?>%">
                                                    </div>
                                                </div>
                                                <?= $shop['product_count'] ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="progress flex-grow-1 mr-2" style="height: 6px;">
                                                    <div class="progress-bar bg-warning" 
                                                         style="width: <?= $total_sales > 0 ? ($shop['sale_count'] / $total_sales * 100) : 0 ?>%">
                                                    </div>
                                                </div>
                                                <?= $shop['sale_count'] ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php 
                                            $shop_total = $shop['user_count'] + $shop['product_count'] + $shop['sale_count'];
                                            $grand_total = $total_users + $total_products + $total_sales;
                                            $percentage = $grand_total > 0 ? round(($shop_total / $grand_total) * 100, 1) : 0;
                                            ?>
                                            <span class="badge <?= $percentage > 50 ? 'badge-success' : ($percentage > 20 ? 'badge-warning' : 'badge-secondary') ?>">
                                                <?= $percentage ?>%
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="text-center py-4">
                            <i class="fas fa-user-chart fa-3x text-muted mb-3"></i>
                            <h6 class="text-muted">User Distribution</h6>
                            <div class="mt-4">
                                <div class="mb-2">
                                    <span class="badge badge-danger mr-2">Admin</span>
                                    <span><?= count(array_filter($users, function($u) { return $u['role'] === 'admin'; })) ?> users</span>
                                </div>
                                <div class="mb-2">
                                    <span class="badge badge-info mr-2">Pharmacist</span>
                                    <span><?= count(array_filter($users, function($u) { return $u['role'] === 'pharmacist'; })) ?> users</span>
                                </div>
                                <div class="mb-2">
                                    <span class="badge badge-primary mr-2">Cashier</span>
                                    <span><?= count(array_filter($users, function($u) { return $u['role'] === 'cashier'; })) ?> users</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Shop Modal -->
<div class="modal fade" id="addShopModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-gradient-primary text-white">
                <h5 class="modal-title">
                    <i class="fas fa-store mr-2"></i> Add New Pharmacy
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Shop Name *</label>
                                <input type="text" name="name" id="shop_name" class="form-control form-control-modern" 
                                       placeholder="e.g., Main Pharmacy Branch" required>
                                <small class="text-muted">This will be the primary identifier</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Phone Number</label>
                                <input type="tel" name="phone" id="phone" class="form-control form-control-modern" 
                                       placeholder="e.g., +255 712 345 678">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Address</label>
                                <textarea name="address" id="address" class="form-control form-control-modern" rows="3" 
                                          placeholder="Full physical address of the pharmacy"></textarea>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Status</label>
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="statusSwitch" name="is_active" checked>
                                    <label class="custom-control-label" for="statusSwitch">Active</label>
                                </div>
                                <small class="text-muted">Inactive shops won't be available for assignments</small>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" id="add_shop" name="add_shop" class="btn btn-primary">
                        <i class="fas fa-save mr-2"></i> Save Shop
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Shop Modal (Dynamic) -->
<div class="modal fade" id="editShopModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-gradient-info text-white">
                <h5 class="modal-title">
                    <i class="fas fa-edit mr-2"></i> Edit Pharmacy
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="" id="editShopForm">
                <input type="hidden" name="shop_id" id="editShopId">
                <input type="hidden" name="update_shop" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Shop Name *</label>
                                <input type="text" name="name" id="editShopName" class="form-control form-control-modern" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Phone Number</label>
                                <input type="tel" name="phone" id="editShopPhone" class="form-control form-control-modern">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">Address</label>
                        <textarea name="address" id="editShopAddress" class="form-control form-control-modern" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">Status</label>
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="editStatusSwitch" name="is_active">
                            <label class="custom-control-label" for="editStatusSwitch">Active</label>
                        </div>
                    </div>
                    
                    <!-- Shop Statistics -->
                    <div class="mt-4 pt-3 border-top">
                        <h6 class="text-muted mb-3"><i class="fas fa-chart-bar mr-2"></i> Shop Statistics</h6>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="text-center">
                                    <div class="stat-number text-primary" id="editUserCount">0</div>
                                    <div class="stat-label">Users</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center">
                                    <div class="stat-number text-info" id="editProductCount">0</div>
                                    <div class="stat-label">Products</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center">
                                    <div class="stat-number text-warning" id="editSaleCount">0</div>
                                    <div class="stat-label">Sales</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="update_shop" class="btn btn-primary">
                        <i class="fas fa-save mr-2"></i> Update Shop
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create User Modal -->
<div class="modal fade" id="createUserModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-gradient-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus mr-2"></i> Create New User
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Full Name *</label>
                                <input type="text" id="new_fullname" class="form-control form-control-modern" 
                                       placeholder="e.g., John Doe" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Username *</label>
                                <input type="text" id="new_username" class="form-control form-control-modern" 
                                       placeholder="e.g., johndoe" required>
                                <small class="text-muted">Used for login</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Password *</label>
                                <input type="password" id="new_password" class="form-control form-control-modern" 
                                       placeholder="Minimum 6 characters" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Confirm Password *</label>
                                <input type="password" id="confirm_password" class="form-control form-control-modern" 
                                       placeholder="Re-enter password" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Role *</label>
                                <select id="new_role" class="form-control form-control-modern" required>
                                    <option value="cashier">Cashier</option>
                                    <option value="pharmacist">Pharmacist</option>
                                    <option value="admin">Admin</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Assign to Shop</label>
                                <select id="new_shop_id" class="form-control form-control-modern">
                                    <option value="">Not assigned</option>
                                    <?php foreach($shops as $shop): ?>
                                        <?php if ($shop['is_active']): ?>
                                        <option value="<?= $shop['id'] ?>"><?= htmlspecialchars($shop['name']) ?></option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" id="create_user" class="btn btn-success">
                        <i class="fas fa-user-plus mr-2"></i> Create User
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reset Password Modal -->
<div class="modal fade" id="resetPasswordModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-gradient-warning text-white">
                <h5 class="modal-title">
                    <i class="fas fa-key mr-2"></i> Reset Password
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="resetUserId">
                    <div class="text-center mb-4">
                        <i class="fas fa-user-lock fa-3x text-warning mb-3"></i>
                        <h5 id="resetUserName">User Name</h5>
                        <p class="text-muted">Set a new password for this user</p>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">New Password *</label>
                        <input type="password" name="new_password" class="form-control form-control-modern" 
                               placeholder="Enter new password" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">Confirm Password *</label>
                        <input type="password" name="confirm_password" class="form-control form-control-modern" 
                               placeholder="Confirm new password" required>
                    </div>
                    
                    <div class="alert alert-info">
                        <small>
                            <i class="fas fa-info-circle mr-1"></i>
                            The user will need to use this new password for their next login.
                        </small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="reset_password" class="btn btn-warning">
                        <i class="fas fa-sync-alt mr-2"></i> Reset Password
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reassign User Modal -->
<div class="modal fade" id="reassignUserModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-gradient-info text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exchange-alt mr-2"></i> Reassign User
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="">
                <div class="modal-body">
                    <input type="hidden" name="reassign_user_id" id="reassignUserId">
                    <div class="text-center mb-4">
                        <i class="fas fa-user-tag fa-3x text-info mb-3"></i>
                        <h5 id="reassignUserName">User Name</h5>
                        <p class="text-muted">Change shop assignment and role</p>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">Current Assignment</label>
                        <div class="alert alert-light">
                            <small>
                                Shop: <span id="currentShop" class="font-weight-bold">Not assigned</span><br>
                                Role: <span id="currentRole" class="font-weight-bold">cashier</span>
                            </small>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">New Shop *</label>
                        <select name="new_shop_id" class="form-control form-control-modern" required>
                            <option value="">Select shop...</option>
                            <?php foreach($shops as $shop): ?>
                                <?php if ($shop['is_active']): ?>
                                <option value="<?= $shop['id'] ?>"><?= htmlspecialchars($shop['name']) ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="font-weight-bold">New Role *</label>
                        <select name="new_role" class="form-control form-control-modern" required>
                            <option value="cashier">Cashier</option>
                            <option value="pharmacist">Pharmacist</option>
                            <option value="admin">Admin</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="reassign_user" class="btn btn-info">
                        <i class="fas fa-save mr-2"></i> Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Load jQuery and Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- JavaScript for Enhanced UI -->
<script>
$(document).ready(function() {
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        $('.alert').alert('close');
    }, 5000);
    
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
    
    // Tab persistence
    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
        localStorage.setItem('activeTab', $(e.target).attr('href'));
    });
    
    var activeTab = localStorage.getItem('activeTab');
    if (activeTab) {
        $('#shopTabs a[href="' + activeTab + '"]').tab('show');
    }
    
    // Form validation
    $('form').on('submit', function() {
        $(this).find('button[type="submit"]').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i> Processing...');
    });
    
    // Reset Password Modal Handler
    $('#resetPasswordModal').on('show.bs.modal', function(event) {
        var button = $(event.relatedTarget);
        var userId = button.data('user-id');
        var userName = button.data('user-name');
        
        var modal = $(this);
        modal.find('#resetUserId').val(userId);
        modal.find('#resetUserName').text(userName);
    });
    
    // Reassign User Modal Handler - FIXED VERSION
    $('#reassignUserModal').on('show.bs.modal', function(event) {
        var button = $(event.relatedTarget);
        var userId = button.data('user-id');
        var userName = button.data('user-name');
        var currentShop = button.data('current-shop');
        var currentRole = button.data('current-role');
        
        console.log("Reassign modal data:", {
            userId: userId,
            userName: userName,
            currentShop: currentShop,
            currentRole: currentRole
        });
        
        var modal = $(this);
        modal.find('#reassignUserId').val(userId);
        modal.find('#reassignUserName').text(userName);
        modal.find('#currentShop').text(currentShop || 'Not assigned');
        modal.find('#currentRole').text(currentRole);
        
        // Set current role as default in select
        modal.find('select[name="new_role"]').val(currentRole);
        
        // Clear shop select
        modal.find('select[name="new_shop_id"]').val('');
    });
    
    // Edit Shop Modal Handler
    $(document).on('click', '.edit-shop-btn', function() {
        var shopId = $(this).data('shop-id');
        var shopName = $(this).data('shop-name');
        var shopPhone = $(this).data('shop-phone') || '';
        var shopAddress = $(this).data('shop-address') || '';
        var shopActive = $(this).data('shop-active');
        var userCount = $(this).data('user-count');
        var productCount = $(this).data('product-count');
        var saleCount = $(this).data('sale-count');
        
        console.log("Editing shop:", shopId, shopName, "Active:", shopActive);
        
        // Populate modal fields
        $('#editShopId').val(shopId);
        $('#editShopName').val(shopName);
        $('#editShopPhone').val(shopPhone);
        $('#editShopAddress').val(shopAddress);
        
        // Set status switch
        $('#editStatusSwitch').prop('checked', shopActive == 1);
        
        // Update statistics
        $('#editUserCount').text(userCount);
        $('#editProductCount').text(productCount);
        $('#editSaleCount').text(saleCount);
        
        // Update modal title with shop name
        $('#editShopModal .modal-title').html('<i class="fas fa-edit mr-2"></i> Edit: ' + shopName);
    });
    
    // Form validation for edit shop
    $('#editShopForm').on('submit', function(e) {
        var shopName = $('#editShopName').val().trim();
        
        if (!shopName) {
            e.preventDefault();
            Swal.fire({
                title: 'Missing Information',
                text: 'Shop name is required',
                icon: 'warning',
                confirmButtonColor: '#3085d6',
            });
            $('#editShopName').focus();
            return false;
        }
        
        // Disable submit button and show loading
        $(this).find('button[name="update_shop"]').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i> Updating...');
    });
    
    // Clear form when modal is hidden
    $('#editShopModal').on('hidden.bs.modal', function() {
        $('#editShopForm')[0].reset();
        $('#editShopForm').find('button[name="update_shop"]').prop('disabled', false).html('<i class="fas fa-save mr-2"></i> Update Shop');
    });
    
    // Password strength indicator for create user form
    $('input[name="new_password"], input[name="confirm_password"]').on('keyup', function() {
        var password = $('input[name="new_password"]').val();
        var confirm = $('input[name="confirm_password"]').val();
        
        if (password.length > 0) {
            var strength = 0;
            if (password.length >= 6) strength++;
            if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
            if (password.match(/\d/)) strength++;
            if (password.match(/[^a-zA-Z\d]/)) strength++;
            
            var strengthText = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong'][strength];
            var strengthColor = ['danger', 'danger', 'warning', 'info', 'success'][strength];
            
            $('.password-strength').remove();
            $(this).parent().append('<small class="password-strength text-' + strengthColor + '">Strength: ' + strengthText + '</small>');
        }
        
        if (confirm.length > 0 && password !== confirm) {
            $('input[name="confirm_password"]').addClass('is-invalid');
            $('.password-match').remove();
            $('input[name="confirm_password"]').parent().append('<small class="password-match text-danger">Passwords do not match</small>');
        } else if (confirm.length > 0) {
            $('input[name="confirm_password"]').removeClass('is-invalid');
            $('.password-match').remove();
        }
    });
});

// Filter users by status
function filterUsers(status) {
    $('#usersTable tbody tr').each(function() {
        var rowStatus = $(this).data('status');
        if (status === 'all' || rowStatus === status) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
    
    // Update button states
    $('[onclick^="filterUsers"]').removeClass('active');
    $('[onclick="filterUsers(\'' + status + '\')"]').addClass('active');
}

// Generate random password
function generatePassword() {
    var length = 10;
    var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";
    var password = "";
    for (var i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    
    $('input[name="new_password"]').val(password);
    $('input[name="confirm_password"]').val(password);
    $('input[name="new_password"]').trigger('keyup');
}

// Show/hide password
function togglePassword(fieldId) {
    var field = document.getElementById(fieldId);
    var icon = field.nextElementSibling.querySelector('i');
    
    if (field.type === "password") {
        field.type = "text";
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        field.type = "password";
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}
</script>

<script>
//added this script after saving shop and user was not working
$(document).ready(function () {
    
    // Toast notification function
    function showToast(message, type = 'info', autoHide = true) {
        // Remove existing toasts
        $('.toast').remove();
        
        var icon = '';
        var bgColor = '';
        var textColor = '';
        
        switch(type) {
            case 'success':
                icon = 'fas fa-check-circle';
                bgColor = 'bg-success';
                textColor = 'text-white';
                break;
            case 'warning':
                icon = 'fas fa-exclamation-triangle';
                bgColor = 'bg-warning';
                textColor = 'text-dark';
                break;
            case 'error':
                icon = 'fas fa-times-circle';
                bgColor = 'bg-danger';
                textColor = 'text-white';
                break;
            case 'info':
            default:
                icon = 'fas fa-info-circle';
                bgColor = 'bg-info';
                textColor = 'text-white';
                break;
        }
        
        // Create toast HTML
        var toastHtml = `
            <div class="toast align-items-center ${bgColor} ${textColor} border-0" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000">
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="${icon} mr-2"></i> ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;
        
        // Append to toast container
        $('#toastContainer').append(toastHtml);
        
        // Initialize and show toast
        var toast = new bootstrap.Toast($('.toast').last()[0], {
            animation: true,
            autohide: autoHide,
            delay: 3000
        });
        toast.show();
    }
    
    // Add toast container to page if it doesn't exist
    if ($('#toastContainer').length === 0) {
        $('body').append(`
            <div id="toastContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px; max-width: 350px;"></div>
        `);
    }

    // Confirm dialog function
    function showConfirm(message, callback) {
        // Remove existing modal if any
        $('#confirmModal').remove();
        
        var modalHtml = `
            <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title"><i class="fas fa-question-circle text-primary"></i> Confirm</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p>${message}</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="confirmButton">Confirm</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
        
        var modal = new bootstrap.Modal($('#confirmModal')[0]);
        modal.show();
        
        $('#confirmButton').on('click', function() {
            modal.hide();
            if (typeof callback === 'function') {
                callback();
            }
        });
        
        $('#confirmModal').on('hidden.bs.modal', function() {
            $(this).remove();
        });
    }

    $("#add_shop").click(function (e) {
        e.preventDefault();

        var shop_name   = $("#shop_name").val();
        var phone       = $("#phone").val();
        var address     = $("#address").val();
        var shop_status = $("#statusSwitch").is(":checked") ? 1 : 0;

        // Validation
        if (!shop_name.trim()) {
            showToast("Shop name is required", "warning");
            $("#shop_name").focus();
            return;
        }

        // Show loading state
        var originalText = $(this).html();
        $(this).prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Saving...');

        $.post("save_shop.php", {
            shop_name: shop_name,
            phone: phone,
            address: address,
            shop_status: shop_status
        }, function (response) {
            if (response.status === "success") {
                showToast(response.message || "Shop added successfully", "success");
                
                // Clear form
                $("#shop_form")[0].reset();
                
                // Redirect after delay
                setTimeout(function() {
                    window.location.href = 'shops.php';
                }, 1500);
                
            } else {
                showToast(response.message || "Failed to add shop", "error");
            }
        }, "json")
        .fail(function (xhr, status, error) {
            console.error("Error:", error);
            showToast("Internal Server Error. Please try again.", "error");
        })
        .always(function() {
            // Reset button state
            $("#add_shop").prop('disabled', false).html(originalText);
        });
    });
    
    // Quick assign
   $(document).ready(function () {
    
    // Custom Toast Notification System
    function showToast(message, type = 'info') {
        // Create toast container if it doesn't exist
        if (!$('#customToastContainer').length) {
            $('body').append('<div id="customToastContainer" class="custom-toast"></div>');
        }
        
        // Icons for different types
        var icons = {
            success: '✓',
            error: '✗',
            warning: '⚠',
            info: 'ℹ'
        };
        
        // Create toast element
        var toastId = 'toast-' + Date.now();
        var toastHtml = `
            <div id="${toastId}" class="toast-item ${type}">
                <span class="toast-icon">${icons[type] || 'ℹ'}</span>
                <span class="toast-message">${message}</span>
                <button class="toast-close" onclick="$('#${toastId}').remove()">×</button>
            </div>
        `;
        
        // Add to container
        $('#customToastContainer').append(toastHtml);
        
        // Auto remove after 3.5 seconds
        setTimeout(function() {
            $('#' + toastId).remove();
        }, 3500);
    }
    
    // Simple confirmation dialog
    function showConfirm(message, callback) {
        // Remove existing confirm if any
        $('#customConfirm').remove();
        
        var confirmHtml = `
            <div id="customConfirm" style="
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 10000;
                display: flex;
                align-items: center;
                justify-content: center;
            ">
                <div style="
                    background: white;
                    padding: 20px;
                    border-radius: 10px;
                    max-width: 400px;
                    width: 90%;
                    box-shadow: 0 4px 20px rgba(0,0,0,0.2);
                ">
                    <h5 style="margin-top: 0; color: #333;">
                        <span style="color: #007bff; margin-right: 8px;">?</span>
                        Confirm
                    </h5>
                    <p>${message}</p>
                    <div style="text-align: right; margin-top: 20px;">
                        <button id="confirmCancel" style="
                            padding: 8px 16px;
                            background: #6c757d;
                            color: white;
                            border: none;
                            border-radius: 4px;
                            margin-right: 10px;
                            cursor: pointer;
                        ">Cancel</button>
                        <button id="confirmOk" style="
                            padding: 8px 16px;
                            background: #007bff;
                            color: white;
                            border: none;
                            border-radius: 4px;
                            cursor: pointer;
                        ">OK</button>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(confirmHtml);
        
        $('#confirmCancel').click(function() {
            $('#customConfirm').remove();
        });
        
        $('#confirmOk').click(function() {
            $('#customConfirm').remove();
            if (typeof callback === 'function') {
                callback();
            }
        });
    }

    // Add Shop Function
    $("#add_shop").click(function (e) {
        e.preventDefault();

        var shop_name   = $("#shop_name").val();
        var phone       = $("#phone").val();
        var address     = $("#address").val();
        var shop_status = $("#statusSwitch").is(":checked") ? 1 : 0;

        // Validation
        if (!shop_name.trim()) {
            showToast("Shop name is required", "warning");
            $("#shop_name").focus();
            return;
        }

        // Show loading state
        var originalText = $(this).html();
        $(this).prop('disabled', true).html('<span style="display:inline-block;width:1em;height:1em;border:2px solid;border-color:transparent currentColor currentColor transparent;border-radius:50%;animation:spin 0.6s linear infinite;margin-right:5px;"></span> Saving...');

        $.post("save_shop.php", {
            shop_name: shop_name,
            phone: phone,
            address: address,
            shop_status: shop_status
        }, function (response) {
            if (response.status === "success") {
                showToast(response.message || "Shop added successfully", "success");
                
                // Clear form
                $("#shop_form")[0].reset();
                
                // Redirect after delay
                setTimeout(function() {
                    window.location.href = 'shops.php';
                }, 1500);
                
            } else {
                showToast(response.message || "Failed to add shop", "error");
            }
        }, "json")
        .fail(function (xhr, status, error) {
            console.error("Error:", error);
            showToast("Internal Server Error. Please try again.", "error");
        })
        .always(function() {
            // Reset button state
            $("#add_shop").prop('disabled', false).html(originalText);
        });
    });
    
    // Quick Assign Function
    $("#assign_user").click(function(e) {
        e.preventDefault();
        
        var user_id = $("#user_id").val();
        var shop_id = $("#shop_id").val();
        var role = $("#role").val();
        
        // Validation
        if (!user_id || !shop_id || !role) {
            showToast("All fields are required", "warning");
            return false;
        }
        
        // Show confirmation
        showConfirm("Are you sure you want to assign this user?", function() {
            // Show loading state
            var originalText = $("#assign_user").html();
            $("#assign_user").prop('disabled', true).html('<span style="display:inline-block;width:1em;height:1em;border:2px solid;border-color:transparent currentColor currentColor transparent;border-radius:50%;animation:spin 0.6s linear infinite;margin-right:5px;"></span> Processing...');
            
            $.ajax({
                url: "Assign_Users.php",
                type: "POST",
                dataType: "json",
                data: {
                    user_id: user_id,
                    shop_id: shop_id,
                    role: role
                },
                success: function(data) {
                    if(data.code === "success") {
                        showToast(data.message, "success");
                        
                        // Clear form
                        $("#user_id, #shop_id, #role").val('');
                        
                    } else {
                        showToast(data.message, "error");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("AJAX Error:", status, error);
                    
                    if (xhr.status === 0) {
                        showToast("Network error. Please check your connection.", "error");
                    } else if (xhr.status === 500) {
                        showToast("Server error. Please try again later.", "error");
                    } else {
                        showToast("Failed to assign user. Please try again.", "error");
                    }
                },
                complete: function() {
                    // Reset button state
                    $("#assign_user").prop('disabled', false).html(originalText);
                }
            });
        });
    });
    
    // Add CSS for spinner animation
    $('head').append(`
        <style>
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    `);
    });
});
</script>

<?php 
require_once '../includes/footer.php'; 
ob_end_flush();
?>