<?php

namespace AIPT\Api\AutomationJobs;

/**
 * Draft Content Manager
 * 
 * Handles CRUD operations for draft content generated by automation jobs
 * 
 * @since 2.3.0
 */
class DraftContentManager {
    
    /**
     * WordPress database instance
     * @var \wpdb
     */
    private $wpdb;
    
    /**
     * Draft content table name
     * @var string
     */
    private $draft_table;
    
    /**
     * Constructor
     */
    public function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->draft_table = $wpdb->prefix . 'aipt_draft_content';
    }
    
    /**
     * Save draft content
     * 
     * @param int $job_id Job ID
     * @param int $product_id Product ID
     * @param string $content_type Content type (title, description, short_description, tags)
     * @param string $generated_content Generated content
     * @param string|null $original_content Original content
     * @return int|false Draft content ID or false on failure
     */
    public function saveDraftContent($job_id, $product_id, $content_type, $generated_content, $original_content = null) {
        try {

            if ($original_content === null) {
                $original_content = $this->getOriginalContent($product_id, $content_type);
            }
            
            $data = [
                'job_id' => $job_id,
                'product_id' => $product_id,
                'content_type' => $content_type,
                'original_content' => $original_content,
                'generated_content' => $generated_content,
                'status' => 'pending',
                'created_by' => get_current_user_id(),
                'created_at' => current_time('mysql')
            ];
            

            $existing_id = $this->wpdb->get_var($this->wpdb->prepare(
                "SELECT id FROM {$this->draft_table}
                WHERE job_id = %d AND product_id = %d AND content_type = %s",
                $job_id, $product_id, $content_type
            ));

            
            if ($existing_id) {

                $result = $this->wpdb->update(
                    $this->draft_table,
                    [
                        'generated_content' => $generated_content,
                        'original_content' => $original_content,
                        'status' => 'pending',
                        'updated_at' => current_time('mysql')
                    ],
                    ['id' => $existing_id],
                    ['%s', '%s', '%s', '%s'],
                    ['%d']
                );
                
                return $result !== false ? $existing_id : false;
            } else {

                $result = $this->wpdb->insert(
                    $this->draft_table,
                    $data,
                    ['%d', '%d', '%s', '%s', '%s', '%s', '%d', '%s']
                );
                
                return $result !== false ? $this->wpdb->insert_id : false;
            }
            
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Get original content from product
     * 
     * @param int $product_id Product ID
     * @param string $content_type Content type
     * @return string Original content
     */
    private function getOriginalContent($product_id, $content_type) {
        $product = wc_get_product($product_id);
        if (!$product) {
            return '';
        }
        
        switch ($content_type) {
            case 'title':
                return $product->get_name();
            case 'description':
                return $product->get_description();
            case 'short_description':
                return $product->get_short_description();
            case 'tags':
                $tags = wp_get_post_terms($product_id, 'product_tag', ['fields' => 'names']);
                return is_array($tags) ? implode(', ', $tags) : '';
            default:
                return '';
        }
    }
    
    /**
     * Get draft content by filters
     * 
     * @param array $filters Filters (job_id, product_id, status, content_type)
     * @param int $limit Limit
     * @param int $offset Offset
     * @return array Draft content items
     */
    public function getDraftContent($filters = [], $limit = 50, $offset = 0) {
        $where_conditions = ['1=1'];
        $query_params = [];
        
        if (!empty($filters['job_id'])) {
            $where_conditions[] = 'dc.job_id = %d';
            $query_params[] = $filters['job_id'];
        }

        if (!empty($filters['product_id'])) {
            $where_conditions[] = 'dc.product_id = %d';
            $query_params[] = $filters['product_id'];
        }
        
        if (!empty($filters['status'])) {
            $where_conditions[] = 'dc.status = %s';
            $query_params[] = $filters['status'];
        }
        
        if (!empty($filters['content_type'])) {
            $where_conditions[] = 'dc.content_type = %s';
            $query_params[] = $filters['content_type'];
        }
        
        $query = "
            SELECT dc.*, p.post_title as product_name, j.name as job_name
            FROM {$this->draft_table} dc
            LEFT JOIN {$this->wpdb->posts} p ON dc.product_id = p.ID
            LEFT JOIN {$this->wpdb->prefix}aipt_automation_jobs j ON dc.job_id = j.id
            WHERE " . implode(' AND ', $where_conditions) . "
            ORDER BY dc.created_at DESC
            LIMIT %d OFFSET %d
        ";
        
        $query_params[] = $limit;
        $query_params[] = $offset;


        if (!empty($query_params)) {
            return $this->wpdb->get_results($this->wpdb->prepare($query, $query_params));
        } else {
            return $this->wpdb->get_results($query);
        }

    }
    
    /**
     * Get draft content count
     * 
     * @param array $filters Filters
     * @return int Count
     */
    public function getDraftContentCount($filters = []) {
        $where_conditions = ['1=1'];
        $query_params = [];
        
        if (!empty($filters['job_id'])) {
            $where_conditions[] = 'job_id = %d';
            $query_params[] = $filters['job_id'];
        }
        
        if (!empty($filters['product_id'])) {
            $where_conditions[] = 'product_id = %d';
            $query_params[] = $filters['product_id'];
        }
        
        if (!empty($filters['status'])) {
            $where_conditions[] = 'status = %s';
            $query_params[] = $filters['status'];
        }
        
        if (!empty($filters['content_type'])) {
            $where_conditions[] = 'content_type = %s';
            $query_params[] = $filters['content_type'];
        }
        
        $query = "
            SELECT COUNT(*)
            FROM {$this->draft_table}
            WHERE " . implode(' AND ', $where_conditions);


        if (!empty($query_params)) {
            return (int) $this->wpdb->get_var($this->wpdb->prepare($query, $query_params));
        } else {
            return (int) $this->wpdb->get_var($query);
        }

    }
    
    /**
     * Approve draft content and apply to product
     * 
     * @param int $draft_id Draft content ID
     * @return bool Success status
     */
    public function approveDraftContent($draft_id) {
        try {

            $draft = $this->wpdb->get_row($this->wpdb->prepare(
                "SELECT * FROM {$this->draft_table} WHERE id = %d",
                $draft_id
            ));

            
            if (!$draft) {
                throw new \Exception('Draft content not found');
            }
            

            $success = $this->applyContentToProduct(
                $draft->product_id,
                $draft->content_type,
                $draft->generated_content
            );
            
            if ($success) {

                $this->wpdb->update(
                    $this->draft_table,
                    [
                        'status' => 'approved',
                        'approved_by' => get_current_user_id(),
                        'approved_at' => current_time('mysql'),
                        'updated_at' => current_time('mysql')
                    ],
                    ['id' => $draft_id],
                    ['%s', '%d', '%s', '%s'],
                    ['%d']
                );
                
                return true;
            }
            
            return false;
            
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Apply content to product
     * 
     * @param int $product_id Product ID
     * @param string $content_type Content type
     * @param string $content Content to apply
     * @return bool Success status
     */
    private function applyContentToProduct($product_id, $content_type, $content) {
        try {
            $product = wc_get_product($product_id);
            if (!$product) {
                return false;
            }
            
            switch ($content_type) {
                case 'title':
                    $product->set_name($content);
                    break;
                case 'description':
                    $product->set_description($content);
                    break;
                case 'short_description':
                    $product->set_short_description($content);
                    break;
                case 'tags':
                    $tag_names = array_map('trim', explode(',', $content));
                    $tag_ids = [];
                    foreach ($tag_names as $tag_name) {
                        if (!empty($tag_name)) {
                            $term = get_term_by('name', $tag_name, 'product_tag');
                            if (!$term) {
                                $term = wp_insert_term($tag_name, 'product_tag');
                                if (!is_wp_error($term)) {
                                    $tag_ids[] = $term['term_id'];
                                }
                            } else {
                                $tag_ids[] = $term->term_id;
                            }
                        }
                    }
                    wp_set_post_terms($product_id, $tag_ids, 'product_tag');
                    break;
                default:
                    return false;
            }
            
            if ($content_type !== 'tags') {
                $product->save();
            }
            
            return true;
            
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Reject draft content
     * 
     * @param int $draft_id Draft content ID
     * @return bool Success status
     */
    public function rejectDraftContent($draft_id) {
        try {
            $result = $this->wpdb->update(
                $this->draft_table,
                [
                    'status' => 'rejected',
                    'approved_by' => get_current_user_id(),
                    'approved_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ],
                ['id' => $draft_id],
                ['%s', '%d', '%s', '%s'],
                ['%d']
            );
            
            return $result !== false;
            
        } catch (\Exception $e) {
            return false;
        }
    }
    
    /**
     * Bulk approve draft content
     *
     * @param array $draft_ids Array of draft content IDs
     * @return array Results array with success/failure for each ID
     */
    public function bulkApproveDraftContent($draft_ids) {
        $results = [];

        foreach ($draft_ids as $draft_id) {
            $results[$draft_id] = $this->approveDraftContent($draft_id);
        }

        return $results;
    }

    /**
     * Bulk delete draft content
     *
     * @param array $draft_ids Array of draft content IDs
     * @return array Results array with success/failure for each ID
     */
    public function bulkDeleteDraftContent($draft_ids) {
        $results = [];

        foreach ($draft_ids as $draft_id) {
            $results[$draft_id] = $this->deleteDraftContent($draft_id);
        }

        return $results;
    }

    /**
     * Delete draft content
     *
     * @param int $draft_id Draft content ID
     * @return bool Success status
     */
    public function deleteDraftContent($draft_id) {
        try {
            $result = $this->wpdb->delete(
                $this->draft_table,
                ['id' => $draft_id],
                ['%d']
            );

            return $result !== false;

        } catch (\Exception $e) {
            return false;
        }
    }
}
