<?php
/**
 * Store Dashboard - For Store Owners to manage their store
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StorePricingManager.php';
require_once '../app/classes/SessionManager.php';
use App\classes\SessionManager;

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$userId = $_SESSION['user_id'];

// SECURITY: Validate session to prevent session hijacking
$sessionManager = new SessionManager($conn);
$sessionValidation = $sessionManager->validateSession($userId);

if (!$sessionValidation['valid']) {
    // Invalid session - force logout
    error_log("Invalid session detected - User ID: $userId, Reason: " . $sessionValidation['reason']);
    $sessionManager->forceLogout();
    header("Location: ../login.php?error=session_invalid");
    exit();
}

// MULTI-LAYER SECURITY CHECK: Verify user is actually a store owner
// Uses StoreManager's multi-layer validation
$storeManager = new StoreManager($conn);
$verification = $storeManager->verifyStoreOwner($userId);

// If user is not a legitimate store owner, redirect to agent dashboard
if (!$verification['valid']) {
    error_log("Store Dashboard Access Denied - User ID: $userId, Reason: " . $verification['reason']);
    header("Location: ../user_index.php");
    exit();
}

// Load store manager
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreByOwnerId($userId);

// If user doesn't have a store, create one (only for actual store owners)
if (!$store) {
    // Get user info
    $userStmt = $conn->prepare("SELECT username, email, phone FROM agents WHERE id = ?");
    $userStmt->bind_param("i", $userId);
    $userStmt->execute();
    $userResult = $userStmt->get_result();
    $user = $userResult->fetch_assoc();
    $userStmt->close();
    
    if ($user) {
        $storeName = $user['username'] . " Store";
        $storeData = [
            'phone' => $user['phone'],
            'email' => $user['email'],
            'description' => "Welcome to " . $user['username'] . "'s data bundle store!",
            'status' => 'active'
        ];
        
        $result = $storeManager->createStore($storeName, $userId, $storeData);
        
        if ($result['success']) {
            $store = $storeManager->getStoreById($result['store_id']);
        }
    }
}

// Get store statistics
$stats = $storeManager->getStoreStats($store['id']);

// Calculate today's total gigabytes ordered
function parsePackageSizeToGb($packageSize) {
    if (empty($packageSize)) return 0;
    $packageSize = trim($packageSize);
    
    // Handle MB
    if (stripos($packageSize, 'MB') !== false) {
        $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
        return round($num / 1024, 4);
    }
    
    // Handle GB
    if (stripos($packageSize, 'GB') !== false) {
        $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
        return round($num, 4);
    }
    
    // Handle plain numbers (assume GB)
    $num = floatval(preg_replace('/[^0-9.]/', '', $packageSize));
    return round($num, 4);
}

$today = date('Y-m-d');
$todayTotalGb = 0;

// Get today's orders from orders table (direct customer orders)
$todayOrdersStmt = $conn->prepare("
    SELECT package_size 
    FROM orders 
    WHERE store_id = ? AND DATE(created_at) = ?
");
$todayOrdersStmt->bind_param("is", $store['id'], $today);
$todayOrdersStmt->execute();
$todayOrdersResult = $todayOrdersStmt->get_result();
while ($row = $todayOrdersResult->fetch_assoc()) {
    $todayTotalGb += parsePackageSizeToGb($row['package_size']);
}
$todayOrdersStmt->close();

// Get today's orders from agent_orders table (agent orders)
$todayAgentOrdersStmt = $conn->prepare("
    SELECT package_size 
    FROM agent_orders 
    WHERE store_id = ? AND DATE(created_at) = ?
");
$todayAgentOrdersStmt->bind_param("is", $store['id'], $today);
$todayAgentOrdersStmt->execute();
$todayAgentOrdersResult = $todayAgentOrdersStmt->get_result();
while ($row = $todayAgentOrdersResult->fetch_assoc()) {
    $todayTotalGb += parsePackageSizeToGb($row['package_size']);
}
$todayAgentOrdersStmt->close();

// Calculate today's total revenue
$todayTotalRevenue = 0;

// Get today's revenue from direct customer orders
$todayRevenueOrdersStmt = $conn->prepare("
    SELECT COALESCE(SUM(amount), 0) as revenue 
    FROM orders 
    WHERE store_id = ? AND DATE(created_at) = ? AND status IN ('processing', 'completed', 'delivered')
");
$todayRevenueOrdersStmt->bind_param("is", $store['id'], $today);
$todayRevenueOrdersStmt->execute();
$todayRevenueOrdersResult = $todayRevenueOrdersStmt->get_result();
$todayRevenueRow = $todayRevenueOrdersResult->fetch_assoc();
$todayTotalRevenue += $todayRevenueRow['revenue'] ?? 0;
$todayRevenueOrdersStmt->close();

// Get today's revenue from agent orders
$todayRevenueAgentOrdersStmt = $conn->prepare("
    SELECT COALESCE(SUM(amount), 0) as revenue 
    FROM agent_orders 
    WHERE store_id = ? AND DATE(created_at) = ? AND status IN ('processing', 'completed', 'delivered')
");
$todayRevenueAgentOrdersStmt->bind_param("is", $store['id'], $today);
$todayRevenueAgentOrdersStmt->execute();
$todayRevenueAgentOrdersResult = $todayRevenueAgentOrdersStmt->get_result();
$todayRevenueAgentRow = $todayRevenueAgentOrdersResult->fetch_assoc();
$todayTotalRevenue += $todayRevenueAgentRow['revenue'] ?? 0;
$todayRevenueAgentOrdersStmt->close();

// Calculate today's total profit
// Profit = Revenue from agent orders (using store pricing) - Total admin cost (using base admin pricing) for ALL orders

// Step 2: Calculate total admin cost for ALL orders (both direct and agent orders) using base admin pricing
$todayTotalAdminCost = 0;

// Function to get admin cost for a package
function getAdminCost($packageSize, $conn) {
    global $store; // Ensure access to store var if needed, though passed conn is good
    $packageSizeGb = parsePackageSizeToGb($packageSize);
    
    // Get admin pricing from tiered pricing rules
    $adminPricePerGb = null;
    $tieredStmt = $conn->prepare("SELECT price_per_gb FROM agent_pricing_rules WHERE network_type = 'mtn' AND role = 'agent' AND is_active = 1 AND min_size_gb <= ? AND max_size_gb >= ? LIMIT 1");
    if ($tieredStmt) {
        $tieredStmt->bind_param("dd", $packageSizeGb, $packageSizeGb);
        $tieredStmt->execute();
        $tieredResult = $tieredStmt->get_result();
        if ($tieredRow = $tieredResult->fetch_assoc()) {
            $adminPricePerGb = $tieredRow['price_per_gb'];
        }
        $tieredStmt->close();
    }
    
    if ($adminPricePerGb !== null && $adminPricePerGb > 0) {
        return round($adminPricePerGb * $packageSizeGb, 2);
    }
    return null;
}

// Calculate admin cost for today's direct customer orders
$todayAdminCostOrdersStmt = $conn->prepare("
    SELECT package_size 
    FROM orders 
    WHERE store_id = ? AND DATE(created_at) = ? AND status IN ('processing', 'completed', 'delivered')
");
$todayAdminCostOrdersStmt->bind_param("is", $store['id'], $today);
$todayAdminCostOrdersStmt->execute();
$todayAdminCostOrdersResult = $todayAdminCostOrdersStmt->get_result();
while ($row = $todayAdminCostOrdersResult->fetch_assoc()) {
    $adminCost = getAdminCost($row['package_size'], $conn);
    if ($adminCost !== null) {
        $todayTotalAdminCost += $adminCost;
    }
}
$todayAdminCostOrdersStmt->close();

// Calculate admin cost for today's agent orders
$todayAdminCostAgentOrdersStmt = $conn->prepare("
    SELECT package_size 
    FROM agent_orders 
    WHERE store_id = ? AND DATE(created_at) = ? AND status IN ('processing', 'completed', 'delivered')
");
$todayAdminCostAgentOrdersStmt->bind_param("is", $store['id'], $today);
$todayAdminCostAgentOrdersStmt->execute();
$todayAdminCostAgentOrdersResult = $todayAdminCostAgentOrdersStmt->get_result();
while ($row = $todayAdminCostAgentOrdersResult->fetch_assoc()) {
    $adminCost = getAdminCost($row['package_size'], $conn);
    if ($adminCost !== null) {
        $todayTotalAdminCost += $adminCost;
    }
}
$todayAdminCostAgentOrdersStmt->close();

// Step 3: Calculate profit = Total Revenue - Total Admin Cost
$todayTotalProfit = round($todayTotalRevenue - $todayTotalAdminCost, 2);

// Calculate today's total order count
$todayOrdersCount = 0;
$todayOrdersCountStmt = $conn->prepare("SELECT COUNT(*) as count FROM orders WHERE store_id = ? AND DATE(created_at) = ?");
$todayOrdersCountStmt->bind_param("is", $store['id'], $today);
$todayOrdersCountStmt->execute();
$todayOrdersCountResult = $todayOrdersCountStmt->get_result();
$todayOrdersCount += $todayOrdersCountResult->fetch_assoc()['count'] ?? 0;
$todayOrdersCountStmt->close();

$todayAgentOrdersCountStmt = $conn->prepare("SELECT COUNT(*) as count FROM agent_orders WHERE store_id = ? AND DATE(created_at) = ?");
$todayAgentOrdersCountStmt->bind_param("is", $store['id'], $today);
$todayAgentOrdersCountStmt->execute();
$todayAgentOrdersCountResult = $todayAgentOrdersCountStmt->get_result();
$todayOrdersCount += $todayAgentOrdersCountResult->fetch_assoc()['count'] ?? 0;
$todayAgentOrdersCountStmt->close();

// Get store owner's balance
$balanceStmt = $conn->prepare("SELECT balance FROM agents WHERE id = ?");
$balanceStmt->bind_param("i", $store['owner_id']);
$balanceStmt->execute();
$balanceResult = $balanceStmt->get_result();
$ownerBalance = $balanceResult->fetch_assoc()['balance'] ?? 0;
$balanceStmt->close();

// Get store agents
$agents = $storeManager->getStoreAgents($store['id']);

// Load pricing manager
$pricingManager = new StorePricingManager($conn);

// Base URL for store
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
$storeUrl = $baseUrl . "/store.php?slug=" . urlencode($store['store_slug']);

// Include reusable navigation
require_once 'includes/store_nav.php';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>My Store - <?php echo htmlspecialchars($store['store_name']); ?></title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
        }
        
        /* Mobile-first responsive styles */
        @media (max-width: 640px) {
            .container {
                padding-left: 0.75rem;
                padding-right: 0.75rem;
            }
            
            /* Compact cards */
            .stat-card {
                padding: 1rem !important;
            }
            
            .stat-card .text-3xl {
                font-size: 1.5rem !important;
            }
            
            /* Cute compact buttons */
            .btn-cute {
                padding: 0.5rem 1rem;
                font-size: 0.875rem;
                border-radius: 0.75rem;
                transition: all 0.2s;
            }
            
            .btn-cute:active {
                transform: scale(0.95);
            }
            
            /* Compact balance card */
            .balance-card {
                padding: 1rem !important;
            }
            
            .balance-card .text-4xl {
                font-size: 2rem !important;
            }
            
            /* Mobile table scroll */
            .table-wrapper {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }
            
            /* Compact modals */
            .modal-content {
                margin: 0.5rem;
                max-height: calc(100vh - 1rem);
                overflow-y: auto;
            }
        }
        
        /* Touch-friendly buttons */
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
        
        /* Smooth animations */
        * {
            transition: background-color 0.2s, transform 0.2s;
        }
    </style>
