<?php
/**
 * Project Templates Controller
 *
 * @package Freelance_Studio
 */

class FS_Project_Templates_Controller {

    /**
     * Handle the request
     */
    public function handle_request() {
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : 'list';
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handle_post();
            return;
        }

        switch ($action) {
            case 'add':
                $this->form();
                break;
            case 'edit':
                $this->form($id);
                break;
            case 'duplicate':
                $this->duplicate($id);
                break;
            default:
                $this->index();
                break;
        }
    }

    /**
     * Handle POST requests
     */
    private function handle_post() {
        if (!isset($_POST['fs_template_nonce']) || !wp_verify_nonce($_POST['fs_template_nonce'], 'fs_save_template')) {
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }

        $id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;

        // Build milestones array
        $milestones = array();
        if (!empty($_POST['milestone_name'])) {
            foreach ($_POST['milestone_name'] as $index => $name) {
                if (empty($name)) continue;
                
                $milestones[] = array(
                    'name' => sanitize_text_field($name),
                    'description' => isset($_POST['milestone_description'][$index]) ? sanitize_textarea_field(wp_unslash($_POST['milestone_description'])[$index]) : '',
                    'days_offset' => isset($_POST['milestone_days_offset'][$index]) ? intval($_POST['milestone_days_offset'][$index]) : 0,
                    'invoice_on_completion' => isset($_POST['milestone_invoice'][$index]) ? 1 : 0,
                    'invoice_percentage' => isset($_POST['milestone_percentage'][$index]) ? floatval($_POST['milestone_percentage'][$index]) : null,
                );
            }
        }

        // Build tasks array
        $tasks = array();
        if (!empty($_POST['task_title'])) {
            foreach ($_POST['task_title'] as $index => $title) {
                if (empty($title)) continue;
                
                $tasks[] = array(
                    'title' => sanitize_text_field($title),
                    'description' => isset($_POST['task_description'][$index]) ? sanitize_textarea_field(wp_unslash($_POST['task_description'])[$index]) : '',
                    'priority' => isset($_POST['task_priority'][$index]) ? sanitize_text_field(wp_unslash($_POST['task_priority'])[$index]) : 'medium',
                    'days_offset' => isset($_POST['task_days_offset'][$index]) ? intval($_POST['task_days_offset'][$index]) : 0,
                    'estimated_hours' => isset($_POST['task_hours'][$index]) ? floatval($_POST['task_hours'][$index]) : null,
                    'milestone_index' => isset($_POST['task_milestone_index'][$index]) && $_POST['task_milestone_index'][$index] !== '' ? intval($_POST['task_milestone_index'][$index]) : null,
                );
            }
        }

        $data = array(
            'name' => sanitize_text_field(wp_unslash($_POST['name'])),
            'description' => sanitize_textarea_field(wp_unslash($_POST['description'])),
            'default_billing_type' => sanitize_text_field(wp_unslash($_POST['default_billing_type'])),
            'default_hourly_rate' => !empty($_POST['default_hourly_rate']) ? floatval($_POST['default_hourly_rate']) : null,
            'estimated_hours' => !empty($_POST['estimated_hours']) ? floatval($_POST['estimated_hours']) : null,
            'typical_price_min' => !empty($_POST['typical_price_min']) ? floatval($_POST['typical_price_min']) : null,
            'typical_price_max' => !empty($_POST['typical_price_max']) ? floatval($_POST['typical_price_max']) : null,
            'default_milestones' => $milestones,
            'default_tasks' => $tasks,
        );

        if ($id) {
            FS_Project_Template::update($id, $data);
            $redirect_id = $id;
        } else {
            $redirect_id = FS_Project_Template::create($data);
        }

        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-project-templates&message=saved'));
        exit;
    }

    /**
     * List all templates
     */
    private function index() {
        $templates = FS_Project_Template::get_all();
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';

        include JEEB_FS_PLUGIN_DIR . 'includes/views/project-templates/list.php';
    }

    /**
     * Add/Edit form
     */
    private function form($id = 0) {
        $template = $id ? FS_Project_Template::get($id) : null;
        $billing_types = array(
            'hourly' => __('Hourly', 'freelance-studio'),
            'fixed' => __('Fixed Price', 'freelance-studio'),
            'retainer' => __('Retainer', 'freelance-studio'),
        );
        $priorities = FS_Task::get_priorities();

        include JEEB_FS_PLUGIN_DIR . 'includes/views/project-templates/form.php';
    }

    /**
     * Duplicate a template
     */
    private function duplicate($id) {
        $new_id = FS_Project_Template::duplicate($id);
        
        if ($new_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-project-templates&action=edit&id=' . $new_id . '&message=duplicated'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-project-templates&error=duplicate_failed'));
        }
        exit;
    }
}
