<?php
// 1. Enable error reporting to see any hidden issues
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 2. Include the connection (using __DIR__ for safety)
require_once __DIR__ . '/db_connect.php';

// Check if connection exists
if (!isset($conn)) {
    die("Error: The variable <code>\$conn</code> is not defined in db_connect.php");
}

// 3. Define the slug function
function create_slug($string) {
    $slug = strtolower($string);
    $slug = str_replace(' ', '-', $slug);
    $slug = preg_replace('/[^a-z0-9-]/', '', $slug);
    $slug = preg_replace('/-+/', '-', $slug);
    return trim($slug, '-');
}

echo "<h3>Starting Slug Update...</h3>";

// 4. Handle based on connection type (PDO vs MySQLi)
if ($conn instanceof PDO) {
    echo "<p>Connection Type: <strong>PDO</strong> detected.</p>";
    
    // Fetch all items
    try {
        // Try selecting from lowercase table first
        $stmt = $conn->query("SELECT id, title, slug FROM teledramas");
    } catch (PDOException $e) {
        // If failed, try Capitalized table name (Linux is case sensitive)
        try {
            $stmt = $conn->query("SELECT id, title, slug FROM Teledramas");
        } catch (PDOException $e2) {
            die("Error: Could not find table 'teledramas' or 'Teledramas'. <br>DB Error: " . $e->getMessage());
        }
    }

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($rows) > 0) {
        // Prepare the update statement once for efficiency
        $updateStmt = $conn->prepare("UPDATE teledramas SET slug = :slug WHERE id = :id");
        
        foreach ($rows as $row) {
            $id = $row['id'];
            $title = $row['title'];
            $currentSlug = $row['slug'];

            // Only update if slug is empty
            if (empty($currentSlug)) {
                $newSlug = create_slug($title);
                
                $updateStmt->execute([':slug' => $newSlug, ':id' => $id]);
                echo "Updated ID $id: $title -> <strong>$newSlug</strong><br>";
            } else {
                echo "Skipped ID $id: Already has slug ($currentSlug)<br>";
            }
        }
    } else {
        echo "Table found, but it has 0 rows of data. Did you import your data?";
    }

} elseif ($conn instanceof mysqli) {
    echo "<p>Connection Type: <strong>MySQLi</strong> detected.</p>";
    
    $result = mysqli_query($conn, "SELECT id, title, slug FROM teledramas");
    
    // Check if table exists/query worked
    if (!$result) {
        die("Query failed: " . mysqli_error($conn) . "<br>Check if table name is 'Teledramas' (Capitalized).");
    }

    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $id = $row['id'];
            $title = $row['title'];
            
            if (empty($row['slug'])) {
                $slug = create_slug($title);
                $updateSql = "UPDATE teledramas SET slug = '$slug' WHERE id = '$id'";
                mysqli_query($conn, $updateSql);
                echo "Updated ID $id: $title -> <strong>$slug</strong><br>";
            } else {
                echo "Skipped ID $id: Already has slug.<br>";
            }
        }
    } else {
        echo "Table is empty.";
    }

} else {
    die("Error: \$conn is not a valid PDO or MySQLi object.");
}
?>