</head>

<body class="bg-gray-900">
    <?php renderStoreNav($store, 'dashboard'); ?>

    <div class="container mx-auto px-3 sm:px-4 py-4 sm:py-6">


        <!-- Store Info Card -->
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 mb-4 sm:mb-6 border border-gray-700">
            <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 sm:gap-4">
                <div class="flex-1 min-w-0">
                    <h2 class="text-lg sm:text-2xl font-bold text-white mb-1.5 sm:mb-2 truncate">
                        <?php echo htmlspecialchars($store['store_name']); ?>
                    </h2>
                    <p class="text-gray-400 mb-3 sm:mb-4 text-sm sm:text-base line-clamp-2">
                        <?php echo htmlspecialchars($store['description'] ?? 'No description'); ?>
                    </p>
                    
                    <div class="flex flex-wrap gap-2 sm:gap-4 text-xs sm:text-sm text-gray-300">
                        <?php if (!empty($store['phone'])): ?>
                        <span class="flex items-center gap-1"><i class="fas fa-phone"></i> <span class="truncate"><?php echo htmlspecialchars($store['phone']); ?></span></span>
                        <?php endif; ?>
                        
                        <?php if (!empty($store['email'])): ?>
                        <span class="flex items-center gap-1"><i class="fas fa-envelope"></i> <span class="truncate max-w-[150px]"><?php echo htmlspecialchars($store['email']); ?></span></span>
                        <?php endif; ?>
                        
                        <span id="storeStatusBadge" class="px-2 sm:px-3 py-1 rounded-full text-xs font-medium 
                            <?php echo $store['status'] === 'active' ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300'; ?>">
                            <?php echo ucfirst($store['status']); ?>
                        </span>
                    </div>
                </div>
                
                <div class="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                    <!-- Store Status Toggle -->
                    <button id="toggleStoreStatusBtn" onclick="toggleStoreStatus()" 
                            class="px-3 sm:px-4 py-2 rounded-xl text-sm sm:text-base btn-touch btn-cute flex items-center justify-center gap-1.5 w-full sm:w-auto
                            <?php echo $store['status'] === 'active' ? 'bg-red-600 hover:bg-red-700 text-white' : 'bg-green-600 hover:bg-green-700 text-white'; ?>">
                        <i class="fas <?php echo $store['status'] === 'active' ? 'fa-pause' : 'fa-play'; ?>"></i> 
                        <span><?php echo $store['status'] === 'active' ? 'Deactivate Store' : 'Activate Store'; ?></span>
                    </button>
                    
                    <button onclick="openEditStoreModal()" 
                            class="bg-blue-600 text-white px-3 sm:px-4 py-2 rounded-xl hover:bg-blue-700 text-sm sm:text-base btn-touch btn-cute flex items-center justify-center gap-1.5 w-full sm:w-auto">
                        <i class="fas fa-edit"></i> <span>Edit Store</span>
                    </button>
                </div>
            </div>
            
            <!-- Store URL -->
            <div class="mt-4 sm:mt-6 p-3 sm:p-4 bg-gray-900 rounded-xl">
                <label class="block text-xs sm:text-sm text-gray-400 mb-2">Your Store URL:</label>
                <div class="flex flex-col sm:flex-row gap-2">
                    <input type="text" readonly value="<?php echo $storeUrl; ?>" 
                           id="storeUrlInput"
                           class="flex-1 bg-gray-800 text-white px-3 sm:px-4 py-2 rounded-xl border border-gray-700 text-xs sm:text-sm">
                    <div class="flex gap-2">
                        <button onclick="copyStoreUrl()" 
                                class="bg-blue-600 text-white px-3 sm:px-4 py-2 rounded-xl hover:bg-blue-700 btn-touch btn-cute flex-1 sm:flex-none">
                            <i class="fas fa-copy mr-1"></i> <span class="hidden sm:inline">Copy</span>
                        </button>
                        <button onclick="shareStoreUrl()" 
                                class="bg-green-600 text-white px-3 sm:px-4 py-2 rounded-xl hover:bg-green-700 btn-touch btn-cute flex-1 sm:flex-none">
                            <i class="fab fa-whatsapp mr-1"></i> <span class="hidden sm:inline">Share</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Account Balance Card (Prominent) -->
        <div class="bg-gradient-to-r from-green-800 to-green-900 rounded-xl p-4 sm:p-6 mb-4 sm:mb-6 border border-green-700 balance-card">
            <div class="flex items-center justify-between gap-3 sm:gap-4">
                <div class="flex-1 min-w-0">
                    <p class="text-green-200 text-xs sm:text-sm mb-1">Account Balance</p>
                    <p class="text-2xl sm:text-4xl font-bold text-white truncate">GH₵ <?php echo number_format($ownerBalance, 2); ?></p>
                    <p class="text-xs text-green-300 mt-1.5 sm:mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        <span class="hidden sm:inline">All orders from your store will debit this balance</span>
                        <span class="sm:hidden">Orders debit this balance</span>
                    </p>
                    <div class="mt-3 sm:mt-4 flex flex-col sm:flex-row gap-2">
                        <a href="store_topup.php" 
                           class="inline-flex items-center justify-center px-3 sm:px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs sm:text-sm font-medium transition-colors btn-touch btn-cute">
                            <i class="fas fa-credit-card mr-1.5"></i>
                            <span>Top Up Account</span>
                        </a>
                        <a href="store_daily_transactions.php" 
                           class="inline-flex items-center justify-center px-3 sm:px-4 py-2 bg-green-700 hover:bg-green-600 text-white rounded-xl text-xs sm:text-sm font-medium transition-colors btn-touch btn-cute">
                            <i class="fas fa-calendar-day mr-1.5"></i>
                            <span>Today's Transactions</span>
                        </a>
                        <a href="../user_index.php?page=balance_history" 
                           class="inline-flex items-center justify-center px-3 sm:px-4 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-xl text-xs sm:text-sm font-medium transition-colors btn-touch btn-cute">
                            <i class="fas fa-chart-line mr-1.5"></i>
                            <span>Full History</span>
                        </a>
                    </div>
                </div>
                <div class="w-12 h-12 sm:w-16 sm:h-16 bg-green-700 rounded-xl flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-wallet text-green-200 text-xl sm:text-3xl"></i>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-3 sm:gap-4 lg:gap-6 mb-4 sm:mb-6">
            <div class="bg-gray-800 rounded-xl p-3 sm:p-4 lg:p-6 border border-gray-700 stat-card">
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <p class="text-gray-400 text-xs sm:text-sm truncate">Total Agents</p>
                        <p class="text-xl sm:text-2xl lg:text-3xl font-bold text-white mt-1"><?php echo $stats['total_agents']; ?></p>
                    </div>
                    <div class="w-8 h-8 sm:w-10 sm:h-10 lg:w-12 lg:h-12 bg-blue-900 rounded-lg flex items-center justify-center flex-shrink-0 ml-2">
                        <i class="fas fa-users text-blue-400 text-sm sm:text-base lg:text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-xl p-3 sm:p-4 lg:p-6 border border-gray-700 stat-card">
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <p class="text-gray-400 text-xs sm:text-sm truncate">Total Orders</p>
                        <p class="text-xl sm:text-2xl lg:text-3xl font-bold text-white mt-1"><?php echo $stats['total_orders']; ?></p>
                        <p class="text-xs text-gray-500 mt-0.5 sm:mt-1 truncate">
                            <?php echo $stats['agent_orders']; ?>A | <?php echo $stats['customer_orders']; ?>C
                        </p>
                    </div>
                    <div class="w-8 h-8 sm:w-10 sm:h-10 lg:w-12 lg:h-12 bg-green-900 rounded-lg flex items-center justify-center flex-shrink-0 ml-2">
                        <i class="fas fa-shopping-cart text-green-400 text-sm sm:text-base lg:text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-xl p-3 sm:p-4 lg:p-6 border border-gray-700 stat-card">
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <p class="text-gray-400 text-xs sm:text-sm truncate">Revenue</p>
                        <p class="text-lg sm:text-xl lg:text-3xl font-bold text-white mt-1 truncate">GH₵ <?php echo number_format($todayTotalRevenue, 0); ?></p>
                        <p class="text-xs text-gray-500 mt-0.5 sm:mt-1 hidden sm:block">Today</p>
                    </div>
                    <div class="w-8 h-8 sm:w-10 sm:h-10 lg:w-12 lg:h-12 bg-purple-900 rounded-lg flex items-center justify-center flex-shrink-0 ml-2">
                        <i class="fas fa-chart-line text-purple-400 text-sm sm:text-base lg:text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-xl p-3 sm:p-4 lg:p-6 border border-gray-700 stat-card">
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <p class="text-gray-400 text-xs sm:text-sm truncate">Avg. Order</p>
                        <p class="text-lg sm:text-xl lg:text-3xl font-bold text-white mt-1 truncate">
                            GH₵ <?php echo $todayOrdersCount > 0 ? number_format($todayTotalRevenue / $todayOrdersCount, 2) : '0'; ?>
                        </p>
                        <p class="text-xs text-gray-500 mt-0.5 sm:mt-1 hidden sm:block">Today</p>
                    </div>
                    <div class="w-8 h-8 sm:w-10 sm:h-10 lg:w-12 lg:h-12 bg-yellow-900 rounded-lg flex items-center justify-center flex-shrink-0 ml-2">
                        <i class="fas fa-calculator text-yellow-400 text-sm sm:text-base lg:text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-xl p-3 sm:p-4 lg:p-6 border border-gray-700 stat-card">
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <p class="text-gray-400 text-xs sm:text-sm truncate">Today (GB)</p>
                        <p class="text-lg sm:text-xl lg:text-3xl font-bold text-white mt-1 truncate">
                            <?php echo number_format($todayTotalGb, 1); ?>GB
                        </p>
                        <p class="text-xs text-gray-500 mt-0.5 sm:mt-1 hidden sm:block">All orders</p>
                    </div>
                    <div class="w-8 h-8 sm:w-10 sm:h-10 lg:w-12 lg:h-12 bg-indigo-900 rounded-lg flex items-center justify-center flex-shrink-0 ml-2">
                        <i class="fas fa-database text-indigo-400 text-sm sm:text-base lg:text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="bg-gray-800 rounded-xl p-3 sm:p-4 lg:p-6 border border-gray-700 stat-card">
                <div class="flex items-center justify-between">
                    <div class="min-w-0 flex-1">
                        <p class="text-gray-400 text-xs sm:text-sm truncate">Profit</p>
                        <p class="text-lg sm:text-xl lg:text-3xl font-bold <?php echo $todayTotalProfit >= 0 ? 'text-green-400' : 'text-red-400'; ?> mt-1 truncate">
                            GH₵ <?php echo number_format($todayTotalProfit, 2); ?>
                        </p>
                        <p class="text-xs text-gray-500 mt-0.5 sm:mt-1 hidden sm:block">Daily</p>
                    </div>
                    <div class="w-8 h-8 sm:w-10 sm:h-10 lg:w-12 lg:h-12 bg-emerald-900 rounded-lg flex items-center justify-center flex-shrink-0 ml-2">
                        <i class="fas fa-coins text-emerald-400 text-sm sm:text-base lg:text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-5 gap-3 sm:gap-4 mb-4 sm:mb-6">
            <a href="store_pricing.php" 
               class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 hover:border-blue-500 active:scale-95 transition-all text-center btn-touch">
                <i class="fas fa-tag text-2xl sm:text-3xl text-blue-400 mb-2"></i>
                <p class="text-white font-medium text-xs sm:text-sm">Pricing</p>
            </a>
            
            <button onclick="openInviteAgentModal()" 
                    class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 hover:border-green-500 active:scale-95 transition-all text-center btn-touch">
                <i class="fas fa-user-plus text-2xl sm:text-3xl text-green-400 mb-2"></i>
                <p class="text-white font-medium text-xs sm:text-sm">Add Agent</p>
            </button>
            
            <a href="store_orders.php" 
               class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 hover:border-purple-500 active:scale-95 transition-all text-center btn-touch">
                <i class="fas fa-list text-2xl sm:text-3xl text-purple-400 mb-2"></i>
                <p class="text-white font-medium text-xs sm:text-sm">Orders</p>
            </a>
            
            <a href="store_agents_balance_history.php" 
               class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 hover:border-amber-500 active:scale-95 transition-all text-center btn-touch">
                <i class="fas fa-history text-2xl sm:text-3xl text-amber-400 mb-2"></i>
                <p class="text-white font-medium text-xs sm:text-sm">Balance History</p>
            </a>
            
            <a href="store_subagent_topups.php" 
               class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 hover:border-blue-500 active:scale-95 transition-all text-center btn-touch">
                <i class="fas fa-credit-card text-2xl sm:text-3xl text-blue-400 mb-2"></i>
                <p class="text-white font-medium text-xs sm:text-sm">Agent Top-ups</p>
            </a>
            
            <a href="store_customization.php" 
               class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 hover:border-pink-500 active:scale-95 transition-all text-center btn-touch">
                <i class="fas fa-palette text-2xl sm:text-3xl text-pink-400 mb-2"></i>
                <p class="text-white font-medium text-xs sm:text-sm">Customize</p>
            </a>
        </div>

        <!-- Store Agents -->
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4 mb-4 sm:mb-6">
                <h3 class="text-lg sm:text-xl font-bold text-white">
                    <i class="fas fa-users mr-2"></i>
                    Store Agents
                </h3>
                <button onclick="openInviteAgentModal()" 
                        class="bg-blue-600 text-white px-3 sm:px-4 py-2 rounded-xl hover:bg-blue-700 btn-touch btn-cute w-full sm:w-auto">
                    <i class="fas fa-plus mr-1.5"></i> <span>Add Agent</span>
                </button>
            </div>

            <?php if (empty($agents)): ?>
            <div class="text-center py-8 sm:py-12">
                <i class="fas fa-users text-4xl sm:text-5xl text-gray-600 mb-3 sm:mb-4"></i>
                <p class="text-gray-400 text-sm sm:text-base">No agents yet. Invite your first agent!</p>
            </div>
            <?php else: ?>
            <div class="overflow-x-auto table-wrapper -mx-4 sm:mx-0 px-4 sm:px-0">
                <table class="w-full min-w-[800px]">
                    <thead>
                        <tr class="border-b border-gray-700 text-left">
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Agent</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Role</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2 hidden md:table-cell">Email</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2 hidden lg:table-cell">Phone</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Balance</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Actions</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2 hidden lg:table-cell">Joined</th>
                            <th class="pb-2 sm:pb-3 text-gray-400 font-medium text-xs sm:text-sm px-2">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($agents as $agent): ?>
                        <tr class="border-b border-gray-700 hover:bg-gray-750">
                            <td class="py-2 sm:py-3 text-white text-xs sm:text-sm px-2 font-medium"><?php echo htmlspecialchars($agent['username']); ?></td>
                            <td class="py-2 sm:py-3 px-2">
                                <?php 
                                $isStoreOwner = isset($agent['is_store_owner']) && $agent['is_store_owner'] == 1;
                                if ($isStoreOwner): ?>
                                    <span class="px-2 sm:px-3 py-1 rounded-full text-xs font-medium bg-purple-900 text-purple-300 flex items-center gap-1 w-fit" title="This user is a store owner">
                                        <i class="fas fa-crown text-xs"></i>
                                        <span class="hidden sm:inline">Store Owner</span>
                                        <span class="sm:hidden">Owner</span>
                                    </span>
                                <?php else: ?>
                                    <span class="px-2 sm:px-3 py-1 rounded-full text-xs font-medium bg-blue-900 text-blue-300 flex items-center gap-1 w-fit" title="Sub-agent of this store">
                                        <i class="fas fa-user text-xs"></i>
                                        Agent
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="py-2 sm:py-3 text-gray-300 text-xs sm:text-sm px-2 hidden md:table-cell truncate max-w-[150px]"><?php echo htmlspecialchars($agent['email'] ?? 'N/A'); ?></td>
                            <td class="py-2 sm:py-3 text-gray-300 text-xs sm:text-sm px-2 hidden lg:table-cell"><?php echo htmlspecialchars($agent['phone'] ?? 'N/A'); ?></td>
                            <td class="py-2 sm:py-3 text-white font-bold text-xs sm:text-sm px-2">GH₵ <?php echo number_format($agent['balance'], 2); ?></td>
                            <td class="py-2 sm:py-3 px-2">
                                <div class="flex gap-1 sm:gap-2 flex-wrap">
                                    <?php if (!$isStoreOwner): ?>
                                    <button data-agent-id="<?php echo intval($agent['id']); ?>" 
                                            data-agent-name="<?php echo htmlspecialchars($agent['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" 
                                            data-agent-balance="<?php echo floatval($agent['balance'] ?? 0); ?>"
                                            class="credit-agent-btn bg-green-600 text-white px-2 sm:px-3 py-1 rounded-lg text-xs hover:bg-green-700 active:scale-95 btn-touch btn-cute">
                                        <i class="fas fa-plus"></i> <span class="hidden sm:inline">Credit</span>
                                    </button>
                                    <button data-agent-id="<?php echo intval($agent['id']); ?>" 
                                            data-agent-name="<?php echo htmlspecialchars($agent['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" 
                                            data-agent-balance="<?php echo floatval($agent['balance'] ?? 0); ?>"
                                            class="debit-agent-btn bg-red-600 text-white px-2 sm:px-3 py-1 rounded-lg text-xs hover:bg-red-700 active:scale-95 btn-touch btn-cute">
                                        <i class="fas fa-minus"></i> <span class="hidden sm:inline">Debit</span>
                                    </button>
                                    <button data-agent-id="<?php echo intval($agent['id']); ?>" 
                                            data-agent-name="<?php echo htmlspecialchars($agent['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                            class="change-password-btn bg-yellow-600 text-white px-2 sm:px-3 py-1 rounded-lg text-xs hover:bg-yellow-700 active:scale-95 btn-touch btn-cute">
                                        <i class="fas fa-key"></i> <span class="hidden sm:inline">Password</span>
                                    </button>
                                    <?php 
                                    $agentStatus = $agent['agent_status'] ?? 'active';
                                    if ($agentStatus === 'active'): ?>
                                    <button onclick="updateAgentStatus(<?php echo intval($agent['id']); ?>, '<?php echo htmlspecialchars($agent['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>', 'suspended')" 
                                            class="bg-orange-600 text-white px-2 sm:px-3 py-1 rounded-lg text-xs hover:bg-orange-700 active:scale-95 btn-touch btn-cute">
                                        <i class="fas fa-ban"></i> <span class="hidden sm:inline">Suspend</span>
                                    </button>
                                    <?php else: ?>
                                    <button onclick="updateAgentStatus(<?php echo intval($agent['id']); ?>, '<?php echo htmlspecialchars($agent['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>', 'active')" 
                                            class="bg-green-600 text-white px-2 sm:px-3 py-1 rounded-lg text-xs hover:bg-green-700 active:scale-95 btn-touch btn-cute">
                                        <i class="fas fa-check"></i> <span class="hidden sm:inline">Activate</span>
                                    </button>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                    <a href="store_agents_balance_history.php?agent_id=<?php echo $agent['id']; ?>" 
                                       class="bg-blue-600 text-white px-2 sm:px-3 py-1 rounded-lg text-xs hover:bg-blue-700 active:scale-95 btn-touch btn-cute inline-flex items-center">
                                        <i class="fas fa-history"></i> <span class="hidden sm:inline ml-1">History</span>
                                    </a>
                                </div>
                            </td>
                            <td class="py-2 sm:py-3 text-gray-300 text-xs sm:text-sm px-2 hidden lg:table-cell"><?php echo date('M d, Y', strtotime($agent['joined_at'])); ?></td>
                            <td class="py-2 sm:py-3 px-2">
                                <span class="px-2 sm:px-3 py-1 rounded-full text-xs font-medium 
                                    <?php echo $agent['agent_status'] === 'active' ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300'; ?>">
                                    <?php echo ucfirst($agent['agent_status']); ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Edit Store Modal -->
    <div id="editStoreModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-3 sm:px-4 py-4">
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 w-full max-w-md border border-gray-700 modal-content max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">Edit Store</h3>
                <button onclick="closeEditStoreModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="editStoreForm" class="space-y-4">
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Store Name</label>
                    <input type="text" name="store_name" value="<?php echo htmlspecialchars($store['store_name']); ?>"
                           disabled
                           class="w-full bg-gray-800 text-gray-400 px-4 py-2 rounded-lg border border-gray-600 cursor-not-allowed">
                    <p class="text-xs text-yellow-400 mt-1">
                        <i class="fas fa-lock mr-1"></i>
                        Store name cannot be changed after creation to maintain permanent URL
                    </p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Description</label>
                    <textarea name="description" rows="3"
                              class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600"><?php echo htmlspecialchars($store['description'] ?? ''); ?></textarea>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">MoMo Phone Number</label>
                    <input type="tel" name="phone" id="store_phone" value="<?php echo htmlspecialchars($store['phone'] ?? ''); ?>"
                           pattern="[0-9]{10}" maxlength="10"
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                    <p class="text-xs text-gray-500 mt-1">Enter 10-digit phone number (e.g., 0247965501)</p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">MoMo Account Name <span class="text-red-400">*</span></label>
                    <input type="text" name="momo_name" id="store_momo_name" value="<?php echo htmlspecialchars($store['momo_name'] ?? ''); ?>"
                           maxlength="100"
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600"
                           placeholder="e.g., John Doe, Jane Smith">
                    <p class="text-xs text-gray-500 mt-1">Enter the name associated with the MoMo phone number. Customers will see this when making payments.</p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">WhatsApp</label>
                    <input type="tel" name="whatsapp" id="store_whatsapp" value="<?php echo htmlspecialchars($store['whatsapp'] ?? ''); ?>"
                           pattern="[0-9]{10}" maxlength="10"
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                    <p class="text-xs text-gray-500 mt-1">Enter 10-digit WhatsApp number (e.g., 0247965501)</p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">WhatsApp Group Link</label>
                    <input type="url" name="whatsapp_group_link" id="store_whatsapp_group_link" 
                           value="<?php echo htmlspecialchars($store['whatsapp_group_link'] ?? ''); ?>"
                           placeholder="https://chat.whatsapp.com/xxxxxxxxxx"
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                    <p class="text-xs text-gray-500 mt-1">Share your WhatsApp group invite link for customers to join</p>
                </div>
                
                <div class="mt-4 p-3 bg-blue-900/20 border border-blue-700 rounded-lg">
                    <p class="text-sm text-blue-300">
                        <i class="fas fa-info-circle mr-2"></i>
                        Want to customize your store's appearance? 
                        <a href="store_customization.php" class="underline font-semibold hover:text-blue-200">Visit the Customization page</a>
                    </p>
                </div>
                
                <button type="submit" 
                        class="w-full bg-blue-600 text-white py-3 rounded-xl hover:bg-blue-700 active:scale-95 btn-touch btn-cute">
                    <i class="fas fa-save mr-2"></i>Save Changes
                </button>
            </form>
        </div>
    </div>

    <!-- Invite Agent Modal -->
    <div id="inviteAgentModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-3 sm:px-4 py-4">
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 w-full max-w-md border border-gray-700 modal-content max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">Add Agent</h3>
                <button onclick="closeInviteAgentModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <!-- Tabs -->
            <div class="flex gap-2 mb-4 border-b border-gray-700">
                <button onclick="switchTab('direct')" id="tab-direct" 
                        class="px-4 py-2 text-sm font-medium text-blue-400 border-b-2 border-blue-400">
                    <i class="fas fa-user-plus mr-1"></i>Add Directly
                </button>
                <button onclick="switchTab('invite')" id="tab-invite" 
                        class="px-4 py-2 text-sm font-medium text-gray-400 hover:text-white border-b-2 border-transparent">
                    <i class="fas fa-link mr-1"></i>Invite Link
                </button>
            </div>
            
            <!-- Add Agent Directly Tab -->
            <div id="tab-content-direct" class="tab-content">
                <form id="addAgentForm" onsubmit="addAgentDirectly(event)">
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Username *</label>
                        <input type="text" id="agentUsername" name="username" required minlength="3"
                               class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500"
                               placeholder="Enter username (min 3 chars)">
                    </div>
                    
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Email *</label>
                        <input type="email" id="agentEmail" name="email" required
                               class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500"
                               placeholder="agent@example.com">
                    </div>
                    
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Phone Number *</label>
                        <input type="tel" id="agentPhone" name="phone" required pattern="[0-9]{10}" maxlength="10"
                               class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500"
                               placeholder="0247965501">
                        <p class="text-xs text-gray-500 mt-1">10 digits starting with 0</p>
                    </div>
                    
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Password *</label>
                        <input type="password" id="agentPassword" name="password" required minlength="6"
                               class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500"
                               placeholder="Min 6 characters">
                    </div>
                    
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Initial Balance (GH₵)</label>
                        <input type="number" id="agentBalance" name="balance" step="0.01" min="0" value="0.00"
                               class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-blue-500">
                    </div>
                    
                    <div id="addAgentError" class="hidden mb-4 p-3 bg-red-900 border border-red-700 text-red-300 rounded-lg text-sm"></div>
                    <div id="addAgentSuccess" class="hidden mb-4 p-3 bg-green-900 border border-green-700 text-green-300 rounded-lg text-sm"></div>
                    
                    <button type="submit" id="addAgentSubmitBtn"
                            class="w-full bg-blue-600 text-white py-3 rounded-xl hover:bg-blue-700 active:scale-95 btn-touch btn-cute">
                        <i class="fas fa-user-plus mr-2"></i>Create Agent
                    </button>
                </form>
            </div>
            
            <!-- Invite Link Tab -->
            <div id="tab-content-invite" class="tab-content hidden">
                <div class="mb-4">
                    <p class="text-gray-400 text-sm mb-4">Share this link with your agents:</p>
                    <div class="bg-gray-900 p-4 rounded-lg">
                        <p class="text-blue-400 text-sm break-all" id="agentInviteLink">
                            <?php echo $baseUrl; ?>/register_agent.php?store=<?php echo urlencode($store['store_slug']); ?>
                        </p>
                    </div>
                    <button onclick="copyInviteLink()" 
                            class="w-full mt-4 bg-blue-600 text-white py-3 rounded-xl hover:bg-blue-700 active:scale-95 btn-touch btn-cute">
                        <i class="fas fa-copy mr-2"></i>Copy Invite Link
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Credit Agent Balance Modal -->
    <div id="creditModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-3 sm:px-4 py-4">
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 w-full max-w-md border border-gray-700 modal-content max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">
                    <i class="fas fa-plus-circle text-green-400 mr-2"></i>Credit Agent Balance
                </h3>
                <button onclick="closeCreditModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="creditForm">
                <div class="mb-4">
                    <p class="text-gray-300 mb-2">Agent: <span id="creditAgentName" class="font-bold text-white"></span></p>
                    <p class="text-gray-400 text-sm">Current Balance: <span id="creditCurrentBalance" class="text-yellow-400 font-semibold"></span></p>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-400 mb-2">Amount (GH₵)</label>
                    <input type="number" id="creditAmount" name="amount" step="0.01" min="0.01" max="50000" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-green-500">
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-400 mb-2">Note (Optional)</label>
                    <textarea id="creditNote" name="note" rows="3"
                              class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-green-500"
                              placeholder="Add a note for this transaction..."></textarea>
                </div>
                
                <button type="submit" id="creditSubmitBtn"
                        class="w-full bg-green-600 text-white py-3 rounded-xl hover:bg-green-700 active:scale-95 btn-touch btn-cute">
                    <i class="fas fa-check mr-2"></i>Credit Balance
                </button>
            </form>
        </div>
    </div>

    <!-- Change Agent Password Modal -->
    <div id="changePasswordModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-3 sm:px-4 py-4">
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 w-full max-w-md border border-gray-700 modal-content max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">
                    <i class="fas fa-key text-yellow-400 mr-2"></i>Change Agent Password
                </h3>
                <button onclick="closeChangePasswordModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="changePasswordForm" onsubmit="changeAgentPassword(event)">
                <div class="mb-4">
                    <p class="text-gray-300 mb-2">Agent: <span id="changePasswordAgentName" class="font-bold text-white"></span></p>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-400 mb-2">New Password *</label>
                    <input type="password" id="newAgentPassword" name="new_password" required minlength="6"
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-yellow-500"
                           placeholder="Enter new password (min 6 characters)">
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-400 mb-2">Confirm Password *</label>
                    <input type="password" id="confirmAgentPassword" name="confirm_password" required minlength="6"
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-yellow-500"
                           placeholder="Confirm new password">
                </div>
                
                <div id="changePasswordError" class="hidden mb-4 p-3 bg-red-900 border border-red-700 text-red-300 rounded-lg text-sm"></div>
                <div id="changePasswordSuccess" class="hidden mb-4 p-3 bg-green-900 border border-green-700 text-green-300 rounded-lg text-sm"></div>
                
                <button type="submit" id="changePasswordSubmitBtn"
                        class="w-full bg-yellow-600 text-white py-3 rounded-xl hover:bg-yellow-700 active:scale-95 btn-touch btn-cute">
                    <i class="fas fa-key mr-2"></i>Change Password
                </button>
            </form>
        </div>
    </div>

    <!-- Debit Agent Balance Modal -->
    <div id="debitModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-3 sm:px-4 py-4">
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 w-full max-w-md border border-gray-700 modal-content max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">
                    <i class="fas fa-minus-circle text-red-400 mr-2"></i>Debit Agent Balance
                </h3>
                <button onclick="closeDebitModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="debitForm">
                <div class="mb-4">
                    <p class="text-gray-300 mb-2">Agent: <span id="debitAgentName" class="font-bold text-white"></span></p>
                    <p class="text-gray-400 text-sm">Current Balance: <span id="debitCurrentBalance" class="text-yellow-400 font-semibold"></span></p>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-400 mb-2">Amount (GH₵)</label>
                    <input type="number" id="debitAmount" name="amount" step="0.01" min="0.01" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-red-500">
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm text-gray-400 mb-2">Note (Optional)</label>
                    <textarea id="debitNote" name="note" rows="3"
                              class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600 focus:border-red-500"
                              placeholder="Add a note for this transaction..."></textarea>
                </div>
                
                <button type="submit" id="debitSubmitBtn"
                        class="w-full bg-red-600 text-white py-3 rounded-xl hover:bg-red-700 active:scale-95 btn-touch btn-cute">
                    <i class="fas fa-minus mr-2"></i>Debit Balance
                </button>
            </form>
        </div>
    </div>

    <script>
        const storeId = <?php echo $store['id']; ?>;
        
        function copyStoreUrl() {
            const input = document.getElementById('storeUrlInput');
            input.select();
            document.execCommand('copy');
            alert('Store URL copied to clipboard!');
        }
        
        function shareStoreUrl() {
            const url = document.getElementById('storeUrlInput').value;
            const text = encodeURIComponent('Check out my data bundle store: ' + url);
            window.open('https://wa.me/?text=' + text, '_blank');
        }
        
        function openEditStoreModal() {
            document.getElementById('editStoreModal').classList.remove('hidden');
        }
        
        function closeEditStoreModal() {
            document.getElementById('editStoreModal').classList.add('hidden');
        }
        
        function openInviteAgentModal() {
            document.getElementById('inviteAgentModal').classList.remove('hidden');
            switchTab('direct'); // Default to direct add tab
        }
        
        function closeInviteAgentModal() {
            document.getElementById('inviteAgentModal').classList.add('hidden');
            // Reset form
            document.getElementById('addAgentForm').reset();
            document.getElementById('addAgentError').classList.add('hidden');
            document.getElementById('addAgentSuccess').classList.add('hidden');
        }
        
        function switchTab(tab) {
            // Hide all tab contents
            document.getElementById('tab-content-direct').classList.add('hidden');
            document.getElementById('tab-content-invite').classList.add('hidden');
            
            // Reset tab button styles
            document.getElementById('tab-direct').classList.remove('text-blue-400', 'border-blue-400');
            document.getElementById('tab-direct').classList.add('text-gray-400', 'border-transparent');
            document.getElementById('tab-invite').classList.remove('text-blue-400', 'border-blue-400');
            document.getElementById('tab-invite').classList.add('text-gray-400', 'border-transparent');
            
            // Show selected tab
            if (tab === 'direct') {
                document.getElementById('tab-content-direct').classList.remove('hidden');
                document.getElementById('tab-direct').classList.remove('text-gray-400', 'border-transparent');
                document.getElementById('tab-direct').classList.add('text-blue-400', 'border-blue-400');
            } else {
                document.getElementById('tab-content-invite').classList.remove('hidden');
                document.getElementById('tab-invite').classList.remove('text-gray-400', 'border-transparent');
                document.getElementById('tab-invite').classList.add('text-blue-400', 'border-blue-400');
            }
        }
        
        async function addAgentDirectly(event) {
            event.preventDefault();
            
            const errorDiv = document.getElementById('addAgentError');
            const successDiv = document.getElementById('addAgentSuccess');
            const submitBtn = document.getElementById('addAgentSubmitBtn');
            
            // Hide previous messages
            errorDiv.classList.add('hidden');
            successDiv.classList.add('hidden');
            
            // Get form data
            const formData = {
                username: document.getElementById('agentUsername').value.trim(),
                email: document.getElementById('agentEmail').value.trim(),
                phone: document.getElementById('agentPhone').value.trim(),
                password: document.getElementById('agentPassword').value,
                balance: parseFloat(document.getElementById('agentBalance').value) || 0.00
            };
            
            // Validate phone
            const cleanPhone = formData.phone.replace(/\D/g, '');
            if (cleanPhone.length !== 10 || cleanPhone.charAt(0) !== '0') {
                errorDiv.textContent = 'Phone must be exactly 10 digits starting with 0';
                errorDiv.classList.remove('hidden');
                return;
            }
            formData.phone = cleanPhone;
            
            // Disable submit button
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Creating...';
            
            try {
                const response = await fetch('../api/create_store_agent.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });
                
                // Check if response is ok
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP error! status: ${response.status} - ${errorText.substring(0, 100)}`);
                }
                
                // Get response text
                const responseText = await response.text();
                
                // Try to parse JSON
                let data;
                try {
                    if (!responseText) {
                        throw new Error('Empty response from server');
                    }
                    data = JSON.parse(responseText);
                } catch (parseError) {
                    console.error('JSON Parse Error:', parseError);
                    console.error('Response text:', responseText);
                    throw new Error('Invalid response from server: ' + responseText.substring(0, 100));
                }
                
                if (data.success) {
                    successDiv.textContent = data.message || 'Agent created successfully!';
                    successDiv.classList.remove('hidden');
                    
                    // Reset form
                    document.getElementById('addAgentForm').reset();
                    
                    // Reload page after 1.5 seconds
                    setTimeout(() => {
                        location.reload();
                    }, 1500);
                } else {
                    errorDiv.textContent = data.message || 'Failed to create agent';
                    errorDiv.classList.remove('hidden');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            } catch (error) {
                console.error('Error:', error);
                errorDiv.textContent = 'Error: ' + (error.message || 'An error occurred. Please try again.');
                errorDiv.classList.remove('hidden');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        }
        
        // Credit/Debit Modal Functions
        let currentAgentId = null;
        let currentAgentName = '';
        let currentAgentBalance = 0;
        
        function openCreditModal(agentId, agentName, currentBalance) {
            currentAgentId = agentId;
            currentAgentName = agentName;
            currentAgentBalance = parseFloat(currentBalance) || 0;
            document.getElementById('creditAgentName').textContent = agentName;
            document.getElementById('creditCurrentBalance').textContent = 'GH₵ ' + currentAgentBalance.toFixed(2);
            document.getElementById('creditAmount').value = '';
            document.getElementById('creditModal').classList.remove('hidden');
        }
        
        function closeCreditModal() {
            document.getElementById('creditModal').classList.add('hidden');
            document.getElementById('creditForm').reset();
        }
        
        function openDebitModal(agentId, agentName, currentBalance) {
            currentAgentId = agentId;
            currentAgentName = agentName;
            currentAgentBalance = parseFloat(currentBalance) || 0;
            document.getElementById('debitAgentName').textContent = agentName;
            document.getElementById('debitCurrentBalance').textContent = 'GH₵ ' + currentAgentBalance.toFixed(2);
            document.getElementById('debitAmount').value = '';
            document.getElementById('debitModal').classList.remove('hidden');
        }
        
        function closeDebitModal() {
            document.getElementById('debitModal').classList.add('hidden');
            document.getElementById('debitForm').reset();
        }
        
        // Event delegation for credit/debit/password buttons (avoids inline onclick escaping issues)
        document.addEventListener('click', function(e) {
            if (e.target.closest('.credit-agent-btn')) {
                const btn = e.target.closest('.credit-agent-btn');
                const agentId = parseInt(btn.getAttribute('data-agent-id'));
                const agentName = btn.getAttribute('data-agent-name');
                const agentBalance = parseFloat(btn.getAttribute('data-agent-balance')) || 0;
                openCreditModal(agentId, agentName, agentBalance);
            } else if (e.target.closest('.debit-agent-btn')) {
                const btn = e.target.closest('.debit-agent-btn');
                const agentId = parseInt(btn.getAttribute('data-agent-id'));
                const agentName = btn.getAttribute('data-agent-name');
                const agentBalance = parseFloat(btn.getAttribute('data-agent-balance')) || 0;
                openDebitModal(agentId, agentName, agentBalance);
            } else if (e.target.closest('.change-password-btn')) {
                const btn = e.target.closest('.change-password-btn');
                const agentId = parseInt(btn.getAttribute('data-agent-id'));
                const agentName = btn.getAttribute('data-agent-name');
                if (typeof openChangePasswordModal === 'function') {
                    openChangePasswordModal(agentId, agentName);
                }
            }
        });
        
        // Change Password Modal Functions
        function openChangePasswordModal(agentId, agentName) {
            currentAgentId = agentId;
            document.getElementById('changePasswordAgentName').textContent = agentName;
            document.getElementById('changePasswordForm').reset();
            document.getElementById('changePasswordError').classList.add('hidden');
            document.getElementById('changePasswordSuccess').classList.add('hidden');
            document.getElementById('changePasswordModal').classList.remove('hidden');
        }
        
        function closeChangePasswordModal() {
            document.getElementById('changePasswordModal').classList.add('hidden');
            document.getElementById('changePasswordForm').reset();
            document.getElementById('changePasswordError').classList.add('hidden');
            document.getElementById('changePasswordSuccess').classList.add('hidden');
        }
        
        async function changeAgentPassword(event) {
            event.preventDefault();
            
            const errorDiv = document.getElementById('changePasswordError');
            const successDiv = document.getElementById('changePasswordSuccess');
            const submitBtn = document.getElementById('changePasswordSubmitBtn');
            
            // Hide previous messages
            errorDiv.classList.add('hidden');
            successDiv.classList.add('hidden');
            
            // Get form data
            const newPassword = document.getElementById('newAgentPassword').value;
            const confirmPassword = document.getElementById('confirmAgentPassword').value;
            
            // Validate passwords match
            if (newPassword !== confirmPassword) {
                errorDiv.textContent = 'Passwords do not match';
                errorDiv.classList.remove('hidden');
                return;
            }
            
            // Validate password length
            if (newPassword.length < 6) {
                errorDiv.textContent = 'Password must be at least 6 characters';
                errorDiv.classList.remove('hidden');
                return;
            }
            
            // Disable submit button
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Changing...';
            
            try {
                const response = await fetch('../api/change_agent_password.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        agent_id: currentAgentId,
                        new_password: newPassword
                    })
                });
                
                // Check if response is ok
                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`HTTP error! status: ${response.status} - ${errorText.substring(0, 100)}`);
                }
                
                // Get response text
                const responseText = await response.text();
                
                // Try to parse JSON
                let data;
                try {
                    if (!responseText) {
                        throw new Error('Empty response from server');
                    }
                    data = JSON.parse(responseText);
                } catch (parseError) {
                    console.error('JSON Parse Error:', parseError);
                    console.error('Response text:', responseText);
                    throw new Error('Invalid response from server: ' + responseText.substring(0, 100));
                }
                
                if (data.success) {
                    successDiv.textContent = data.message || 'Password changed successfully!';
                    successDiv.classList.remove('hidden');
                    
                    // Reset form
                    document.getElementById('changePasswordForm').reset();
                    
                    // Close modal after 1.5 seconds
                    setTimeout(() => {
                        closeChangePasswordModal();
                    }, 1500);
                } else {
                    errorDiv.textContent = data.message || 'Failed to change password';
                    errorDiv.classList.remove('hidden');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            } catch (error) {
                console.error('Error:', error);
                errorDiv.textContent = 'Error: ' + (error.message || 'An error occurred. Please try again.');
                errorDiv.classList.remove('hidden');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        }
        
        // Handle Credit Form Submission
        document.getElementById('creditForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const amount = parseFloat(document.getElementById('creditAmount').value);
            const note = document.getElementById('creditNote').value.trim();
            
            if (!amount || amount <= 0) {
                alert('Please enter a valid amount');
                return;
            }
            
            if (amount > 50000) {
                alert('Amount cannot exceed GH₵ 50,000');
                return;
            }
            
            const submitBtn = document.getElementById('creditSubmitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';
            
            try {
                const formData = new FormData();
                formData.append('agent_id', currentAgentId);
                formData.append('amount', amount);
                formData.append('note', note);
                formData.append('action', 'credit');
                
                const response = await fetch('manage_agent_balance.php', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Agent balance credited successfully!');
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Credit Balance';
                }
            } catch (error) {
                alert('An error occurred. Please try again.');
                console.error('Credit error:', error);
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Credit Balance';
            }
        });
        
        // Handle Debit Form Submission
        document.getElementById('debitForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const amount = parseFloat(document.getElementById('debitAmount').value);
            const note = document.getElementById('debitNote').value.trim();
            
            if (!amount || amount <= 0) {
                alert('Please enter a valid amount');
                return;
            }
            
            if (amount > currentAgentBalance) {
                alert('Cannot debit more than current balance (GH₵ ' + currentAgentBalance.toFixed(2) + ')');
                return;
            }
            
            if (!confirm('Are you sure you want to debit GH₵ ' + amount.toFixed(2) + ' from ' + currentAgentName + '?')) {
                return;
            }
            
            const submitBtn = document.getElementById('debitSubmitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';
            
            try {
                const formData = new FormData();
                formData.append('agent_id', currentAgentId);
                formData.append('amount', amount);
                formData.append('note', note);
                formData.append('action', 'debit');
                
                const response = await fetch('manage_agent_balance.php', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Agent balance debited successfully!');
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-minus mr-2"></i>Debit Balance';
                }
            } catch (error) {
                alert('An error occurred. Please try again.');
                console.error('Debit error:', error);
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-minus mr-2"></i>Debit Balance';
            }
        });
        
        // Phone number validation for add agent form
        document.addEventListener('DOMContentLoaded', function() {
            const phoneInput = document.getElementById('agentPhone');
            if (phoneInput) {
                phoneInput.addEventListener('input', function() {
                    // Remove any non-digit characters
                    this.value = this.value.replace(/\D/g, '');
                    // Limit to 10 digits
                    if (this.value.length > 10) {
                        this.value = this.value.substring(0, 10);
                    }
                    
                    // Validate format
                    const phone = this.value.trim();
                    this.classList.remove('border-red-500', 'border-green-500');
                    
                    if (phone.length === 10 && phone.charAt(0) === '0') {
                        this.classList.add('border-green-500');
                    } else if (phone.length > 0) {
                        this.classList.add('border-red-500');
                    }
                });
                
                phoneInput.addEventListener('blur', function() {
                    const phone = this.value.trim();
                    if (phone.length > 0 && (phone.length !== 10 || phone.charAt(0) !== '0')) {
                        this.classList.add('border-red-500');
                    }
                });
            }
        });
        
        // Update Agent Status Function
        async function updateAgentStatus(agentId, agentName, newStatus) {
            const action = newStatus === 'suspended' ? 'suspend' : 'activate';
            const confirmMessage = newStatus === 'suspended' 
                ? `Are you sure you want to suspend ${agentName}?\n\nSuspended agents will not be able to place orders.`
                : `Are you sure you want to activate ${agentName}?`;
            
            if (!confirm(confirmMessage)) {
                return;
            }
            
            try {
                const formData = new FormData();
                formData.append('agent_id', agentId);
                formData.append('status', newStatus);
                
                const response = await fetch('update_agent_status.php', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert(`Agent ${action}ed successfully!`);
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (error) {
                alert('An error occurred. Please try again.');
                console.error('Update agent status error:', error);
            }
        }
        
        function copyInviteLink() {
            const link = document.getElementById('agentInviteLink').textContent;
            navigator.clipboard.writeText(link).then(() => {
                alert('Invite link copied to clipboard!');
            });
        }
        
        // Toggle Store Status Function
        async function toggleStoreStatus() {
            const currentStatus = '<?php echo $store['status']; ?>';
            const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
            const action = newStatus === 'active' ? 'activate' : 'deactivate';
            const confirmMessage = newStatus === 'inactive' 
                ? 'Are you sure you want to deactivate your store?\n\nWhen deactivated:\n- Your store will not be accessible to customers\n- Customers cannot place orders\n- Your store will appear as inactive\n\nYou can reactivate it anytime.'
                : 'Are you sure you want to activate your store?\n\nWhen activated:\n- Your store will be accessible to customers\n- Customers can place orders\n- Your store will appear as active';
            
            if (!confirm(confirmMessage)) {
                return;
            }
            
            const btn = document.getElementById('toggleStoreStatusBtn');
            const originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span>Processing...</span>';
            
            try {
                const formData = new FormData();
                formData.append('store_id', <?php echo $store['id']; ?>);
                formData.append('status', newStatus);
                
                const response = await fetch('../api/toggle_store_status.php', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert(`Store ${action}d successfully!`);
                    window.location.reload();
                } else {
                    alert('Error: ' + data.message);
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            } catch (error) {
                alert('An error occurred. Please try again.');
                console.error('Toggle store status error:', error);
                btn.disabled = false;
                btn.innerHTML = originalText;
            }
        }
        
        // Phone number validation for store contact info
        const storePhoneInput = document.getElementById('store_phone');
        const storeWhatsappInput = document.getElementById('store_whatsapp');
        
        function validatePhoneInput(input) {
            input.addEventListener('input', function() {
                // Remove any non-digit characters
                this.value = this.value.replace(/\D/g, '');
                // Limit to 10 digits
                if (this.value.length > 10) {
                    this.value = this.value.substring(0, 10);
                }
                
                // Validate format
                const phone = this.value.trim();
                this.classList.remove('border-red-500', 'border-green-500');
                
                if (phone.length === 10 && phone.charAt(0) === '0') {
                    this.classList.add('border-green-500');
                } else if (phone.length > 0) {
                    this.classList.add('border-red-500');
                }
            });
            
            input.addEventListener('blur', function() {
                const phone = this.value.trim();
                if (phone.length > 0 && (phone.length !== 10 || phone.charAt(0) !== '0')) {
                    this.classList.add('border-red-500');
                }
            });
        }
        
        if (storePhoneInput) {
            validatePhoneInput(storePhoneInput);
        }
        
        if (storeWhatsappInput) {
            validatePhoneInput(storeWhatsappInput);
        }
        
        // Handle edit store form submission
        document.getElementById('editStoreForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Validate phone numbers before submission
            const phone = storePhoneInput ? storePhoneInput.value.trim() : '';
            const whatsapp = storeWhatsappInput ? storeWhatsappInput.value.trim() : '';
            
            if (phone && (phone.length !== 10 || phone.charAt(0) !== '0')) {
                alert('Please enter a valid phone number. Must be exactly 10 digits starting with 0 (e.g., 0247965501).');
                if (storePhoneInput) storePhoneInput.focus();
                return;
            }
            
            if (whatsapp && (whatsapp.length !== 10 || whatsapp.charAt(0) !== '0')) {
                alert('Please enter a valid WhatsApp number. Must be exactly 10 digits starting with 0 (e.g., 0247965501).');
                if (storeWhatsappInput) storeWhatsappInput.focus();
                return;
            }
            
            const formData = new FormData(this);
            formData.append('store_id', storeId);
            // Remove store_name from form data - it cannot be changed for security
            formData.delete('store_name');
            
            fetch('update_store.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Store updated successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred');
            });
        });
    </script>
</body>
</html>



