<?php
// 1. Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 2. Include the connection
require_once __DIR__ . '/db_connect.php';

if (!isset($conn)) {
    die("Error: \$conn is not defined.");
}

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 Programmes Slug Update...</h3>";

if ($conn instanceof PDO) {
    echo "<p>Connection Type: <strong>PDO</strong></p>";
    
    // Select from programmes table
    $stmt = $conn->query("SELECT id, title, slug FROM programmes");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($rows) > 0) {
        $updateStmt = $conn->prepare("UPDATE programmes SET slug = :slug WHERE id = :id");
        
        foreach ($rows as $row) {
            $id = $row['id'];
            $title = $row['title'];
            $currentSlug = $row['slug'];

            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 'programmes' is empty.";
    }

} elseif ($conn instanceof mysqli) {
    echo "<p>Connection Type: <strong>MySQLi</strong></p>";
    $result = mysqli_query($conn, "SELECT id, title, slug FROM programmes");

    if ($result && 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);
                mysqli_query($conn, "UPDATE programmes SET slug = '$slug' WHERE id = '$id'");
                echo "Updated ID $id: $title -> <strong>$slug</strong><br>";
            } else {
                echo "Skipped ID $id: Already has slug.<br>";
            }
        }
    }
}
?>