<?php
defined('ABSPATH') or die('Direct access not allowed');

/**
 * VollstartRD_RepairTypes — Repair type catalog.
 *
 * SRP: CRUD for repair types (categories of repairs).
 * Each type has an icon, estimated duration, default price,
 * favorite flag, and sort order.
 */
class VollstartRD_RepairTypes {

    private $MAIN;

    /** Available dashicon options for repair types. */
    private array $iconOptions = [
        'admin-tools', 'smartphone', 'laptop', 'desktop', 'tablet',
        'camera', 'car', 'bike', 'hammer', 'wrench',
        'shield', 'lightbulb', 'performance', 'clock', 'visibility',
        'star-filled', 'heart', 'flag', 'tag', 'category',
    ];

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

    /**
     * Create a new repair type.
     * @return int Repair type ID
     */
    public function create(array $data): int {
        return $this->MAIN->getDB()->insert('repair_types', [
            'name'                     => sanitize_text_field($data['name'] ?? ''),
            'description'              => sanitize_textarea_field($data['description'] ?? ''),
            'icon'                     => sanitize_text_field($data['icon'] ?? 'admin-tools'),
            'estimated_duration_hours' => (float) ($data['estimated_duration_hours'] ?? 0),
            'default_price'            => (float) ($data['default_price'] ?? 0),
            'is_favorite'              => !empty($data['is_favorite']) ? 1 : 0,
            'sort_order'               => (int) ($data['sort_order'] ?? 0),
            'active'                   => 1,
        ]);
    }

    /**
     * Update a repair type.
     */
    public function update(int $id, array $data): bool {
        $old = $this->getById($id);

        $fields = [];
        if (isset($data['name'])) $fields['name'] = sanitize_text_field($data['name']);
        if (isset($data['description'])) $fields['description'] = sanitize_textarea_field($data['description']);
        if (isset($data['icon'])) $fields['icon'] = sanitize_text_field($data['icon']);
        if (isset($data['estimated_duration_hours'])) $fields['estimated_duration_hours'] = (float) $data['estimated_duration_hours'];
        if (isset($data['default_price'])) $fields['default_price'] = (float) $data['default_price'];
        if (isset($data['is_favorite'])) $fields['is_favorite'] = !empty($data['is_favorite']) ? 1 : 0;
        if (isset($data['sort_order'])) $fields['sort_order'] = (int) $data['sort_order'];
        if (isset($data['active'])) $fields['active'] = !empty($data['active']) ? 1 : 0;

        if (empty($fields)) {
            return false;
        }

        $result = $this->MAIN->getDB()->update('repair_types', $fields, ['id' => $id]) !== false;

        if ($result && $old) {
            foreach ($fields as $key => $newVal) {
                $oldVal = $old[$key] ?? '';
                if ((string) $oldVal !== (string) $newVal) {
                    $this->logChange($id, $key, (string) $oldVal, (string) $newVal);
                }
            }
        }

        return $result;
    }

    private function logChange(int $typeId, string $field, string $oldValue, string $newValue): void {
        try {
            $this->MAIN->getDB()->insert('repair_type_history', [
                'repair_type_id' => $typeId,
                'field_name'     => $field,
                'old_value'      => $oldValue,
                'new_value'      => $newValue,
                'changed_by'     => get_current_user_id(),
                'changed_at'     => wp_date('Y-m-d H:i:s'),
            ]);
        } catch (\Exception $e) {}
    }

    public function getHistory(int $typeId): array {
        $db = $this->MAIN->getDB();
        global $wpdb;
        $tbl = $db->getTabelle('repair_type_history');
        return $db->getResults(
            "SELECT h.*, u.display_name AS changed_by_name FROM %i h LEFT JOIN {$wpdb->users} u ON h.changed_by = u.ID WHERE h.repair_type_id = %d ORDER BY h.changed_at DESC",
            $tbl, $typeId
        );
    }

    /**
     * Get a single repair type by ID.
     */
    public function getById(int $id): ?array {
        $db = $this->MAIN->getDB();
        $tbl = $db->getTabelle('repair_types');
        return $db->getRow("SELECT * FROM %i WHERE id = %d", $tbl, $id);
    }

    /**
     * Get all repair types (ordered by sort_order, then name).
     */
    public function getAll(bool $activeOnly = false): array {
        $db = $this->MAIN->getDB();
        $tbl = $db->getTabelle('repair_types');
        $where = $activeOnly ? "WHERE active = 1" : "";
        return $db->getResults("SELECT * FROM %i {$where} ORDER BY sort_order ASC, name ASC", $tbl);
    }

    /**
     * Get favorites (for quick-start buttons).
     */
    public function getFavorites(): array {
        $db = $this->MAIN->getDB();
        $tbl = $db->getTabelle('repair_types');
        return $db->getResults("SELECT * FROM %i WHERE is_favorite = 1 AND active = 1 ORDER BY sort_order ASC, name ASC", $tbl);
    }

    /**
     * Delete a repair type.
     */
    public function delete(int $id): bool {
        return $this->MAIN->getDB()->delete('repair_types', ['id' => $id]) !== false;
    }

    /**
     * Get available icon options.
     */
    public function getIconOptions(): array {
        return $this->iconOptions;
    }

    /**
     * Update sort order for multiple types at once.
     */
    public function updateSortOrder(array $order): void {
        foreach ($order as $index => $id) {
            $this->MAIN->getDB()->update('repair_types', ['sort_order' => $index], ['id' => (int) $id]);
        }
    }

    /**
     * Count all repair types.
     */
    public function count(): int {
        return $this->MAIN->getDB()->count('repair_types');
    }
}
