<?php

/**
 * Template Model
 * Handles message template management
 */
class Template {
    
    private $db;
    
    public $id;
    public $name;
    public $description;
    public $content;
    public $status;
    public $created_at;
    public $updated_at;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create a new template
     * 
     * @param array $data
     * @return int|false Template ID on success, false on failure
     */
    public function create($data) {
        // Validate required fields
        if (empty($data['name']) || empty($data['content'])) {
            return false;
        }
        
        $sql = "INSERT INTO templates (name, description, content, status) VALUES (?, ?, ?, ?)";
        
        $status = isset($data['status']) ? $data['status'] : 'active';
        
        $this->db->execute($sql, [
            $data['name'],
            $data['description'] ?? '',
            $data['content'],
            $status
        ]);
        
        return $this->db->lastInsertId();
    }
    
    /**
     * Find template by ID
     * 
     * @param int $id
     * @return Template|false
     */
    public function findById($id) {
        $sql = "SELECT * FROM templates WHERE id = ? LIMIT 1";
        $template = $this->db->fetchOne($sql, [$id]);
        
        if ($template) {
            $this->fillFromArray($template);
            return $this;
        }
        
        return false;
    }
    
    /**
     * Update template
     * 
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function update($id, $data) {
        $fields = [];
        $values = [];
        
        // Build update query dynamically
        if (isset($data['name'])) {
            $fields[] = "name = ?";
            $values[] = $data['name'];
        }
        
        if (isset($data['description'])) {
            $fields[] = "description = ?";
            $values[] = $data['description'];
        }
        
        if (isset($data['content'])) {
            $fields[] = "content = ?";
            $values[] = $data['content'];
        }
        
        if (isset($data['status'])) {
            $fields[] = "status = ?";
            $values[] = $data['status'];
        }
        
        if (empty($fields)) {
            return false;
        }
        
        $values[] = $id;
        $sql = "UPDATE templates SET " . implode(', ', $fields) . " WHERE id = ?";
        
        // Execute the query - return true if query executed successfully
        // Note: execute() returns affected rows, which could be 0 if no changes were made
        try {
            $this->db->execute($sql, $values);
            return true; // Query executed successfully
        } catch (Exception $e) {
            logError("Template update failed: " . $e->getMessage(), ['template_id' => $id]);
            return false;
        }
    }
    
    /**
     * Delete template
     * 
     * @param int $id
     * @return bool
     */
    public function delete($id) {
        $sql = "DELETE FROM templates WHERE id = ?";
        return $this->db->execute($sql, [$id]) > 0;
    }
    
    /**
     * Get all templates
     * 
     * @return array
     */
    public function getAll() {
        $sql = "SELECT * FROM templates ORDER BY created_at DESC";
        return $this->db->fetchAll($sql);
    }
    
    /**
     * Get active templates only
     * 
     * @return array
     */
    public function getActive() {
        $sql = "SELECT * FROM templates WHERE status = 'active' ORDER BY name ASC";
        return $this->db->fetchAll($sql);
    }
    
    /**
     * Get templates with pagination
     * 
     * @param int $page
     * @param int $perPage
     * @return array
     */
    public function paginate($page = 1, $perPage = 20) {
        $offset = ($page - 1) * $perPage;
        $sql = "SELECT * FROM templates ORDER BY created_at DESC LIMIT ? OFFSET ?";
        return $this->db->fetchAll($sql, [$perPage, $offset]);
    }
    
    /**
     * Count total templates
     * 
     * @return int
     */
    public function count() {
        $sql = "SELECT COUNT(*) as count FROM templates";
        $result = $this->db->fetchOne($sql);
        return $result['count'] ?? 0;
    }
    
    /**
     * Count active templates
     * 
     * @return int
     */
    public function countActive() {
        $sql = "SELECT COUNT(*) as count FROM templates WHERE status = 'active'";
        $result = $this->db->fetchOne($sql);
        return $result['count'] ?? 0;
    }
    
    /**
     * Toggle template status
     * 
     * @param int $id
     * @return bool
     */
    public function toggleStatus($id) {
        $sql = "UPDATE templates SET status = IF(status = 'active', 'inactive', 'active') WHERE id = ?";
        return $this->db->execute($sql, [$id]) > 0;
    }
    
