<?php
/**
 * Migration Script: Multi-Layer Role System
 * 
 * This script migrates existing store owners from role='agent' to role='store_owner'
 * and ensures complete separation between store owners and agents
 * 
 * Run this ONCE to migrate existing data
 */

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

echo "=== Migrating to Multi-Layer Role System ===\n\n";

$storeManager = new StoreManager($conn);

// Find all users who own stores
$storeOwnersStmt = $conn->prepare("
    SELECT DISTINCT a.id, a.username, a.email, a.role, a.is_store_owner, a.store_id, s.id as store_id_owned
    FROM agents a
    INNER JOIN stores s ON s.owner_id = a.id
    ORDER BY a.id
");
$storeOwnersStmt->execute();
$result = $storeOwnersStmt->get_result();

$migratedCount = 0;
$checkedCount = 0;

echo "Migrating Store Owners:\n";
echo str_repeat("-", 60) . "\n";

while ($row = $result->fetch_assoc()) {
    $checkedCount++;
    $agentId = $row['id'];
    $username = $row['username'];
    $currentRole = $row['role'];
    $currentIsStoreOwner = $row['is_store_owner'];
    $storeId = $row['store_id_owned'];
    
    echo "User: $username (ID: $agentId)\n";
    echo "  Current: role='$currentRole', is_store_owner=$currentIsStoreOwner, store_id={$row['store_id']}\n";
    
    // Update to store_owner role if not already
    if ($currentRole !== 'store_owner' || $currentIsStoreOwner != 1 || $row['store_id'] != $storeId) {
        $updateStmt = $conn->prepare("
            UPDATE agents 
            SET role = 'store_owner', is_store_owner = 1, store_id = ? 
            WHERE id = ?
        ");
        $updateStmt->bind_param("ii", $storeId, $agentId);
        $updateStmt->execute();
        $updateStmt->close();
        
        echo "  ✓ MIGRATED: role='store_owner', is_store_owner=1, store_id=$storeId\n";
        $migratedCount++;
    } else {
        echo "  ✓ Already correct\n";
    }
    echo "\n";
}

$storeOwnersStmt->close();

// Now fix any agents that have incorrect flags
echo "\nFixing Agents:\n";
echo str_repeat("-", 60) . "\n";

$agentsStmt = $conn->prepare("
    SELECT a.id, a.username, a.role, a.is_store_owner, a.store_id, s.id as owns_store
    FROM agents a
    LEFT JOIN stores s ON s.owner_id = a.id
    WHERE a.role = 'agent' OR a.is_store_owner = 0
    ORDER BY a.id
");
$agentsStmt->execute();
$agentsResult = $agentsStmt->get_result();

$fixedAgents = 0;
$checkedAgents = 0;

while ($row = $agentsResult->fetch_assoc()) {
    $checkedAgents++;
    $agentId = $row['id'];
    $username = $row['username'];
    
    // If agent owns a store, they should be store_owner
    if (!empty($row['owns_store'])) {
        echo "Agent $username (ID: $agentId) owns a store - fixing...\n";
        $fixStmt = $conn->prepare("
            UPDATE agents 
            SET role = 'store_owner', is_store_owner = 1, store_id = ? 
            WHERE id = ?
        ");
        $fixStmt->bind_param("ii", $row['owns_store'], $agentId);
        $fixStmt->execute();
        $fixStmt->close();
        echo "  ✓ Fixed to store_owner\n";
        $fixedAgents++;
    } 
    // If agent has is_store_owner = 1 but doesn't own a store, fix it
    elseif ($row['is_store_owner'] == 1 && empty($row['owns_store'])) {
        echo "Agent $username (ID: $agentId) has is_store_owner=1 but no store - fixing...\n";
        $fixStmt = $conn->prepare("
            UPDATE agents 
            SET is_store_owner = 0, role = 'agent' 
            WHERE id = ?
        ");
        $fixStmt->bind_param("i", $agentId);
        $fixStmt->execute();
        $fixStmt->close();
        echo "  ✓ Fixed to agent\n";
        $fixedAgents++;
    }
    // Ensure role is 'agent' for non-store-owners
    elseif ($row['role'] !== 'agent' && empty($row['owns_store'])) {
        echo "Agent $username (ID: $agentId) has wrong role - fixing...\n";
        $fixStmt = $conn->prepare("
            UPDATE agents 
            SET role = 'agent', is_store_owner = 0 
            WHERE id = ?
        ");
        $fixStmt->bind_param("i", $agentId);
        $fixStmt->execute();
        $fixStmt->close();
        echo "  ✓ Fixed role to agent\n";
        $fixedAgents++;
    }
}

$agentsStmt->close();

echo "\n=== Summary ===\n";
echo "Store Owners Checked: $checkedCount\n";
echo "Store Owners Migrated: $migratedCount\n";
echo "Agents Checked: $checkedAgents\n";
echo "Agents Fixed: $fixedAgents\n";
echo "\nMigration Complete!\n";
echo "\nMulti-Layer Security Now Active:\n";
echo "  - Store Owners: role='store_owner', is_store_owner=1, owns store\n";
echo "  - Agents: role='agent', is_store_owner=0, belongs to store\n";
?>

