<?php
/**
 * Fix unit name from "Pcss" to "Pcs" in products table
 * Access this file via browser: http://your-domain/public/fix_unit_pcss_to_pcs.php
 */

// Load environment
$envFile = __DIR__ . '/../.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (str_starts_with(trim($line), '#')) continue;
        if (str_contains($line, '=')) {
            list($key, $value) = explode('=', $line, 2);
            $key = trim($key);
            $value = trim($value);
            if (str_starts_with($value, '"') && str_ends_with($value, '"')) {
                $value = substr($value, 1, -1);
            } elseif (str_starts_with($value, "'") && str_ends_with($value, "'")) {
                $value = substr($value, 1, -1);
            }
            putenv("$key=$value");
            $_ENV[$key] = $value;
        }
    }
}

// Database config
$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbName = getenv('DB_NAME') ?: 'tellerpro';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASS') ?: '';

try {
    $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // First, let's check what units exist
    $checkStmt = $pdo->query("SELECT DISTINCT unit FROM products WHERE unit LIKE '%Pcs%' OR unit LIKE '%pcs%'");
    $existingUnits = $checkStmt->fetchAll(PDO::FETCH_COLUMN);
    
    $message = "Found units matching 'Pcs': " . implode(', ', $existingUnits) . "<br><br>";
    
    // Update products where unit is "Pcss" (case-insensitive)
    $stmt = $pdo->prepare("UPDATE products SET unit = 'Pcs' WHERE LOWER(unit) = 'pcss'");
    $stmt->execute();
    $affectedRows = $stmt->rowCount();
    
    // Also update other variations
    $stmt2 = $pdo->prepare("UPDATE products SET unit = 'Pcs' WHERE unit LIKE 'Pc%'");
    $stmt2->execute();
    $affectedRows2 = $stmt2->rowCount();
    
    $totalAffected = $affectedRows + $affectedRows2;
    
    $message .= "Fixed $totalAffected product(s) - changed unit variations to 'Pcs'";
    
    if ($totalAffected > 0) {
        $message .= "<br><strong>✓ Successfully updated product units</strong>";
    } else {
        $message .= "<br><strong>✓ No products found with unit variations (already fixed or doesn't exist)</strong>";
    }
    
} catch (Exception $e) {
    $message = "Error: " . $e->getMessage();
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Fix Unit Pcss to Pcs</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            margin-top: 0;
        }
        .message {
            padding: 15px;
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            margin: 20px 0;
        }
        .error {
            background: #ffebee;
            border-left-color: #f44336;
        }
        a {
            display: inline-block;
            margin-top: 20px;
            color: #1976d2;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Fix Unit Pcss to Pcs</h1>
        <div class="message <?php echo isset($e) ? 'error' : ''; ?>">
            <?php echo $message; ?>
        </div>
        <a href="<?php echo APP_URL; ?>/products">Go to Products Page</a>
    </div>
</body>
</html>
