<?php
/**
 * ===========================================
 * FLOWBOT DCI - FEED DATA MODEL
 * ===========================================
 * Handles feed_data table operations
 */

declare(strict_types=1);

namespace FlowbotDCI\Models;

use FlowbotDCI\Core\Database;

class FeedData
{
    private Database $db;
    private string $table = 'feed_data';

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    /**
     * Get or create feed data by domain
     */
    public function getOrCreate(string $websiteBase, string $websiteFeed): array
    {
        // Try to find existing
        $existing = $this->findByDomain($websiteBase);
        if ($existing) {
            return $existing;
        }

        // Create new
        $id = $this->insert([
            'website_base'       => $websiteBase,
            'website_feed'       => $websiteFeed,
            'main_category_id'   => 0,
            'subcategory_id'     => null,
            'subcategory_name'   => null,
            'subsubcategory_id'  => null,
            'subsubcategory_name' => null,
        ]);

        return [
            'id'               => $id,
            'website_base'     => $websiteBase,
            'website_feed'     => $websiteFeed,
            'main_category_id' => 0,
        ];
    }

    /**
     * Find by domain
     */
    public function findByDomain(string $domain): ?array
    {
        $stmt = $this->db->query(
            "SELECT * FROM {$this->table} WHERE website_base LIKE ? LIMIT 1",
            ["%$domain%"]
        );
        $result = $stmt->fetch();
        return $result ?: null;
    }

    /**
     * Find by ID
     */
    public function find(int $id): ?array
    {
        $stmt = $this->db->query(
            "SELECT * FROM {$this->table} WHERE id = ?",
            [$id]
        );
        $result = $stmt->fetch();
        return $result ?: null;
    }

    /**
     * Insert new feed data
     */
    public function insert(array $data): int
    {
        $sql = "INSERT INTO {$this->table} (
            website_base, website_feed, main_category_id,
            subcategory_id, subcategory_name,
            subsubcategory_id, subsubcategory_name
        ) VALUES (?, ?, ?, ?, ?, ?, ?)";

        $this->db->query($sql, [
            $data['website_base'],
            $data['website_feed'],
            $data['main_category_id'] ?? 0,
            $data['subcategory_id'] ?? null,
            $data['subcategory_name'] ?? null,
            $data['subsubcategory_id'] ?? null,
            $data['subsubcategory_name'] ?? null,
        ]);

        return (int)$this->db->lastInsertId();
    }

    /**
     * Update feed data
     */
    public function update(int $id, array $data): bool
    {
        $fields = [];
        $values = [];

        foreach ($data as $key => $value) {
            $fields[] = "$key = ?";
            $values[] = $value;
        }

        $values[] = $id;
        $sql = "UPDATE {$this->table} SET " . implode(', ', $fields) . " WHERE id = ?";

        $this->db->query($sql, $values);
        return true;
    }

    /**
     * Delete feed data
     */
    public function delete(int $id): bool
    {
        $this->db->query("DELETE FROM {$this->table} WHERE id = ?", [$id]);
        return true;
    }

    /**
     * Get all feed data
     */
    public function getAll(int $limit = 100): array
    {
        $stmt = $this->db->query(
            "SELECT * FROM {$this->table} ORDER BY id DESC LIMIT ?",
            [$limit]
        );
        return $stmt->fetchAll();
    }

    /**
     * Count total entries
     */
    public function count(): int
    {
        $stmt = $this->db->query("SELECT COUNT(*) FROM {$this->table}");
        return (int)$stmt->fetchColumn();
    }
}