    /**
     * Search templates
     * 
     * @param string $query
     * @return array
     */
    public function search($query) {
        $sql = "SELECT * FROM templates 
                WHERE name LIKE ? OR description LIKE ? OR content LIKE ?
                ORDER BY created_at DESC";
        
        $searchTerm = '%' . $query . '%';
        return $this->db->fetchAll($sql, [$searchTerm, $searchTerm, $searchTerm]);
    }
    
    /**
     * Fill object properties from array
     * 
     * @param array $data
     */
    private function fillFromArray($data) {
        $this->id = $data['id'] ?? null;
        $this->name = $data['name'] ?? null;
        $this->description = $data['description'] ?? null;
        $this->content = $data['content'] ?? null;
        $this->status = $data['status'] ?? null;
        $this->created_at = $data['created_at'] ?? null;
        $this->updated_at = $data['updated_at'] ?? null;
    }
    
    /**
     * Get user's default template
     * 
     * @param int $userId
     * @return Template|null
     */
    public function getUserDefaultTemplate($userId) {
        $sql = "SELECT t.* FROM templates t
                INNER JOIN user_templates ut ON t.id = ut.template_id
                WHERE ut.user_id = ? AND ut.is_default = 1 AND t.status = 'active'
                LIMIT 1";
        
        $data = $this->db->fetchOne($sql, [$userId]);
        
        if ($data) {
            $template = new Template();
            $template->fillFromArray($data);
            return $template;
        }
        
        // If no default template, return first active template
        $sql = "SELECT * FROM templates WHERE status = 'active' ORDER BY id ASC LIMIT 1";
        $data = $this->db->fetchOne($sql);
        
        if ($data) {
            $template = new Template();
            $template->fillFromArray($data);
            return $template;
        }
        
        return null;
    }
    
    /**
     * Set user's default template
     * 
     * @param int $userId
     * @param int $templateId
     * @return bool
     */
    public function setUserDefaultTemplate($userId, $templateId) {
        try {
            // First, delete any existing default for this user (to avoid unique constraint issue)
            $sql = "DELETE FROM user_templates WHERE user_id = ? AND is_default = 1";
            $this->db->execute($sql, [$userId]);
            
            // Check if user-template association exists
            $sql = "SELECT id FROM user_templates WHERE user_id = ? AND template_id = ?";
            $existing = $this->db->fetchOne($sql, [$userId, $templateId]);
            
            if ($existing) {
                // Update existing association
                $sql = "UPDATE user_templates SET is_default = 1 WHERE user_id = ? AND template_id = ?";
                return $this->db->execute($sql, [$userId, $templateId]) !== false;
            } else {
                // Create new association
                $sql = "INSERT INTO user_templates (user_id, template_id, is_default) VALUES (?, ?, 1)";
                return $this->db->execute($sql, [$userId, $templateId]) !== false;
            }
        } catch (Exception $e) {
            logError("Failed to set default template: " . $e->getMessage(), ['user_id' => $userId, 'template_id' => $templateId]);
            return false;
        }
    }
    
    /**
     * Convert template to array
     * 
     * @return array
     */
    public function toArray() {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'content' => $this->content,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at
        ];
    }
    
    /**
     * Get paginated templates
     */
    public function getPaginated($limit = 10, $offset = 0) {
        $sql = "SELECT * FROM templates ORDER BY created_at DESC LIMIT ? OFFSET ?";
        return $this->db->fetchAll($sql, [$limit, $offset]);
    }
    
    /**
     * Search templates with pagination
     */
    public function searchPaginated($query, $limit = 10, $offset = 0) {
        $searchTerm = '%' . $query . '%';
        $sql = "SELECT * FROM templates 
                WHERE name LIKE ? OR description LIKE ? OR content LIKE ?
                ORDER BY created_at DESC 
                LIMIT ? OFFSET ?";
        return $this->db->fetchAll($sql, [$searchTerm, $searchTerm, $searchTerm, $limit, $offset]);
    }
    
    /**
     * Count total templates
     */
    public function countTotal() {
        $sql = "SELECT COUNT(*) as total FROM templates";
        $result = $this->db->fetchOne($sql);
        return $result ? (int)$result['total'] : 0;
    }
    
    /**
     * Count search results
     */
    public function countSearch($query) {
        $searchTerm = '%' . $query . '%';
        $sql = "SELECT COUNT(*) as total FROM templates 
                WHERE name LIKE ? OR description LIKE ? OR content LIKE ?";
        $result = $this->db->fetchOne($sql, [$searchTerm, $searchTerm, $searchTerm]);
        return $result ? (int)$result['total'] : 0;
    }
}
