<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$pdo = require __DIR__ . '/config/pdo.php';

try {
    // 1. Create Table
    $sql = "CREATE TABLE IF NOT EXISTS sliders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        image VARCHAR(255) NOT NULL,
        title VARCHAR(100) DEFAULT NULL,
        description TEXT DEFAULT NULL,
        link_url VARCHAR(255) DEFAULT NULL,
        is_active TINYINT(1) DEFAULT 1,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";

    $pdo->exec($sql);
    echo "Table 'sliders' check/creation: OK.\n";

    // 2. Check if empty
    $count = $pdo->query("SELECT COUNT(*) FROM sliders")->fetchColumn();
    
    if ($count == 0) {
        // 3. Seed Data
        $sliders = [
            ['banner1.png', 'Oleh-oleh Premium', 'Koleksi lengkap untuk menyempurnakan ibadah Anda.', 'public/index.php?page=products'],
            ['banner2.png', 'Kurma Ajwa & Zamzam', 'Langsung dari tanah suci, dijamin keasliannya.', 'public/index.php?page=products&q=kurma'],
            ['banner3.png', 'Paket Hadiah Spesial', 'Cocok untuk kado kerabat dan keluarga.', 'public/index.php?page=products']
        ];

        foreach ($sliders as $index => $s) {
            // Check if image exists in uploads, if not copy from assets
            $source = __DIR__ . '/assets/img/' . $s[0];
            $dest = __DIR__ . '/uploads/' . $s[0];
            
            if (!is_dir(__DIR__ . '/uploads')) {
                mkdir(__DIR__ . '/uploads');
            }

            if (file_exists($source)) {
                if (!file_exists($dest)) {
                    copy($source, $dest);
                    echo "Copied {$s[0]} to uploads.\n";
                }
            } else {
                echo "Warning: Source image {$s[0]} not found in assets/img.\n";
            }
            
            $sort = $index;
            // Check if already exists to avoid dupes in case of partial runs
            $stmt = $pdo->prepare("SELECT id FROM sliders WHERE image = ?");
            $stmt->execute([$s[0]]);
            if (!$stmt->fetch()) {
                $sqlInsert = "INSERT INTO sliders (image, title, description, link_url, sort_order) VALUES (?, ?, ?, ?, ?)";
                $pdo->prepare($sqlInsert)->execute([$s[0], $s[1], $s[2], $s[3], $sort]);
                echo "Inserted slider: {$s[1]}\n";
            }
        }
    } else {
        echo "Table already has data. Skipping seed.\n";
    }

    echo "Repair completed successfully.";

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
