<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

$integratedAuth = new IntegratedAdminAuth();
$database = new Database();
$pdo = $database->getConnection();
$siteManager = new SiteManager($database);
$auth = new MultiTenantAuth($pdo);

// Check if logged in with integrated system
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

// Validate session and get admin data
$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Check if user is master admin
$isMaster = isset($adminData['is_master']) && $adminData['is_master'];
if (!$isMaster) {
    header('Location: dashboard.php?error=' . urlencode('Access denied. Master admin only.'));
    exit;
}

// Update session data for template
$_SESSION['integrated_admin_data'] = $adminData;
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

// Handle AJAX request for getting sub admin data (must be before any HTML output)
if (isset($_GET['get_sub_admin']) && is_numeric($_GET['get_sub_admin'])) {
    $subAdminId = (int)$_GET['get_sub_admin'];
    
    try {
        $pdo = $database->getConnection();
        
        // Get sub admin basic data
        $stmt = $pdo->prepare("SELECT * FROM site_admins WHERE id = ?");
        $stmt->execute([$subAdminId]);
        $subAdmin = $stmt->fetch();
        
        if ($subAdmin) {
            // Get permissions
            $permStmt = $pdo->prepare("
                SELECT pt.permission_key 
                FROM admin_permissions ap 
                JOIN permission_types pt ON ap.permission_type_id = pt.id 
                WHERE ap.admin_id = ?
            ");
            $permStmt->execute([$subAdminId]);
            $permissions = $permStmt->fetchAll(PDO::FETCH_COLUMN);
            
            // Get market access
            $marketStmt = $pdo->prepare("
                SELECT market_name, can_view, can_edit, can_manage_results 
                FROM admin_market_access 
                WHERE admin_id = ?
            ");
            $marketStmt->execute([$subAdminId]);
            $marketAccess = $marketStmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Convert market access to associative array
            $marketAccessMap = [];
            foreach ($marketAccess as $access) {
                $marketAccessMap[$access['market_name']] = [
                    'can_view' => (bool)$access['can_view'],
                    'can_edit' => (bool)$access['can_edit'],
                    'can_manage_results' => (bool)$access['can_manage_results']
                ];
            }
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => true, 
                'sub_admin' => $subAdmin,
                'permissions' => $permissions,
                'market_access' => $marketAccessMap
            ]);
        } else {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => 'Sub admin not found']);
        }
    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

