<?php
/**
 * Fix Agent Roles - Utility script to correct is_store_owner flags
 * This fixes agents that have is_store_owner = 1 but don't actually own a store
 * 
 * Run this script once to fix any existing data issues
 */

require_once 'config.php';
require_once 'app/classes/StoreManager.php';

echo "=== Fixing Agent Roles ===\n\n";

$storeManager = new StoreManager($conn);

// Find all agents with is_store_owner = 1
$checkStmt = $conn->prepare("
    SELECT a.id, a.username, a.email, a.is_store_owner, a.store_id, s.id as store_exists
    FROM agents a
    LEFT JOIN stores s ON s.owner_id = a.id
    WHERE a.is_store_owner = 1
");
$checkStmt->execute();
$result = $checkStmt->get_result();

$fixedCount = 0;
$checkedCount = 0;

while ($row = $result->fetch_assoc()) {
    $checkedCount++;
    $agentId = $row['id'];
    $username = $row['username'];
    $hasStore = !empty($row['store_exists']);
    
    echo "Checking: $username (ID: $agentId)\n";
    echo "  - is_store_owner: " . $row['is_store_owner'] . "\n";
    echo "  - store_id: " . ($row['store_id'] ?? 'NULL') . "\n";
    echo "  - Owns store: " . ($hasStore ? 'YES' : 'NO') . "\n";
    
    // If agent has is_store_owner = 1 but doesn't own a store, fix it
    if (!$hasStore) {
        // Check if they're a sub-agent (have a store_id pointing to another store)
        if ($row['store_id'] !== null) {
            // They're a sub-agent, not a store owner
            $fixStmt = $conn->prepare("UPDATE agents SET is_store_owner = 0 WHERE id = ?");
            $fixStmt->bind_param("i", $agentId);
            $fixStmt->execute();
            $fixStmt->close();
            
            echo "  ✓ FIXED: Set is_store_owner = 0 (sub-agent)\n";
            $fixedCount++;
        } else {
            // They have is_store_owner = 1 but no store - this is an error
            $fixStmt = $conn->prepare("UPDATE agents SET is_store_owner = 0 WHERE id = ?");
            $fixStmt->bind_param("i", $agentId);
            $fixStmt->execute();
            $fixStmt->close();
            
            echo "  ✓ FIXED: Set is_store_owner = 0 (no store owned)\n";
            $fixedCount++;
        }
    } else {
        echo "  ✓ OK: Legitimate store owner\n";
    }
    echo "\n";
}

$checkStmt->close();

echo "=== Summary ===\n";
echo "Checked: $checkedCount agents\n";
echo "Fixed: $fixedCount agents\n";
echo "\nDone!\n";
?>

