<?php
/**
 * Contract Section Model
 *
 * @package Freelance_Studio
 */

class FS_Contract_Section {

    /**
     * Get all sections
     *
     * @param bool $active_only Only return active sections
     * @return array Array of section objects
     */
    public static function get_all($active_only = false) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fs_contract_sections';

        $where = $active_only ? "WHERE is_active = 1" : "";
        
        return $wpdb->get_results(
            "SELECT * FROM $table_name $where ORDER BY sort_order ASC"
        );
    }

    /**
     * Get all sections keyed by section_key
     *
     * @param bool $active_only Whether to return only active sections
     * @return array Associative array of sections keyed by section_key
     */
    public static function get_all_keyed($active_only = false) {
        $sections = self::get_all($active_only);
        $keyed = array();
        
        foreach ($sections as $section) {
            $keyed[$section->section_key] = array(
                'id' => $section->id,
                'section_key' => $section->section_key,
                'title' => $section->title,
                'content' => $section->content,
                'is_default' => isset($section->is_default) ? $section->is_default : 0,
                'is_active' => isset($section->is_active) ? $section->is_active : 1,
                'sort_order' => isset($section->sort_order) ? $section->sort_order : 0,
            );
        }
        
        return $keyed;
    }

    /**
     * Get a section by ID
     *
     * @param int $id Section ID
     * @return object|null Section object
     */
    public static function get($id) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fs_contract_sections';

        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE id = %d",
            $id
        ));
    }

    /**
     * Get a section by key
     *
     * @param string $key Section key
     * @return object|null Section object
     */
    public static function get_by_key($key) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fs_contract_sections';

        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE section_key = %s",
            $key
        ));
    }

    /**
     * Update a section
     *
     * @param int $id Section ID
     * @param array $data Section data
     * @return bool Success
     */
    public static function update($id, $data) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fs_contract_sections';

        $update_data = array();
        $allowed_fields = array('title', 'content', 'sort_order', 'is_required', 'is_active');

        foreach ($allowed_fields as $field) {
            if (isset($data[$field])) {
                $update_data[$field] = $data[$field];
            }
        }

        if (empty($update_data)) {
            return true;
        }

        return $wpdb->update($table_name, $update_data, array('id' => $id)) !== false;
    }

    /**
     * Toggle section active status
     *
     * @param int $id Section ID
     * @param bool $active Active status
     * @return bool Success
     */
    public static function toggle_active($id, $active) {
        return self::update($id, array('is_active' => $active ? 1 : 0));
    }

    /**
     * Reorder sections
     *
     * @param array $order Array of section IDs in order
     * @return bool Success
     */
    public static function reorder($order) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fs_contract_sections';

        foreach ($order as $index => $id) {
            $wpdb->update(
                $table_name,
                array('sort_order' => $index + 1),
                array('id' => intval($id))
            );
        }

        return true;
    }

    /**
     * Get sections formatted for contract use
     * 
     * @param array $enabled_sections Array of section keys that are enabled for this contract
     * @return array Array of sections with enabled status
     */
    public static function get_for_contract($enabled_sections = null) {
        $all_sections = self::get_all();
        $result = array();

        foreach ($all_sections as $section) {
            // If no enabled_sections specified, use the is_active setting
            if ($enabled_sections === null) {
                $section->enabled = $section->is_active ? true : false;
            } else {
                // Check if this section is in the enabled list
                $section->enabled = in_array($section->section_key, $enabled_sections);
            }
            $result[] = $section;
        }

        return $result;
    }

    /**
     * Build contract terms HTML from enabled sections
     *
     * @param array $enabled_sections Array of section keys that are enabled
     * @param array $replacements Optional array of placeholder replacements
     * @return string HTML content
     */
    public static function build_terms_html($enabled_sections, $replacements = array()) {
        $sections = self::get_all();
        $html = '<div class="contract-terms" style="margin: 0; padding: 0;">';

        $section_number = 1;
        foreach ($sections as $section) {
            if (!in_array($section->section_key, $enabled_sections)) {
                continue;
            }

            $content = $section->content;

            // Apply replacements for placeholders
            foreach ($replacements as $placeholder => $value) {
                $content = str_replace($placeholder, $value, $content);
            }

            // First section has no top margin, subsequent sections have spacing
            $section_margin = ($section_number === 1) ? '0' : '12px';
            
            $html .= '<div class="contract-section" id="section-' . esc_attr($section->section_key) . '" style="margin: 0; padding: 0; margin-top: ' . $section_margin . ';">';
            $html .= '<h3 style="margin: 0 0 4px 0; padding: 0;">' . $section_number . '. ' . esc_html($section->title) . '</h3>';
            $html .= '<div class="section-content" style="margin: 0; padding: 0;">' . wp_kses_post($content) . '</div>';
            $html .= '</div>';

            $section_number++;
        }

        $html .= '</div>';

        return $html;
    }

    /**
     * Reset sections to defaults
     */
    public static function reset_to_defaults() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fs_contract_sections';

        // Clear existing sections
        $wpdb->query("TRUNCATE TABLE $table_name");

        // Re-install defaults
        FS_Activator::install_default_contract_sections();
    }

    /**
     * Get default placeholder values
     *
     * @return array Array of placeholder => description
     */
    public static function get_placeholders() {
        return array(
            '[Number]' => __('Number of days (e.g., for notice period, cure period)', 'freelance-studio'),
            '[Percentage]' => __('Late payment percentage (e.g., 1.5%)', 'freelance-studio'),
            '[Hourly Rate]' => __('Freelancer\'s hourly rate', 'freelance-studio'),
            '[Freelancer\'s State/Country]' => __('Governing law jurisdiction', 'freelance-studio'),
        );
    }
}
