<?php
/**
 * PostType Model
 * Manages custom post type definitions
 */
namespace Models;

class PostType
{
    private static $pdo;

    public static function setPdo($pdo)
    {
        self::$pdo = $pdo;
    }

    /**
     * Initialize tables
     */
    public static function createTables()
    {
        // Post Types table
        self::$pdo->exec("
            CREATE TABLE IF NOT EXISTS post_types (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT UNIQUE NOT NULL,
                label_singular TEXT NOT NULL,
                label_plural TEXT NOT NULL,
                icon TEXT DEFAULT 'fas fa-file',
                slug_prefix TEXT DEFAULT '',
                supports TEXT DEFAULT '[\"title\",\"content\",\"thumbnail\"]',
                fields TEXT DEFAULT '[]',
                has_archive INTEGER DEFAULT 1,
                menu_position INTEGER DEFAULT 50,
                is_system INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");

        // Custom Posts table
        self::$pdo->exec("
            CREATE TABLE IF NOT EXISTS custom_posts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                post_type TEXT NOT NULL,
                title TEXT NOT NULL,
                slug TEXT UNIQUE NOT NULL,
                content TEXT,
                excerpt TEXT,
                thumbnail TEXT,
                fields_data TEXT DEFAULT '{}',
                status TEXT DEFAULT 'draft',
                author_id INTEGER,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");

        // Taxonomies table - drop and recreate if schema mismatch
        try {
            // Check if table has the label column
            $result = self::$pdo->query("PRAGMA table_info(taxonomies)")->fetchAll(\PDO::FETCH_ASSOC);
            $hasLabel = false;
            foreach ($result as $col) {
                if ($col['name'] === 'label') {
                    $hasLabel = true;
                    break;
                }
            }

            if (!$hasLabel && !empty($result)) {
                // Drop and recreate
                self::$pdo->exec("DROP TABLE IF EXISTS taxonomies");
            }
        } catch (\Exception $e) {
            // Table doesn't exist, that's fine
        }

        self::$pdo->exec("
            CREATE TABLE IF NOT EXISTS taxonomies (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT UNIQUE NOT NULL,
                label TEXT NOT NULL,
                post_type TEXT NOT NULL,
                hierarchical INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");

        // Terms table
        self::$pdo->exec("
            CREATE TABLE IF NOT EXISTS terms (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                taxonomy TEXT NOT NULL,
                name TEXT NOT NULL,
                slug TEXT NOT NULL,
                description TEXT,
                parent_id INTEGER DEFAULT NULL,
                count INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        ");

        // Term relationships
        self::$pdo->exec("
            CREATE TABLE IF NOT EXISTS term_relationships (
                post_id INTEGER NOT NULL,
                term_id INTEGER NOT NULL,
                PRIMARY KEY (post_id, term_id)
            )
        ");
    }

    /**
     * Get all post types
     */
    public static function all()
    {
        $stmt = self::$pdo->query("SELECT * FROM post_types ORDER BY menu_position, label_plural");
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Get post type by name
     */
    public static function get($name)
    {
        $stmt = self::$pdo->prepare("SELECT * FROM post_types WHERE name = ?");
        $stmt->execute([$name]);
        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($result) {
            $result['supports'] = json_decode($result['supports'], true) ?: [];
            $result['fields'] = json_decode($result['fields'], true) ?: [];
        }
        return $result;
    }

    /**
     * Create post type
     */
    public static function create($data)
    {
        $stmt = self::$pdo->prepare("
            INSERT INTO post_types (name, label_singular, label_plural, icon, slug_prefix, supports, fields, has_archive, menu_position, is_system)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $data['name'],
            $data['label_singular'],
            $data['label_plural'],
            $data['icon'] ?? 'fas fa-file',
            $data['slug_prefix'] ?? $data['name'] . '/',
            is_array($data['supports'] ?? null) ? json_encode($data['supports']) : ($data['supports'] ?? '["title","content"]'),
            is_array($data['fields'] ?? null) ? json_encode($data['fields']) : ($data['fields'] ?? '[]'),
            $data['has_archive'] ?? 1,
            $data['menu_position'] ?? 50,
            $data['is_system'] ?? 0
        ]);

        return self::$pdo->lastInsertId();
    }

    /**
     * Update post type
     */
    public static function update($name, $data)
    {
        $fields = [];
        $values = [];

        $allowedFields = ['label_singular', 'label_plural', 'icon', 'slug_prefix', 'supports', 'fields', 'has_archive', 'menu_position'];

        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $fields[] = "$field = ?";
                $value = $data[$field];
                if (in_array($field, ['supports', 'fields']) && is_array($value)) {
                    $value = json_encode($value);
                }
                $values[] = $value;
            }
        }

        if (empty($fields))
            return false;

        $values[] = $name;
        $sql = "UPDATE post_types SET " . implode(', ', $fields) . ", updated_at = CURRENT_TIMESTAMP WHERE name = ?";

        $stmt = self::$pdo->prepare($sql);
        return $stmt->execute($values);
    }

    /**
     * Delete post type (non-system only)
     */
    public static function delete($name)
    {
        $stmt = self::$pdo->prepare("DELETE FROM post_types WHERE name = ? AND is_system = 0");
        return $stmt->execute([$name]);
    }

    /**
     * Seed default post types
     */
    public static function seedDefaults()
    {
        $defaults = [
            // Product - E-commerce
            [
                'name' => 'product',
                'label_singular' => 'Product',
                'label_plural' => 'Products',
                'icon' => 'fas fa-box',
                'slug_prefix' => 'products/',
                'supports' => ['title', 'content', 'thumbnail', 'excerpt'],
                'has_archive' => 1,
                'menu_position' => 10,
                'is_system' => 1,
                'fields' => [
                    ['name' => 'price', 'type' => 'number', 'label' => 'Price', 'required' => true],
                    ['name' => 'sale_price', 'type' => 'number', 'label' => 'Sale Price'],
                    ['name' => 'sku', 'type' => 'text', 'label' => 'SKU'],
                    ['name' => 'stock', 'type' => 'number', 'label' => 'Stock Quantity'],
                    [
                        'name' => 'gallery',
                        'type' => 'repeater',
                        'label' => 'Gallery',
                        'fields' => [
                            ['name' => 'image', 'type' => 'media', 'label' => 'Image']
                        ]
                    ]
                ]
            ],

            // Property - Real Estate
            [
                'name' => 'property',
                'label_singular' => 'Property',
                'label_plural' => 'Properties',
                'icon' => 'fas fa-home',
                'slug_prefix' => 'properties/',
                'supports' => ['title', 'content', 'thumbnail', 'excerpt'],
                'has_archive' => 1,
                'menu_position' => 20,
                'is_system' => 1,
                'fields' => [
                    ['name' => 'price', 'type' => 'number', 'label' => 'Price', 'required' => true],
                    ['name' => 'area_m2', 'type' => 'number', 'label' => 'Area (m²)'],
                    ['name' => 'rooms', 'type' => 'number', 'label' => 'Rooms'],
                    ['name' => 'bathrooms', 'type' => 'number', 'label' => 'Bathrooms'],
                    ['name' => 'location', 'type' => 'text', 'label' => 'Location'],
                    ['name' => 'address', 'type' => 'textarea', 'label' => 'Full Address'],
                    [
                        'name' => 'property_type',
                        'type' => 'select',
                        'label' => 'Type',
                        'options' => [
                            ['value' => 'apartment', 'label' => 'Apartment'],
                            ['value' => 'house', 'label' => 'House'],
                            ['value' => 'villa', 'label' => 'Villa'],
                            ['value' => 'land', 'label' => 'Land'],
                            ['value' => 'commercial', 'label' => 'Commercial']
                        ]
                    ],
                    [
                        'name' => 'status',
                        'type' => 'select',
                        'label' => 'Status',
                        'options' => [
                            ['value' => 'for_sale', 'label' => 'For Sale'],
                            ['value' => 'for_rent', 'label' => 'For Rent'],
                            ['value' => 'sold', 'label' => 'Sold']
                        ]
                    ],
                    ['name' => 'features', 'type' => 'textarea', 'label' => 'Features (one per line)'],
                    [
                        'name' => 'gallery',
                        'type' => 'repeater',
                        'label' => 'Gallery',
                        'fields' => [
                            ['name' => 'image', 'type' => 'media', 'label' => 'Image']
                        ]
                    ]
                ]
            ],

            // Portfolio
            [
                'name' => 'portfolio',
                'label_singular' => 'Project',
                'label_plural' => 'Portfolio',
                'icon' => 'fas fa-briefcase',
                'slug_prefix' => 'portfolio/',
                'supports' => ['title', 'content', 'thumbnail', 'excerpt'],
                'has_archive' => 1,
                'menu_position' => 30,
                'is_system' => 1,
                'fields' => [
                    ['name' => 'client', 'type' => 'text', 'label' => 'Client'],
                    ['name' => 'project_date', 'type' => 'text', 'label' => 'Date', 'placeholder' => '2024'],
                    ['name' => 'project_url', 'type' => 'url', 'label' => 'Project URL'],
                    ['name' => 'technologies', 'type' => 'text', 'label' => 'Technologies Used'],
                    [
                        'name' => 'gallery',
                        'type' => 'repeater',
                        'label' => 'Gallery',
                        'fields' => [
                            ['name' => 'image', 'type' => 'media', 'label' => 'Image'],
                            ['name' => 'caption', 'type' => 'text', 'label' => 'Caption']
                        ]
                    ]
                ]
            ],

            // Event
            [
                'name' => 'event',
                'label_singular' => 'Event',
                'label_plural' => 'Events',
                'icon' => 'fas fa-calendar-alt',
                'slug_prefix' => 'events/',
                'supports' => ['title', 'content', 'thumbnail', 'excerpt'],
                'has_archive' => 1,
                'menu_position' => 40,
                'is_system' => 1,
                'fields' => [
                    ['name' => 'event_date', 'type' => 'text', 'label' => 'Date', 'placeholder' => '2024-12-31'],
                    ['name' => 'event_time', 'type' => 'text', 'label' => 'Time', 'placeholder' => '19:00'],
                    ['name' => 'end_date', 'type' => 'text', 'label' => 'End Date'],
                    ['name' => 'location', 'type' => 'text', 'label' => 'Location'],
                    ['name' => 'address', 'type' => 'textarea', 'label' => 'Full Address'],
                    ['name' => 'ticket_price', 'type' => 'number', 'label' => 'Ticket Price'],
                    ['name' => 'capacity', 'type' => 'number', 'label' => 'Capacity'],
                    ['name' => 'registration_url', 'type' => 'url', 'label' => 'Registration URL']
                ]
            ],

            // Team Member
            [
                'name' => 'team_member',
                'label_singular' => 'Team Member',
                'label_plural' => 'Team',
                'icon' => 'fas fa-user-tie',
                'slug_prefix' => 'team/',
                'supports' => ['title', 'content', 'thumbnail'],
                'has_archive' => 1,
                'menu_position' => 50,
                'is_system' => 1,
                'fields' => [
                    ['name' => 'role', 'type' => 'text', 'label' => 'Role/Position'],
                    ['name' => 'email', 'type' => 'email', 'label' => 'Email'],
                    ['name' => 'phone', 'type' => 'text', 'label' => 'Phone'],
                    ['name' => 'bio', 'type' => 'textarea', 'label' => 'Short Bio'],
                    ['name' => 'linkedin', 'type' => 'url', 'label' => 'LinkedIn'],
                    ['name' => 'twitter', 'type' => 'url', 'label' => 'Twitter'],
                    ['name' => 'order', 'type' => 'number', 'label' => 'Display Order']
                ]
            ]
        ];

        foreach ($defaults as $pt) {
            // Check if exists
            $existing = self::get($pt['name']);
            if (!$existing) {
                self::create($pt);
            }
        }
    }

    /**
     * Get post count for a post type
     */
    public static function getPostCount($postType)
    {
        $stmt = self::$pdo->prepare("SELECT COUNT(*) FROM custom_posts WHERE post_type = ?");
        $stmt->execute([$postType]);
        return $stmt->fetchColumn();
    }
}
