<?php
/**
 * Quick Fix: Update all store owners to have role = 'store_owner'
 * Run this immediately to fix cobbystore and other store owners
 * 
 * This script:
 * 1. Checks database structure of role field
 * 2. Ensures 'store_owner' is a valid value
 * 3. Updates all store owners to role = 'store_owner'
 */

require_once 'config.php';

echo "=== Quick Fix: Store Owners Role Update ===\n\n";

// Step 1: Check and fix database structure
echo "Step 1: Checking database structure...\n";
echo str_repeat("-", 60) . "\n";

$columnInfoStmt = $conn->prepare("SHOW COLUMNS FROM agents WHERE Field = 'role'");
$columnInfoStmt->execute();
$columnResult = $columnInfoStmt->get_result();
$columnInfo = $columnResult->fetch_assoc();
$columnInfoStmt->close();

if ($columnInfo) {
    echo "Role field type: " . $columnInfo['Type'] . "\n";
    
    // If it's an ENUM, check if 'store_owner' is included
    if (stripos($columnInfo['Type'], 'enum') !== false) {
        if (stripos($columnInfo['Type'], 'store_owner') === false) {
            echo "⚠️  'store_owner' not in ENUM - adding it...\n";
            
            // Extract current enum values
            preg_match("/enum\((.+)\)/i", $columnInfo['Type'], $matches);
            if (isset($matches[1])) {
                $enumValues = $matches[1];
                $alterSql = "ALTER TABLE agents MODIFY COLUMN role ENUM($enumValues, 'store_owner')";
                
                if (mysqli_query($conn, $alterSql)) {
                    echo "✓ Added 'store_owner' to ENUM\n";
                } else {
                    echo "⚠️  ENUM update failed, trying VARCHAR approach...\n";
                    // Change to VARCHAR if ENUM fails
                    $alterSql2 = "ALTER TABLE agents MODIFY COLUMN role VARCHAR(50) DEFAULT 'agent'";
                    if (mysqli_query($conn, $alterSql2)) {
                        echo "✓ Changed to VARCHAR(50)\n";
                    }
                }
            }
        } else {
            echo "✓ 'store_owner' already supported\n";
        }
    } else {
        echo "✓ Field is VARCHAR/TEXT - supports 'store_owner'\n";
    }
} else {
    echo "❌ ERROR: 'role' column not found!\n";
    exit(1);
}

echo "\n";

// Step 2: Find and update all store owners
echo "Step 2: Finding and updating store owners...\n";
echo str_repeat("-", 60) . "\n";

// 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, s.store_name
    FROM agents a
    INNER JOIN stores s ON s.owner_id = a.id
    ORDER BY a.id
");
$storeOwnersStmt->execute();
$result = $storeOwnersStmt->get_result();

$fixedCount = 0;
$totalCount = 0;

while ($row = $result->fetch_assoc()) {
    $totalCount++;
    $agentId = $row['id'];
    $username = $row['username'];
    $currentRole = $row['role'];
    $storeId = $row['store_id_owned'];
    
    echo "User: $username (ID: $agentId, Store: {$row['store_name']})\n";
    echo "  Current: role='$currentRole', is_store_owner={$row['is_store_owner']}, store_id={$row['store_id']}\n";
    
    // Update to store_owner role
    $updateStmt = $conn->prepare("
        UPDATE agents 
        SET role = 'store_owner', is_store_owner = 1, store_id = ? 
        WHERE id = ?
    ");
    $updateStmt->bind_param("ii", $storeId, $agentId);
    
    if ($updateStmt->execute()) {
        // Verify the update
        $verifyStmt = $conn->prepare("SELECT role, is_store_owner, store_id FROM agents WHERE id = ?");
        $verifyStmt->bind_param("i", $agentId);
        $verifyStmt->execute();
        $verifyResult = $verifyStmt->get_result();
        $verifyData = $verifyResult->fetch_assoc();
        $verifyStmt->close();
        
        if ($verifyData['role'] === 'store_owner' && $verifyData['is_store_owner'] == 1) {
            echo "  ✓ FIXED: role='store_owner', is_store_owner=1, store_id=$storeId\n\n";
            $fixedCount++;
        } else {
            echo "  ⚠️  Update executed but verification failed\n";
            echo "     role='{$verifyData['role']}', is_store_owner={$verifyData['is_store_owner']}\n\n";
        }
    } else {
        echo "  ✗ FAILED: " . $updateStmt->error . "\n\n";
    }
    $updateStmt->close();
}

$storeOwnersStmt->close();

// Step 3: Final verification
echo "Step 3: Final verification...\n";
echo str_repeat("-", 60) . "\n";

$verifyAllStmt = $conn->prepare("
    SELECT a.id, a.username, a.role, a.is_store_owner, s.id as store_exists
    FROM agents a
    INNER JOIN stores s ON s.owner_id = a.id
");
$verifyAllStmt->execute();
$verifyAllResult = $verifyAllStmt->get_result();

$allCorrect = true;
while ($verifyRow = $verifyAllResult->fetch_assoc()) {
    if ($verifyRow['role'] !== 'store_owner' || $verifyRow['is_store_owner'] != 1) {
        echo "❌ Still incorrect: {$verifyRow['username']} - role='{$verifyRow['role']}', is_store_owner={$verifyRow['is_store_owner']}\n";
        $allCorrect = false;
    }
}

if ($allCorrect) {
    echo "✓ All store owners verified correctly!\n\n";
} else {
    echo "⚠️  Some issues remain - check above\n\n";
}

$verifyAllStmt->close();

echo "=== Summary ===\n";
echo "Store Owners Found: $totalCount\n";
echo "Store Owners Fixed: $fixedCount\n";
echo "\nDone! Store owners (including cobbystore) can now login correctly.\n";
echo "They will be redirected to the store dashboard.\n";
?>