$currentSite = $siteManager->getCurrentSite();
$success = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action === 'create_sub_admin') {
            // Create new sub-admin
            $username = trim($_POST['username']);
            $email = trim($_POST['email']);
            $fullName = trim($_POST['full_name']);
            $password = $_POST['password'];
            $siteId = $_POST['site_id'] ?? null;
            $permissions = $_POST['permissions'] ?? [];
            $marketAccess = $_POST['market_access'] ?? [];
            
            // If no site selected, use current site
            if (empty($siteId)) {
                $siteId = $currentSite['id'];
            }
            
            if (empty($username) || empty($email) || empty($fullName) || empty($password)) {
                throw new Exception('Semua field wajib diisi');
            }
            
            // Check if username already exists
            $checkStmt = $pdo->prepare("SELECT id FROM site_admins WHERE username = ?");
            $checkStmt->execute([$username]);
            if ($checkStmt->fetch()) {
                throw new Exception('Username sudah digunakan');
            }
            
            // Hash password
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            
            // Insert new sub-admin
            $stmt = $pdo->prepare("
                INSERT INTO site_admins (username, email, full_name, password, site_id, created_by, created_at, is_active) 
                VALUES (?, ?, ?, ?, ?, ?, NOW(), 1)
            ");
            $stmt->execute([$username, $email, $fullName, $hashedPassword, $siteId, $integratedAuth->getAdminId($adminData)]);
            $subAdminId = $pdo->lastInsertId();
            
            // Insert permissions
            foreach ($permissions as $permission) {
                // Get permission_type_id from permission_key
                $permTypeStmt = $pdo->prepare("SELECT id FROM permission_types WHERE permission_key = ?");
                $permTypeStmt->execute([$permission]);
                $permissionTypeId = $permTypeStmt->fetchColumn();
                
                if ($permissionTypeId) {
                    $permStmt = $pdo->prepare("
                        INSERT INTO admin_permissions (admin_id, permission_type_id) 
                        VALUES (?, ?)
                    ");
                    $permStmt->execute([$subAdminId, $permissionTypeId]);
                }
            }
            
            // Insert market access
            foreach ($marketAccess as $marketData) {
                $marketStmt = $pdo->prepare("
                    INSERT INTO admin_market_access (admin_id, market_name, can_view, can_edit, can_manage_results) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $marketStmt->execute([
                    $subAdminId,
                    $marketData['market_id'], // This will be market name actually
                    isset($marketData['can_view']) ? 1 : 0,
                    isset($marketData['can_edit']) ? 1 : 0,
                    isset($marketData['can_manage_results']) ? 1 : 0
                ]);
            }
            
            // Log activity
            $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'CREATE_SUB_ADMIN', 
                "Created sub-admin: $username for site: " . ($siteId ? $siteId : 'all'), 'master');
            
            $success = 'Sub admin berhasil dibuat!';
            
        } elseif ($action === 'update_sub_admin') {
            // Update existing sub-admin
            $subAdminId = $_POST['sub_admin_id'];
            $username = trim($_POST['username']);
            $email = trim($_POST['email']);
            $fullName = trim($_POST['full_name']);
            $siteId = !empty($_POST['site_id']) ? $_POST['site_id'] : $currentSite['id'];
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            $permissions = $_POST['permissions'] ?? [];
            $marketAccess = $_POST['market_access'] ?? [];
            
            // Update sub-admin basic info
            $stmt = $pdo->prepare("
                UPDATE site_admins 
                SET email = ?, full_name = ?, site_id = ?, is_active = ? 
                WHERE id = ?
            ");
            $stmt->execute([$email, $fullName, $siteId, $isActive, $subAdminId]);
            
            // Update password if provided
            if (!empty($_POST['password'])) {
                $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $passStmt = $pdo->prepare("UPDATE site_admins SET password = ? WHERE id = ?");
                $passStmt->execute([$hashedPassword, $subAdminId]);
            }
            
            // Delete old permissions and insert new ones
            $delStmt = $pdo->prepare("DELETE FROM admin_permissions WHERE admin_id = ?");
            $delStmt->execute([$subAdminId]);
            
            foreach ($permissions as $permission) {
                // Get permission_type_id from permission_key
                $permTypeStmt = $pdo->prepare("SELECT id FROM permission_types WHERE permission_key = ?");
                $permTypeStmt->execute([$permission]);
                $permissionTypeId = $permTypeStmt->fetchColumn();
                
                if ($permissionTypeId) {
                    $permStmt = $pdo->prepare("
                        INSERT INTO admin_permissions (admin_id, permission_type_id) 
                        VALUES (?, ?)
                    ");
                    $permStmt->execute([$subAdminId, $permissionTypeId]);
                }
            }
            
            // Delete old market access and insert new ones
            $delMarketStmt = $pdo->prepare("DELETE FROM admin_market_access WHERE admin_id = ?");
            $delMarketStmt->execute([$subAdminId]);
            
            foreach ($marketAccess as $marketData) {
                $marketStmt = $pdo->prepare("
                    INSERT INTO admin_market_access (admin_id, market_name, can_view, can_edit, can_manage_results) 
                    VALUES (?, ?, ?, ?, ?)
                ");
                $marketStmt->execute([
                    $subAdminId,
                    $marketData['market_id'], // This will be market name actually
                    isset($marketData['can_view']) ? 1 : 0,
                    isset($marketData['can_edit']) ? 1 : 0,
                    isset($marketData['can_manage_results']) ? 1 : 0
                ]);
            }
            
            $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_SUB_ADMIN', 
                "Updated sub-admin: $username", 'master');
            
            $success = 'Sub admin berhasil diupdate!';
            
        } elseif ($action === 'delete_sub_admin') {
            // Delete sub-admin
            $subAdminId = $_POST['sub_admin_id'];
            
            // Get sub-admin info for logging
            $infoStmt = $pdo->prepare("SELECT username FROM site_admins WHERE id = ?");
            $infoStmt->execute([$subAdminId]);
            $subAdminInfo = $infoStmt->fetch();
            
            // Delete permissions
            $delPermStmt = $pdo->prepare("DELETE FROM admin_permissions WHERE admin_id = ?");
            $delPermStmt->execute([$subAdminId]);
            
            // Delete market access
            $delMarketStmt = $pdo->prepare("DELETE FROM admin_market_access WHERE admin_id = ?");
            $delMarketStmt->execute([$subAdminId]);
            
            // Delete sub-admin
            $delStmt = $pdo->prepare("DELETE FROM site_admins WHERE id = ?");
            $delStmt->execute([$subAdminId]);
            
            $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'DELETE_SUB_ADMIN', 
                "Deleted sub-admin: " . ($subAdminInfo['username'] ?? 'Unknown'), 'master');
            
            $success = 'Sub admin berhasil dihapus!';
        }
        
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Get all sub-admins
$subAdmins = [];
try {
    $stmt = $pdo->prepare("
        SELECT sa.*, s.site_name, COUNT(ap.id) as permission_count,
               COUNT(ama.id) as market_count
        FROM site_admins sa
        LEFT JOIN sites s ON sa.site_id = s.id
        LEFT JOIN admin_permissions ap ON sa.id = ap.admin_id
        LEFT JOIN admin_market_access ama ON sa.id = ama.admin_id
        GROUP BY sa.id
        ORDER BY sa.created_at DESC
    ");
    $stmt->execute();
    $subAdmins = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error getting sub-admins: " . $e->getMessage());
}

// Get available sites
$sites = [];
try {
    $stmt = $pdo->prepare("SELECT id, site_name, domain FROM sites WHERE is_active = 1 ORDER BY site_name");
    $stmt->execute();
    $sites = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error getting sites: " . $e->getMessage());
}

// Get available markets
$markets = [];
try {
    $stmt = $pdo->prepare("SELECT id, market_name, market_code FROM market_schedules ORDER BY market_name");
    $stmt->execute();
    $markets = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error getting markets: " . $e->getMessage());
}

// Get available permissions
$availablePermissions = [
    'manage_colors' => 'Kelola Warna Tema',
    'manage_content' => 'Kelola Konten',
    'manage_results' => 'Kelola Hasil Togel',
    'manage_markets' => 'Kelola Pasaran',
    'manage_buku_mimpi' => 'Kelola Buku Mimpi',
    'manage_livedraw' => 'Kelola Live Draw',
    'manage_paito' => 'Kelola Paito Warna',
    'manage_prediksi' => 'Kelola Prediksi',
    'manage_history' => 'Kelola History',
    'view_analytics' => 'Lihat Analytics'
];

// Set page variables for template
$pageTitle = 'Kelola Sub Admin';
$pageDescription = 'Manajemen sub admin dan permissions';
$headerActions = '
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createSubAdminModal">
        <i class="bi bi-person-plus me-1"></i>
        Tambah Sub Admin
    </button>
';

// Set flash messages
if ($success) {
    $_SESSION['success_message'] = $success;
}
if ($error) {
    $_SESSION['error_message'] = $error;
}

// Include sidebar template
include 'admin-sidebar-template.php';
?>

<!-- Sub Admins Content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-people me-2"></i>
                    Daftar Sub Admin
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($subAdmins)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-person-x display-4 text-muted"></i>
                    <h5 class="mt-3">Belum ada Sub Admin</h5>
                    <p class="text-muted">Klik tombol "Tambah Sub Admin" untuk menambahkan sub admin pertama</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Username</th>
                                <th>Full Name</th>
                                <th>Email</th>
                                <th>Site</th>
                                <th>Permissions</th>
                                <th>Markets</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($subAdmins as $subAdmin): ?>
                            <tr>
                                <td>
                                    <strong><?php echo htmlspecialchars($subAdmin['username']); ?></strong>
                                </td>
                                <td><?php echo htmlspecialchars($subAdmin['full_name']); ?></td>
                                <td><?php echo htmlspecialchars($subAdmin['email']); ?></td>
                                <td>
                                    <span class="badge bg-info">
                                        <?php echo $subAdmin['site_name'] ?? 'All Sites'; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-primary">
                                        <?php echo $subAdmin['permission_count']; ?> permissions
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-success">
                                        <?php echo $subAdmin['market_count']; ?> markets
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-<?php echo $subAdmin['is_active'] ? 'success' : 'danger'; ?>">
                                        <?php echo $subAdmin['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary" 
                                                onclick="editSubAdmin(<?php echo $subAdmin['id']; ?>)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteSubAdmin(<?php echo $subAdmin['id']; ?>, '<?php echo htmlspecialchars($subAdmin['username']); ?>')">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Create Sub Admin Modal -->
<div class="modal fade" id="createSubAdminModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah Sub Admin Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="create_sub_admin">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Username *</label>
                            <input type="text" class="form-control" name="username" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email *</label>
                            <input type="email" class="form-control" name="email" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Full Name *</label>
                            <input type="text" class="form-control" name="full_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password *</label>
                            <input type="password" class="form-control" name="password" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Assign to Site</label>
                        <select class="form-select" name="site_id">
                            <option value="">Default (Current Site: <?php echo htmlspecialchars($currentSite['site_name']); ?>)</option>
                            <?php foreach ($sites as $site): ?>
                            <option value="<?php echo $site['id']; ?>" <?php echo ($site['id'] == $currentSite['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($site['site_name']); ?><?php echo ($site['id'] == $currentSite['id']) ? ' (Current)' : ''; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text">Kosongkan untuk assign ke site saat ini (<?php echo htmlspecialchars($currentSite['site_name']); ?>)</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Permissions</label>
                        <div class="row">
                            <?php foreach ($availablePermissions as $key => $label): ?>
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" 
                                           name="permissions[]" value="<?php echo $key; ?>" 
                                           id="perm_<?php echo $key; ?>">
                                    <label class="form-check-label" for="perm_<?php echo $key; ?>">
                                        <?php echo $label; ?>
                                    </label>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Market Access</label>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Market</th>
                                        <th>
                                            <div class="d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input me-2" 
                                                       id="check_all_view" onchange="toggleAllPermissions('can_view')">
                                                <label for="check_all_view">View</label>
                                            </div>
                                        </th>
                                        <th>
                                            <div class="d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input me-2" 
                                                       id="check_all_edit" onchange="toggleAllPermissions('can_edit')">
                                                <label for="check_all_edit">Edit</label>
                                            </div>
                                        </th>
                                        <th>
                                            <div class="d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input me-2" 
                                                       id="check_all_manage" onchange="toggleAllPermissions('can_manage_results')">
                                                <label for="check_all_manage">Manage Results</label>
                                            </div>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($markets as $market): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($market['market_name']); ?></td>
                                        <td>
                                            <input type="checkbox" class="form-check-input market-permission can_view" 
                                                   name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][can_view]">
                                            <input type="hidden" name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][market_id]" 
                                                   value="<?php echo htmlspecialchars($market['market_name']); ?>">
                                        </td>
                                        <td>
                                            <input type="checkbox" class="form-check-input market-permission can_edit" 
                                                   name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][can_edit]">
                                        </td>
                                        <td>
                                            <input type="checkbox" class="form-check-input market-permission can_manage_results" 
                                                   name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][can_manage_results]">
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Sub Admin</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Sub Admin Modal -->
<div class="modal fade" id="editSubAdminModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Sub Admin</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editSubAdminForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_sub_admin">
                    <input type="hidden" name="sub_admin_id" id="edit_sub_admin_id">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Username *</label>
                            <input type="text" class="form-control" name="username" id="edit_username" required readonly>
                            <div class="form-text">Username tidak dapat diubah</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Email *</label>
                            <input type="email" class="form-control" name="email" id="edit_email" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Full Name *</label>
                            <input type="text" class="form-control" name="full_name" id="edit_full_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Password</label>
                            <input type="password" class="form-control" name="password" id="edit_password">
                            <div class="form-text">Kosongkan jika tidak ingin mengubah password</div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Assign to Site</label>
                        <select class="form-select" name="site_id" id="edit_site_id">
                            <option value="">Default (Current Site: <?php echo htmlspecialchars($currentSite['site_name']); ?>)</option>
                            <?php foreach ($sites as $site): ?>
                            <option value="<?php echo $site['id']; ?>" <?php echo ($site['id'] == $currentSite['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($site['site_name']); ?><?php echo ($site['id'] == $currentSite['id']) ? ' (Current)' : ''; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text">Kosongkan untuk assign ke site saat ini (<?php echo htmlspecialchars($currentSite['site_name']); ?>)</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Permissions</label>
                        <div class="row">
                            <?php foreach ($availablePermissions as $key => $label): ?>
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input edit-permission" type="checkbox" 
                                           name="permissions[]" value="<?php echo $key; ?>" 
                                           id="edit_perm_<?php echo $key; ?>">
                                    <label class="form-check-label" for="edit_perm_<?php echo $key; ?>">
                                        <?php echo $label; ?>
                                    </label>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Market Access</label>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Market</th>
                                        <th>
                                            <div class="d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input me-2" 
                                                       id="edit_check_all_view" onchange="toggleAllEditPermissions('can_view')">
                                                <label for="edit_check_all_view">View</label>
                                            </div>
                                        </th>
                                        <th>
                                            <div class="d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input me-2" 
                                                       id="edit_check_all_edit" onchange="toggleAllEditPermissions('can_edit')">
                                                <label for="edit_check_all_edit">Edit</label>
                                            </div>
                                        </th>
                                        <th>
                                            <div class="d-flex align-items-center">
                                                <input type="checkbox" class="form-check-input me-2" 
                                                       id="edit_check_all_manage" onchange="toggleAllEditPermissions('can_manage_results')">
                                                <label for="edit_check_all_manage">Manage Results</label>
                                            </div>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($markets as $market): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($market['market_name']); ?></td>
                                        <td>
                                            <input type="checkbox" class="form-check-input edit-market-permission can_view" 
                                                   name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][can_view]">
                                            <input type="hidden" name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][market_id]" 
                                                   value="<?php echo htmlspecialchars($market['market_name']); ?>">
                                        </td>
                                        <td>
                                            <input type="checkbox" class="form-check-input edit-market-permission can_edit" 
                                                   name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][can_edit]">
                                        </td>
                                        <td>
                                            <input type="checkbox" class="form-check-input edit-market-permission can_manage_results" 
                                                   name="market_access[<?php echo htmlspecialchars($market['market_name']); ?>][can_manage_results]">
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Sub Admin</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
// Additional JavaScript for sub-admins
$additionalJS = '
<script>
function editSubAdmin(id) {
    // Fetch sub admin data using AJAX
    fetch("?get_sub_admin=" + id)
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.success) {
                var subAdmin = data.sub_admin;
                var permissions = data.permissions;
                var marketAccess = data.market_access;
                
                // Populate basic fields
                document.getElementById("edit_sub_admin_id").value = subAdmin.id;
                document.getElementById("edit_username").value = subAdmin.username;
                document.getElementById("edit_email").value = subAdmin.email;
                document.getElementById("edit_full_name").value = subAdmin.full_name;
                document.getElementById("edit_password").value = "";
                
                // Set site selection
                var siteSelect = document.getElementById("edit_site_id");
                siteSelect.value = subAdmin.site_id || "";
                
                // Clear all permission checkboxes first
                document.querySelectorAll(".edit-permission").forEach(function(checkbox) {
                    checkbox.checked = false;
                });
                
                // Set permissions
                permissions.forEach(function(permission) {
                    var checkbox = document.getElementById("edit_perm_" + permission);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
                
                // Clear all market access checkboxes first
                document.querySelectorAll(".edit-market-permission").forEach(function(checkbox) {
                    checkbox.checked = false;
                });
                
                // Set market access
                Object.keys(marketAccess).forEach(function(marketName) {
                    var access = marketAccess[marketName];
                    var prefix = "market_access[" + marketName + "]";
                    
                    if (access.can_view) {
                        var checkbox = document.querySelector("input[name=\\"" + prefix + "[can_view]\\"]");
                        if (checkbox) checkbox.checked = true;
                    }
                    
                    if (access.can_edit) {
                        var checkbox = document.querySelector("input[name=\\"" + prefix + "[can_edit]\\"]");
                        if (checkbox) checkbox.checked = true;
                    }
                    
                    if (access.can_manage_results) {
                        var checkbox = document.querySelector("input[name=\\"" + prefix + "[can_manage_results]\\"]");
                        if (checkbox) checkbox.checked = true;
                    }
                });
                
                // Update master checkboxes for edit modal
                updateEditMasterCheckboxes();
                
                // Show modal
                var modal = new bootstrap.Modal(document.getElementById("editSubAdminModal"));
                modal.show();
                
            } else {
                showNotification(data.message || "Failed to load sub admin data", "error");
            }
        })
        .catch(function(error) {
            console.error("Error:", error);
            showNotification("Error loading sub admin data", "error");
        });
}

// Function to update master checkboxes in edit modal
function updateEditMasterCheckboxes() {
    ["can_view", "can_edit", "can_manage_results"].forEach(function(permissionType) {
        var checkboxes = document.querySelectorAll(".edit-market-permission." + permissionType);
        var checkedCount = document.querySelectorAll(".edit-market-permission." + permissionType + ":checked").length;
        
        var masterCheckboxId;
        switch(permissionType) {
            case "can_view":
                masterCheckboxId = "edit_check_all_view";
                break;
            case "can_edit":
                masterCheckboxId = "edit_check_all_edit";
                break;
            case "can_manage_results":
                masterCheckboxId = "edit_check_all_manage";
                break;
        }
        
        var masterCheckbox = document.getElementById(masterCheckboxId);
        if (masterCheckbox) {
            if (checkedCount === 0) {
                masterCheckbox.indeterminate = false;
                masterCheckbox.checked = false;
            } else if (checkedCount === checkboxes.length) {
                masterCheckbox.indeterminate = false;
                masterCheckbox.checked = true;
            } else {
                masterCheckbox.indeterminate = true;
                masterCheckbox.checked = false;
            }
        }
    });
}

// Toggle all permissions for edit modal
function toggleAllEditPermissions(permissionType) {
    var masterCheckboxId;
    switch(permissionType) {
        case "can_view":
            masterCheckboxId = "edit_check_all_view";
            break;
        case "can_edit":
            masterCheckboxId = "edit_check_all_edit";
            break;
        case "can_manage_results":
            masterCheckboxId = "edit_check_all_manage";
            break;
    }
    
    var masterCheckbox = document.getElementById(masterCheckboxId);
    var checkboxes = document.querySelectorAll(".edit-market-permission." + permissionType);
    
    if (masterCheckbox && checkboxes.length > 0) {
        checkboxes.forEach(function(checkbox) {
            checkbox.checked = masterCheckbox.checked;
        });
    }
}

function deleteSubAdmin(id, username) {
    if (confirm("Are you sure you want to delete sub-admin: " + username + "?")) {
        const form = document.createElement("form");
        form.method = "POST";
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_sub_admin">
            <input type="hidden" name="sub_admin_id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Toggle all permissions for a specific column
function toggleAllPermissions(permissionType) {
    var masterCheckboxId;
    
    // Map permission types to their master checkbox IDs
    switch(permissionType) {
        case "can_view":
            masterCheckboxId = "check_all_view";
            break;
        case "can_edit":
            masterCheckboxId = "check_all_edit";
            break;
        case "can_manage_results":
            masterCheckboxId = "check_all_manage";
            break;
        default:
            masterCheckboxId = "check_all_" + permissionType.replace("can_", "");
    }
    
    var masterCheckbox = document.getElementById(masterCheckboxId);
    var checkboxes = document.querySelectorAll(".market-permission." + permissionType);
    
    if (masterCheckbox && checkboxes.length > 0) {
        checkboxes.forEach(function(checkbox) {
            checkbox.checked = masterCheckbox.checked;
        });
    }
}

// Market permission logic
document.addEventListener("DOMContentLoaded", function() {
    // Original create modal market rows
    const marketRows = document.querySelectorAll("tbody tr");
    
    marketRows.forEach(row => {
        const viewCheckbox = row.querySelector(".can_view");
        const editCheckbox = row.querySelector(".can_edit");
        const manageCheckbox = row.querySelector(".can_manage_results");
        
        // Auto-check view when edit or manage is checked
        if (editCheckbox) {
            editCheckbox.addEventListener("change", function() {
                if (this.checked && viewCheckbox) {
                    viewCheckbox.checked = true;
                }
            });
        }
        
        if (manageCheckbox) {
            manageCheckbox.addEventListener("change", function() {
                if (this.checked && viewCheckbox) {
                    viewCheckbox.checked = true;
                }
            });
        }
        
        // Uncheck dependent permissions when view is unchecked
        if (viewCheckbox) {
            viewCheckbox.addEventListener("change", function() {
                if (!this.checked) {
                    if (editCheckbox) editCheckbox.checked = false;
                    if (manageCheckbox) manageCheckbox.checked = false;
                }
            });
        }
    });
    
    // Edit modal market permission logic
    var setupEditModalPermissions = function() {
        var editMarketRows = document.querySelectorAll("#editSubAdminModal tbody tr");
        
        editMarketRows.forEach(function(row) {
            var viewCheckbox = row.querySelector(".edit-market-permission.can_view");
            var editCheckbox = row.querySelector(".edit-market-permission.can_edit");
            var manageCheckbox = row.querySelector(".edit-market-permission.can_manage_results");
            
            // Auto-check view when edit or manage is checked
            if (editCheckbox) {
                editCheckbox.addEventListener("change", function() {
                    if (this.checked && viewCheckbox) {
                        viewCheckbox.checked = true;
                    }
                });
            }
            
            if (manageCheckbox) {
                manageCheckbox.addEventListener("change", function() {
                    if (this.checked && viewCheckbox) {
                        viewCheckbox.checked = true;
                    }
                });
            }
            
            // Uncheck dependent permissions when view is unchecked
            if (viewCheckbox) {
                viewCheckbox.addEventListener("change", function() {
                    if (!this.checked) {
                        if (editCheckbox) editCheckbox.checked = false;
                        if (manageCheckbox) manageCheckbox.checked = false;
                    }
                    updateEditMasterCheckboxes();
                });
            }
            
            // Update master checkboxes when individual checkboxes change
            [editCheckbox, manageCheckbox].forEach(function(checkbox) {
                if (checkbox) {
                    checkbox.addEventListener("change", function() {
                        updateEditMasterCheckboxes();
                    });
                }
            });
        });
    };
    
    // Setup edit modal permissions when modal is shown
    document.getElementById("editSubAdminModal").addEventListener("shown.bs.modal", setupEditModalPermissions);
    
    // Update master checkboxes when individual checkboxes change
    function updateMasterCheckbox(permissionType) {
        var checkboxes = document.querySelectorAll(".market-permission." + permissionType);
        var checkedCount = document.querySelectorAll(".market-permission." + permissionType + ":checked").length;
        
        var masterCheckboxId;
        // Map permission types to their master checkbox IDs
        switch(permissionType) {
            case "can_view":
                masterCheckboxId = "check_all_view";
                break;
            case "can_edit":
                masterCheckboxId = "check_all_edit";
                break;
            case "can_manage_results":
                masterCheckboxId = "check_all_manage";
                break;
            default:
                masterCheckboxId = "check_all_" + permissionType.replace("can_", "");
        }
        
        var masterCheckbox = document.getElementById(masterCheckboxId);
        
        if (masterCheckbox) {
            if (checkedCount === 0) {
                masterCheckbox.indeterminate = false;
                masterCheckbox.checked = false;
            } else if (checkedCount === checkboxes.length) {
                masterCheckbox.indeterminate = false;
                masterCheckbox.checked = true;
            } else {
                masterCheckbox.indeterminate = true;
                masterCheckbox.checked = false;
            }
        }
    }
    
    // Listen for changes on all market permission checkboxes
    document.querySelectorAll(".market-permission").forEach(function(checkbox) {
        checkbox.addEventListener("change", function() {
            var classList = this.classList;
            var permissionType = classList[classList.length - 1]; // Get last class
            updateMasterCheckbox(permissionType);
        });
    });
});
</script>';

include 'admin-sidebar-footer.php';
?>