<?php
/**
 * Proposals Controller
 *
 * @package Freelance_Studio
 */

class FS_Proposals_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->add();
                break;
            case 'edit':
                $this->edit($id);
                break;
            case 'view':
                $this->view($id);
                break;
            case 'duplicate':
                $this->duplicate($id);
                break;
            case 'send':
                $this->send($id);
                break;
            case 'pdf':
                $this->pdf($id);
                break;
            case 'convert':
                $this->convert_to_contract($id);
                break;
            case 'approve':
                $this->approve($id);
                break;
            default:
                $this->index();
                break;
        }
    }

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

        $action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
        $id = isset($_POST['proposal_id']) ? intval($_POST['proposal_id']) : 0;

        // Parse services from form
        $services = array();
        if (isset($_POST['services']) && is_array($_POST['services'])) {
            foreach ($_POST['services'] as $service) {
                if (!empty($service['name'])) {
                    $services[] = array(
                        'name' => sanitize_text_field(wp_unslash($service['name'] ?? '')),
                        'description' => sanitize_textarea_field(wp_unslash($service['description'] ?? '')),
                        'pricing_type' => sanitize_text_field($service['pricing_type'] ?? 'fixed'),
                        'rate' => floatval($service['rate'] ?? 0),
                        'quantity' => floatval($service['quantity'] ?? 1),
                        'amount' => floatval($service['amount'] ?? 0),
                    );
                }
            }
        }
        
        // Parse custom sections from form
        $custom_sections = array();
        if (isset($_POST['custom_sections']) && is_array($_POST['custom_sections'])) {
            foreach ($_POST['custom_sections'] as $section) {
                if (!empty($section['title']) || !empty($section['content'])) {
                    $custom_sections[] = array(
                        'id' => sanitize_text_field($section['id'] ?? uniqid('section_')),
                        'title' => sanitize_text_field(wp_unslash($section['title'] ?? '')),
                        'content' => wp_kses_post(wp_unslash($section['content'] ?? '')),
                        'position' => sanitize_text_field($section['position'] ?? 'before_pricing'),
                    );
                }
            }
        }
        
        // Parse selected contacts
        $send_to_contacts = array();
        if (isset($_POST['send_to_contacts']) && is_array($_POST['send_to_contacts'])) {
            foreach ($_POST['send_to_contacts'] as $contact_id) {
                if ($contact_id !== 'primary') {
                    $send_to_contacts[] = intval($contact_id);
                }
            }
        }

        // Calculate total amount
        $total_amount = array_reduce($services, function($carry, $service) {
            return $carry + floatval($service['amount']);
        }, 0);

        $data = array(
            'client_id' => intval($_POST['client_id']),
            'title' => sanitize_text_field(wp_unslash($_POST['title'])),
            'services' => $services,
            'custom_sections' => $custom_sections,
            'pricing_type' => sanitize_text_field(wp_unslash($_POST['pricing_type'] ?? 'fixed')),
            'hourly_rate' => floatval($_POST['hourly_rate'] ?? 0),
            'estimated_hours' => floatval($_POST['estimated_hours'] ?? 0),
            'total_amount' => $total_amount,
            'deposit_required' => isset($_POST['deposit_required']) ? 1 : 0,
            'deposit_type' => sanitize_text_field(wp_unslash($_POST['deposit_type'] ?? 'percentage')),
            'deposit_value' => floatval($_POST['deposit_value'] ?? 0),
            'billing_frequency' => sanitize_text_field(wp_unslash($_POST['billing_frequency'] ?? 'once')),
            'first_invoice_date' => sanitize_text_field(wp_unslash($_POST['first_invoice_date'] ?? '')),
            'start_date' => sanitize_text_field(wp_unslash($_POST['start_date'] ?? '')),
            'valid_until' => sanitize_text_field(wp_unslash($_POST['valid_until'] ?? '')),
            'notes' => sanitize_textarea_field(wp_unslash($_POST['notes'] ?? '')),
            'internal_notes' => sanitize_textarea_field(wp_unslash($_POST['internal_notes'] ?? '')),
            'send_to_contacts' => !empty($send_to_contacts) ? json_encode($send_to_contacts) : null,
        );

        if ($action === 'update' && $id) {
            // Check if this was a revision request - if so, mark as revised and offer to resend
            $existing_proposal = FS_Proposal::get($id);
            $was_revision_requested = ($existing_proposal && $existing_proposal->status === 'revision_requested');
            
            $result = FS_Proposal::update($id, $data);
            
            if ($result !== false && $was_revision_requested) {
                // Update status to 'revised' and clear revision notes
                FS_Proposal::update_status($id, 'revised');
                
                // Redirect to view with option to resend
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=revised'));
            } else {
                $message = $result !== false ? 'updated' : 'error';
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=' . $message));
            }
        } else {
            // Check free plan active proposal limit before creating
            if ( function_exists( 'fs_studio_limit_reached' ) && fs_studio_limit_reached( 'active_proposals' ) ) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=limit_reached'));
                exit;
            }
            
            $proposal_id = FS_Proposal::create($data);
            if ($proposal_id) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $proposal_id . '&message=created'));
            } else {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=add&message=error'));
            }
        }
        exit;
    }

    /**
     * List all proposals
     */
    public function index() {
        // Handle archive/unarchive actions
        if (isset($_GET['do_archive']) && isset($_GET['id']) && wp_verify_nonce($_GET['_wpnonce'] ?? '', 'fs_archive_proposal')) {
            $id = intval($_GET['id']);
            FS_Proposal::archive($id);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=archived'));
        }
        if (isset($_GET['do_unarchive']) && isset($_GET['id']) && wp_verify_nonce($_GET['_wpnonce'] ?? '', 'fs_unarchive_proposal')) {
            $id = intval($_GET['id']);
            FS_Proposal::unarchive($id);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&tab=archived&message=unarchived'));
        }

        $current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'active';
        $status_filter = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : null;
        $client_filter = isset($_GET['client_id']) ? intval($_GET['client_id']) : null;
        $orderby = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : 'created_at';
        $order = isset($_GET['order']) ? sanitize_text_field($_GET['order']) : 'DESC';
        
        // Pagination
        $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 25;
        $per_page = in_array($per_page, array(10, 25, 50, 100)) ? $per_page : 25;
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $offset = ($current_page - 1) * $per_page;
        
        $args = array(
            'orderby' => $orderby,
            'order' => $order,
            'archived' => $current_tab === 'archived',
            'limit' => $per_page,
            'offset' => $offset,
        );
        if ($status_filter) {
            $args['status'] = $status_filter;
        }
        if ($client_filter) {
            $args['client_id'] = $client_filter;
        }
        
        $proposals = FS_Proposal::get_all($args);
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Proposal::get_statuses();
        $active_count = FS_Proposal::get_count(false);
        $archived_count = FS_Proposal::get_count(true);
        
        // Total for pagination
        $count_args = array('archived' => $current_tab === 'archived');
        if ($status_filter) $count_args['status'] = $status_filter;
        if ($client_filter) $count_args['client_id'] = $client_filter;
        $total_items = FS_Proposal::count($count_args);
        $total_pages = ceil($total_items / $per_page);
        
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $messages = array(
            'created' => __('Proposal created successfully.', 'freelance-studio'),
            'updated' => __('Proposal updated successfully.', 'freelance-studio'),
            'deleted' => __('Proposal deleted successfully.', 'freelance-studio'),
            'sent' => __('Proposal sent successfully! The client will receive an email with a link to view and approve.', 'freelance-studio'),
            'sent_no_email' => __('Proposal marked as sent, but email delivery failed. Your server may not be configured for sending mail. Consider using an SMTP plugin like WP Mail SMTP, or share the client link manually.', 'freelance-studio'),
            'duplicated' => __('Proposal duplicated successfully.', 'freelance-studio'),
            'converted' => __('Proposal converted to contract successfully.', 'freelance-studio'),
            'revised' => __('Proposal revised successfully. Click "Send Revised Proposal" to notify the client.', 'freelance-studio'),
            'error' => __('An error occurred. Please try again.', 'freelance-studio'),
            'archived' => __('Proposal archived successfully.', 'freelance-studio'),
            'unarchived' => __('Proposal restored from archive.', 'freelance-studio'),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/proposals/list.php';
    }

    /**
     * Add new proposal form
     */
    public function add() {
        $proposal = null;
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Proposal::get_statuses();
        $frequencies = FS_Proposal::get_billing_frequencies();
        $next_proposal_number = FS_Proposal::generate_proposal_number();
        $is_new = true;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        // Pre-select client if passed in URL
        $selected_client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;
        
        // Default values
        $default_hourly_rate = get_option('fs_default_hourly_rate', 65);
        $default_valid_days = get_option('fs_proposal_valid_days', 30);
        
        // Load section templates
        $section_templates = FS_Proposal_Section::get_all();
        $section_positions = FS_Proposal_Section::get_position_labels();
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/proposals/form.php';
    }

    /**
     * Edit proposal form
     */
    public function edit($id) {
        $proposal = FS_Proposal::get($id);
        
        if (!$proposal) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=not_found'));
            exit;
        }
        
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Proposal::get_statuses();
        $frequencies = FS_Proposal::get_billing_frequencies();
        $is_new = false;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $default_hourly_rate = get_option('fs_default_hourly_rate', 65);
        
        // Load section templates
        $section_templates = FS_Proposal_Section::get_all();
        $section_positions = FS_Proposal_Section::get_position_labels();
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/proposals/form.php';
    }

    /**
     * View proposal (preview)
     */
    public function view($id) {
        $proposal = FS_Proposal::get($id);
        
        if (!$proposal) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=not_found'));
            exit;
        }
        
        $client = FS_Client::get($proposal->client_id);
        $settings = $this->get_business_settings();
        $statuses = FS_Proposal::get_statuses();
        $frequencies = FS_Proposal::get_billing_frequencies();
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $messages = array(
            'created' => __('Proposal created successfully.', 'freelance-studio'),
            'updated' => __('Proposal updated successfully.', 'freelance-studio'),
            'sent' => __('Proposal sent successfully! The client will receive an email with a link to view and approve.', 'freelance-studio'),
            'sent_no_email' => __('Proposal marked as sent, but email delivery failed. Your server may not be configured for sending mail. Consider using an SMTP plugin like WP Mail SMTP, or share the client link manually below.', 'freelance-studio'),
            'revised' => __('Proposal revised successfully. Click "Send Revised Proposal" to notify the client.', 'freelance-studio'),
            'approved' => __('Proposal marked as approved.', 'freelance-studio'),
            'already_approved' => __('This proposal is already approved.', 'freelance-studio'),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/proposals/view.php';
    }

    /**
     * Duplicate a proposal
     */
    public function duplicate($id) {
        $new_id = FS_Proposal::duplicate($id);
        
        if ($new_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=edit&id=' . $new_id . '&message=duplicated'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=error'));
        }
        exit;
    }

    /**
     * Mark proposal as sent and send email
     */
    public function send($id) {
        $proposal = FS_Proposal::get($id);
        
        if (!$proposal) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=not_found'));
            exit;
        }
        
        // Get contact IDs if specified
        $contact_ids = array();
        if (!empty($proposal->send_to_contacts)) {
            $contact_ids = json_decode($proposal->send_to_contacts, true) ?: array();
        }
        
        // Send email to client
        $sent = FS_Email_Service::send_proposal($id, $contact_ids);
        
        if ($sent) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=sent'));
        } else {
            // Still mark as sent even if email fails (they can resend or share link manually)
            FS_Proposal::update_status($id, FS_Proposal::STATUS_SENT);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=sent_no_email'));
        }
        exit;
    }

    /**
     * Generate PDF for proposal
     */
    public function pdf($id) {
        // PDF downloads are a Pro feature
        if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=pro_required'));
            exit;
        }
        
        // Clear any output buffers to prevent WordPress admin from interfering
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        $proposal = FS_Proposal::get($id);
        
        if (!$proposal) {
            wp_die(esc_html__('Proposal not found', 'freelance-studio'));
        }
        
        $client = FS_Client::get($proposal->client_id);
        
        FS_PDF_Service::generate_proposal($proposal, $client);
    }

    /**
     * Convert proposal to contract
     */
    public function convert_to_contract($id) {
        $proposal = FS_Proposal::get($id);
        
        if (!$proposal) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=not_found'));
            exit;
        }
        
        // Create contract from proposal
        // This will be implemented in Phase 3
        // For now, redirect to contract creation with proposal data pre-filled
        
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=add&proposal_id=' . $id));
        exit;
    }

    /**
     * Manually approve a proposal (verbal approval)
     */
    public function approve($id) {
        $proposal = FS_Proposal::get($id);
        
        if (!$proposal) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&message=not_found'));
            exit;
        }
        
        // Don't allow approving already approved/converted proposals
        if (in_array($proposal->status, array('approved', 'converted'))) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=already_approved'));
            exit;
        }
        
        // Update status to approved
        $result = FS_Proposal::update($id, array(
            'status' => 'approved',
            'approved_at' => current_time('mysql'),
        ));
        
        if ($result !== false) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=approved'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-proposals&action=view&id=' . $id . '&message=error'));
        }
        exit;
    }

    /**
     * Get business settings for proposal display
     */
    private function get_business_settings() {
        return array(
            'business_name' => get_option('fs_business_name', ''),
            'business_email' => get_option('fs_business_email', ''),
            'business_phone' => get_option('fs_business_phone', ''),
            'business_website' => get_option('fs_business_website', ''),
            'business_address' => get_option('fs_business_address', ''),
            'business_city' => get_option('fs_business_city', ''),
            'business_state' => get_option('fs_business_state', ''),
            'business_zip' => get_option('fs_business_zip', ''),
            'business_country' => get_option('fs_business_country', ''),
            'business_logo' => get_option('fs_business_logo', ''),
            'business_logo_light' => get_option('fs_business_logo_light', ''),
            'invoice_primary_color' => get_option('fs_invoice_primary_color', '#2271b1'),
            'invoice_primary_color_mode' => get_option('fs_invoice_primary_color_mode', 'solid'),
            'invoice_primary_color_2' => get_option('fs_invoice_primary_color_2', '#1a5276'),
            'invoice_gradient_direction' => get_option('fs_invoice_gradient_direction', '135'),
            'contractor_signature' => get_option('fs_contractor_signature', ''),
            'contractor_signer_name' => get_option('fs_contractor_signer_name', ''),
            'contractor_signer_title' => get_option('fs_contractor_signer_title', ''),
        );
    }
}
