<?php
/**
 * Project Template Model
 *
 * @package Freelance_Studio
 */

class FS_Project_Template {

    /**
     * Get a single template by ID
     */
    public static function get($id) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_project_types';
        
        $template = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d",
            $id
        ));
        
        if ($template) {
            $template->default_tasks = json_decode($template->default_tasks ?? '', true) ?: array();
            $template->default_milestones = json_decode($template->default_milestones ?? '', true) ?: array();
        }
        
        return $template;
    }

    /**
     * Get all templates
     */
    public static function get_all($args = array()) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_project_types';
        
        $defaults = array(
            'orderby' => 'name',
            'order' => 'ASC',
        );
        
        $args = wp_parse_args($args, $defaults);
        $orderby = in_array($args['orderby'], array('name', 'created_at')) ? $args['orderby'] : 'name';
        $order = strtoupper($args['order']) === 'DESC' ? 'DESC' : 'ASC';
        
        $templates = $wpdb->get_results(
            "SELECT * FROM {$table} ORDER BY {$orderby} {$order}"
        );
        
        foreach ($templates as $template) {
            $template->default_tasks = json_decode($template->default_tasks ?? '', true) ?: array();
            $template->default_milestones = json_decode($template->default_milestones ?? '', true) ?: array();
        }
        
        return $templates;
    }

    /**
     * Get templates for dropdown
     */
    public static function get_for_dropdown() {
        $templates = self::get_all();
        $options = array();
        
        foreach ($templates as $template) {
            $options[$template->id] = $template->name;
        }
        
        return $options;
    }

    /**
     * Create a new template
     */
    public static function create($data) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_project_types';
        
        $milestones = isset($data['default_milestones']) ? $data['default_milestones'] : array();
        $tasks = isset($data['default_tasks']) ? $data['default_tasks'] : array();
        
        if (is_array($milestones)) {
            $milestones = wp_json_encode($milestones);
        }
        if (is_array($tasks)) {
            $tasks = wp_json_encode($tasks);
        }
        
        $result = $wpdb->insert(
            $table,
            array(
                'name' => sanitize_text_field($data['name']),
                'description' => isset($data['description']) ? sanitize_textarea_field($data['description']) : null,
                'default_billing_type' => isset($data['default_billing_type']) ? sanitize_text_field($data['default_billing_type']) : 'hourly',
                'default_hourly_rate' => isset($data['default_hourly_rate']) ? floatval($data['default_hourly_rate']) : null,
                'default_milestones' => $milestones,
                'default_tasks' => $tasks,
                'estimated_hours' => isset($data['estimated_hours']) ? floatval($data['estimated_hours']) : null,
                'typical_price_min' => isset($data['typical_price_min']) ? floatval($data['typical_price_min']) : null,
                'typical_price_max' => isset($data['typical_price_max']) ? floatval($data['typical_price_max']) : null,
            ),
            array('%s', '%s', '%s', '%f', '%s', '%s', '%f', '%f', '%f')
        );
        
        return $result ? $wpdb->insert_id : false;
    }

    /**
     * Update a template
     */
    public static function update($id, $data) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_project_types';
        
        $update_data = array();
        $format = array();
        
        if (isset($data['name'])) {
            $update_data['name'] = sanitize_text_field($data['name']);
            $format[] = '%s';
        }
        
        if (array_key_exists('description', $data)) {
            $update_data['description'] = $data['description'] ? sanitize_textarea_field($data['description']) : null;
            $format[] = '%s';
        }
        
        if (isset($data['default_billing_type'])) {
            $update_data['default_billing_type'] = sanitize_text_field($data['default_billing_type']);
            $format[] = '%s';
        }
        
        if (array_key_exists('default_hourly_rate', $data)) {
            $update_data['default_hourly_rate'] = $data['default_hourly_rate'] ? floatval($data['default_hourly_rate']) : null;
            $format[] = '%f';
        }
        
        if (isset($data['default_milestones'])) {
            $milestones = is_array($data['default_milestones']) ? wp_json_encode($data['default_milestones']) : $data['default_milestones'];
            $update_data['default_milestones'] = $milestones;
            $format[] = '%s';
        }
        
        if (isset($data['default_tasks'])) {
            $tasks = is_array($data['default_tasks']) ? wp_json_encode($data['default_tasks']) : $data['default_tasks'];
            $update_data['default_tasks'] = $tasks;
            $format[] = '%s';
        }
        
        if (array_key_exists('estimated_hours', $data)) {
            $update_data['estimated_hours'] = $data['estimated_hours'] ? floatval($data['estimated_hours']) : null;
            $format[] = '%f';
        }
        
        if (array_key_exists('typical_price_min', $data)) {
            $update_data['typical_price_min'] = $data['typical_price_min'] ? floatval($data['typical_price_min']) : null;
            $format[] = '%f';
        }
        
        if (array_key_exists('typical_price_max', $data)) {
            $update_data['typical_price_max'] = $data['typical_price_max'] ? floatval($data['typical_price_max']) : null;
            $format[] = '%f';
        }
        
        if (empty($update_data)) {
            return false;
        }
        
        return $wpdb->update($table, $update_data, array('id' => $id), $format, array('%d'));
    }

    /**
     * Delete a template
     */
    public static function delete($id) {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_project_types';
        
        return $wpdb->delete($table, array('id' => $id), array('%d'));
    }

    /**
     * Apply template to a project (create milestones and tasks)
     */
    public static function apply_to_project($template_id, $project_id, $start_date = null) {
        $template = self::get($template_id);
        
        if (!$template) {
            return false;
        }
        
        $start_date = $start_date ?: current_time('Y-m-d');
        $milestone_map = array(); // Maps template milestone index to created milestone ID
        
        // Create milestones first
        if (!empty($template->default_milestones)) {
            foreach ($template->default_milestones as $index => $milestone_data) {
                $due_date = null;
                if (!empty($milestone_data['days_offset'])) {
                    $due_date = gmdate('Y-m-d', strtotime($start_date . ' + ' . intval($milestone_data['days_offset']) . ' days'));
                }
                
                $milestone_id = FS_Milestone::create(array(
                    'project_id' => $project_id,
                    'name' => $milestone_data['name'],
                    'description' => isset($milestone_data['description']) ? $milestone_data['description'] : null,
                    'due_date' => $due_date,
                    'invoice_on_completion' => isset($milestone_data['invoice_on_completion']) ? $milestone_data['invoice_on_completion'] : 0,
                    'invoice_percentage' => isset($milestone_data['invoice_percentage']) ? $milestone_data['invoice_percentage'] : null,
                    'position' => $index,
                ));
                
                if ($milestone_id) {
                    $milestone_map[$index] = $milestone_id;
                }
            }
        }
        
        // Create tasks
        if (!empty($template->default_tasks)) {
            foreach ($template->default_tasks as $task_data) {
                $due_date = null;
                if (!empty($task_data['days_offset'])) {
                    $due_date = gmdate('Y-m-d', strtotime($start_date . ' + ' . intval($task_data['days_offset']) . ' days'));
                }
                
                // Map milestone reference if present
                $milestone_id = null;
                if (isset($task_data['milestone_index']) && isset($milestone_map[$task_data['milestone_index']])) {
                    $milestone_id = $milestone_map[$task_data['milestone_index']];
                }
                
                FS_Task::create(array(
                    'project_id' => $project_id,
                    'milestone_id' => $milestone_id,
                    'title' => $task_data['title'],
                    'description' => isset($task_data['description']) ? $task_data['description'] : null,
                    'priority' => isset($task_data['priority']) ? $task_data['priority'] : 'medium',
                    'due_date' => $due_date,
                    'estimated_hours' => isset($task_data['estimated_hours']) ? $task_data['estimated_hours'] : null,
                ));
            }
        }
        
        return true;
    }

    /**
     * Count templates
     */
    public static function count() {
        global $wpdb;
        $table = $wpdb->prefix . 'fs_project_types';
        
        return (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table}");
    }

    /**
     * Duplicate a template
     */
    public static function duplicate($id) {
        $template = self::get($id);
        
        if (!$template) {
            return false;
        }
        
        return self::create(array(
            'name' => $template->name . ' (Copy)',
            'description' => $template->description,
            'default_billing_type' => $template->default_billing_type,
            'default_hourly_rate' => $template->default_hourly_rate,
            'default_milestones' => $template->default_milestones,
            'default_tasks' => $template->default_tasks,
            'estimated_hours' => $template->estimated_hours,
            'typical_price_min' => $template->typical_price_min,
            'typical_price_max' => $template->typical_price_max,
        ));
    }
}
