<?php
/// file: seed.php

declare(strict_types=1);

$basePath = __DIR__;
if (is_file($basePath . '/vendor/autoload.php')) {
    require $basePath . '/vendor/autoload.php';
} else {
    spl_autoload_register(static function (string $class) use ($basePath): void {
        $prefix = 'App\\';
        if (! str_starts_with($class, $prefix)) {
            return;
        }
        $relative = str_replace('\\', '/', substr($class, strlen($prefix)));
        $file = $basePath . '/app/' . $relative . '.php';
        if (is_file($file)) {
            require $file;
        }
    });
}
require $basePath . '/app/Helpers/functions.php';

use App\Core\Database;
use App\Core\Env;
use App\Core\Config;

Env::load($basePath . '/.env');
Config::load($basePath . '/config');

$dbConfig = Config::get('database.connections.mysql', []);
if (! is_array($dbConfig) || ($dbConfig['database'] ?? '') === '') {
    fwrite(STDERR, "Set DB_NAME in .env\n");
    exit(1);
}

$pdo = Database::connect($dbConfig);

$c = (int) $pdo->query('SELECT COUNT(*) FROM projects')->fetchColumn();
if ($c >= 6) {
    echo "Seed skipped (projects already present).\n";
    exit(0);
}

$email = Env::get('ADMIN_EMAIL', 'admin@saneksa.studio') ?? 'admin@saneksa.studio';
$pass = Env::get('ADMIN_PASSWORD', 'password') ?? 'password';
$hash = password_hash($pass, PASSWORD_DEFAULT);

$st = $pdo->prepare('INSERT INTO admins (email, password_hash) VALUES (?, ?) ON DUPLICATE KEY UPDATE password_hash = VALUES(password_hash)');
$st->execute([$email, $hash]);

$projects = require $basePath . '/database/seeds/projects_data.php';
$insP = $pdo->prepare(
    'INSERT INTO projects (title, slug, client, year, sector, category, services, summary, challenge, creative_direction, process, outcomes, cover_type, cover_path, status, sort_order)
     VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
);
foreach ($projects as $i => $p) {
    $insP->execute([
        $p['title'],
        $p['slug'],
        $p['client'],
        $p['year'],
        $p['sector'],
        $p['category'],
        $p['services'],
        $p['summary'],
        $p['challenge'],
        $p['creative_direction'],
        $p['process'],
        $p['outcomes'],
        $p['cover_type'],
        $p['cover_path'],
        'published',
        $i,
    ]);
    $pid = (int) $pdo->lastInsertId();
    foreach ($p['gallery'] ?? [] as $g => $media) {
        $pdo->prepare('INSERT INTO project_media (project_id, type, path, caption, sort_order) VALUES (?,?,?,?,?)')
            ->execute([$pid, $media['type'], $media['path'], $media['caption'] ?? '', $g]);
    }
}

$services = require $basePath . '/database/seeds/services_data.php';
$insS = $pdo->prepare(
    'INSERT INTO services (title, slug, short_description, detail, process, deliverables, ideal_client, sort_order, status) VALUES (?,?,?,?,?,?,?,?,?)'
);
foreach ($services as $j => $s) {
    $insS->execute([
        $s['title'],
        $s['slug'],
        $s['short_description'],
        $s['detail'],
        $s['process'],
        $s['deliverables'],
        $s['ideal_client'],
        $j,
        'published',
    ]);
}

$posts = require $basePath . '/database/seeds/journal_data.php';
$insJ = $pdo->prepare(
    'INSERT INTO journal_posts (title, slug, excerpt, body, category, reading_time, cover_path, status, published_at) VALUES (?,?,?,?,?,?,?,?,?)'
);
foreach ($posts as $post) {
    $insJ->execute([
        $post['title'],
        $post['slug'],
        $post['excerpt'],
        $post['body'],
        $post['category'],
        $post['reading_time'],
        $post['cover_path'],
        'published',
        $post['published_at'],
    ]);
}

$careers = require $basePath . '/database/seeds/careers_data.php';
$insC = $pdo->prepare(
    'INSERT INTO careers (title, slug, location, type, description, sort_order, status) VALUES (?,?,?,?,?,?,?)'
);
foreach ($careers as $k => $job) {
    $insC->execute([
        $job['title'],
        $job['slug'],
        $job['location'],
        $job['type'],
        $job['description'],
        $k,
        'open',
    ]);
}

$defaults = require $basePath . '/database/seeds/settings_data.php';
foreach ($defaults['site_settings'] as $key => $val) {
    $pdo->prepare('INSERT INTO site_settings (setting_key, setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)')
        ->execute([$key, $val]);
}
foreach ($defaults['seo_meta'] as $row) {
    $pdo->prepare(
        'INSERT INTO seo_meta (page_key, title, description, og_title, og_description, og_image, robots) VALUES (?,?,?,?,?,?,?)
         ON DUPLICATE KEY UPDATE title=VALUES(title), description=VALUES(description), og_title=VALUES(og_title), og_description=VALUES(og_description), og_image=VALUES(og_image), robots=VALUES(robots)'
    )->execute([
        $row['page_key'],
        $row['title'],
        $row['description'],
        $row['og_title'],
        $row['og_description'],
        $row['og_image'],
        $row['robots'],
    ]);
}
foreach ($defaults['audio_settings'] as $ak => $av) {
    $pdo->prepare('INSERT INTO audio_settings (setting_key, setting_value) VALUES (?,?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)')
        ->execute([$ak, $av]);
}

echo "Seed complete. Admin: {$email}\n";
