<?php
/**
 * One-time content seeding.
 *
 * On theme activation (and as a safety net, first admin load) the original
 * 6 services + 6 projects become real, editable posts — their images pulled
 * into the media library — and the contact settings are pre-filled.
 *
 * Guarded by the `iliya_seeded` option so it runs exactly once, ever.
 *
 * @package Iliya
 */

if (! defined('ABSPATH')) {
    exit;
}

add_action('after_switch_theme', 'iliya_seed_content');
add_action('admin_init', 'iliya_seed_content');

function iliya_seed_content() {
    if (get_option('iliya_seeded')) {
        return;
    }
    // Claim the flag up front so the two hooks can never double-seed.
    update_option('iliya_seeded', 1);

    iliya_seed_settings();
    iliya_seed_services();
    iliya_seed_projects();
}

/** Pre-fill the site settings option (only if absent). */
function iliya_seed_settings() {
    if (false === get_option('iliya_settings', false)) {
        add_option('iliya_settings', iliya_settings_defaults());
    }
}

/**
 * Import a theme asset image into the media library.
 *
 * @param string $filename  e.g. 'yard-rebar.webp' (relative to assets/images/).
 * @param int    $parent_id Attach to this post.
 * @return int Attachment ID, or 0 on failure.
 */
function iliya_import_asset_image($filename, $parent_id = 0) {
    $path = get_template_directory() . '/assets/images/' . $filename;
    if (! file_exists($path)) {
        return 0;
    }

    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $upload = wp_upload_bits(basename($path), null, file_get_contents($path));
    if (! empty($upload['error'])) {
        return 0;
    }

    $filetype  = wp_check_filetype($upload['file'], null);
    $attach_id = wp_insert_attachment([
        'post_mime_type' => $filetype['type'] ?: 'image/webp',
        'post_title'     => sanitize_file_name(pathinfo($upload['file'], PATHINFO_FILENAME)),
        'post_content'   => '',
        'post_status'    => 'inherit',
    ], $upload['file'], $parent_id);

    if (is_wp_error($attach_id) || ! $attach_id) {
        return 0;
    }

    wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $upload['file']));
    return $attach_id;
}

/** Seed the 6 original services. */
function iliya_seed_services() {
    $services = [
        ['icon' => 'recycle',   'img' => 'yard-rebar',     'title' => 'خرید و فروش ضایعات و فلزات',  'desc' => 'ضایعات آهن، آلومینیوم، برنز، استیل، فولاد و ضایعات غیرفلزی با بهترین قیمت روز.'],
        ['icon' => 'crane',     'img' => 'infra-tunnel',   'title' => 'پیمانکاری عمرانی و راه‌سازی', 'desc' => 'طراحی، محاسبه و اجرای راه، باند، سد، تونل، راه‌آهن، مترو و ابنیه سبک و سنگین.'],
        ['icon' => 'bolt',      'img' => 'weld-torch',     'title' => 'تأسیسات برقی و مکانیکی',      'desc' => 'تأسیسات ساختمان و کارخانجات، گازرسانی، آب و فاضلاب، پست‌های توزیع و نیروگاه.'],
        ['icon' => 'structure', 'img' => 'weld-bead',      'title' => 'سازه‌های فلزی و جوشکاری',     'desc' => 'ساخت انواع سازه فلزی، سندبلاست، جوشکاری تخصصی و مرمت و بازسازی ابنیه.'],
        ['icon' => 'leaf',      'img' => 'infra-overpass', 'title' => 'خدمات شهری و فضای سبز',       'desc' => 'محوطه‌سازی، فضای سبز، مبلمان شهری، نظافت معابر و اجرای طرح‌های بازیافت.'],
        ['icon' => 'globe',     'img' => 'yard-aerial',    'title' => 'بازرگانی، صادرات و واردات',   'desc' => 'صادرات و واردات کالاهای مجاز، ترخیص از گمرک و شرکت در مناقصات و مزایدات.'],
    ];
    foreach ($services as $i => $s) {
        $id = wp_insert_post([
            'post_type'    => 'iliya_service',
            'post_status'  => 'publish',
            'post_title'   => $s['title'],
            'post_content' => $s['desc'],
            'menu_order'   => $i,
        ]);
        if (! $id || is_wp_error($id)) {
            continue;
        }
        update_post_meta($id, '_iliya_icon', $s['icon']);
        $att = iliya_import_asset_image($s['img'] . '.webp', $id);
        if ($att) {
            set_post_thumbnail($id, $att);
        }
    }
}

/** Seed the 6 original projects. */
function iliya_seed_projects() {
    $projects = [
        ['img' => 'infra-tunnel',   'tag' => 'زیرساخت',   'title' => 'تونل و راه‌سازی',      'meta' => 'عمران سنگین'],
        ['img' => 'infra-bridge',   'tag' => 'سازه کلان', 'title' => 'پل و سازه‌های بزرگ',   'meta' => 'بتنی / فلزی'],
        ['img' => 'infra-overpass', 'tag' => 'ابنیه',     'title' => 'بزرگراه و ابنیه',      'meta' => 'راه و باند'],
        ['img' => 'yard-rebar',     'tag' => 'بازرگانی',  'title' => 'تأمین فولاد و ضایعات', 'meta' => 'فلزات'],
        ['img' => 'weld-bead',      'tag' => 'ساخت',      'title' => 'سازه فلزی و جوشکاری',  'meta' => 'کارگاهی'],
        ['img' => 'hero-skyline',   'tag' => 'صنعتی',     'title' => 'پروژه‌های صنعتی',      'meta' => 'کارخانه'],
    ];
    foreach ($projects as $i => $p) {
        $id = wp_insert_post([
            'post_type'   => 'iliya_project',
            'post_status' => 'publish',
            'post_title'  => $p['title'],
            'menu_order'  => $i,
        ]);
        if (! $id || is_wp_error($id)) {
            continue;
        }
        update_post_meta($id, '_iliya_tag', $p['tag']);
        update_post_meta($id, '_iliya_meta', $p['meta']);
        $att = iliya_import_asset_image($p['img'] . '.webp', $id);
        if ($att) {
            set_post_thumbnail($id, $att);
        }
    }
}
