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

class FS_Contracts_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 'sign':
                $this->sign($id);
                break;
            case 'create_invoice':
                $this->create_invoice($id);
                break;
            case 'complete':
                $this->complete($id);
                break;
            default:
                $this->index();
                break;
        }
    }

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

        $action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
        $id = isset($_POST['contract_id']) ? intval($_POST['contract_id']) : 0;
        
        // Validate required fields
        if (empty($_POST['client_id']) || intval($_POST['client_id']) === 0) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=add&message=error&error=no_client'));
            exit;
        }
        
        if (empty($_POST['title'])) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=add&message=error&error=no_title'));
            exit;
        }

        // 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 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(
            'proposal_id' => isset($_POST['proposal_id']) ? intval($_POST['proposal_id']) : null,
            'client_id' => intval($_POST['client_id']),
            'title' => sanitize_text_field(wp_unslash($_POST['title'])),
            'services' => $services,
            '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'] ?? '')),
            'enabled_sections' => isset($_POST['enabled_sections']) ? array_map('sanitize_text_field', $_POST['enabled_sections']) : array(),
            'start_date' => sanitize_text_field(wp_unslash($_POST['start_date'] ?? '')),
            'end_date' => sanitize_text_field(wp_unslash($_POST['end_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,
            'client_contact_id' => (!empty($_POST['client_contact_id']) && $_POST['client_contact_id'] !== 'custom') ? intval($_POST['client_contact_id']) : null,
            'contact_name' => !empty($_POST['contact_name']) ? sanitize_text_field(wp_unslash($_POST['contact_name'])) : null,
            'contact_email' => !empty($_POST['contact_email']) ? sanitize_email(wp_unslash($_POST['contact_email'])) : null,
            'contact_phone' => !empty($_POST['contact_phone']) ? sanitize_text_field(wp_unslash($_POST['contact_phone'])) : null,
        );

        if ($action === 'update' && $id) {
            $result = FS_Contract::update($id, $data);
            $message = $result !== false ? 'updated' : 'error';
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $id . '&message=' . $message));
        } else {
            // Check free plan active contract limit before creating
            if ( function_exists( 'fs_studio_limit_reached' ) && fs_studio_limit_reached( 'active_contracts' ) ) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=limit_reached'));
                exit;
            }
            
            $contract_id = FS_Contract::create($data);
            if ($contract_id) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $contract_id . '&message=created'));
            } else {
                // Log the error for debugging
                global $wpdb;
                error_log('Freelance Studio - Contract creation failed. Last DB error: ' . $wpdb->last_error);
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=add&message=error'));
            }
        }
        exit;
    }

    /**
     * List all contracts
     */
    public function index() {
        // Handle archive/unarchive actions
        if (isset($_GET['do_archive']) && isset($_GET['id']) && wp_verify_nonce($_GET['_wpnonce'] ?? '', 'fs_archive_contract')) {
            $id = intval($_GET['id']);
            FS_Contract::archive($id);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=archived'));
        }
        if (isset($_GET['do_unarchive']) && isset($_GET['id']) && wp_verify_nonce($_GET['_wpnonce'] ?? '', 'fs_unarchive_contract')) {
            $id = intval($_GET['id']);
            FS_Contract::unarchive($id);
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&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;
        }
        
        $contracts = FS_Contract::get_all($args);
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Contract::get_statuses();
        $active_count = FS_Contract::get_count(false);
        $archived_count = FS_Contract::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_Contract::count($count_args);
        $total_pages = ceil($total_items / $per_page);
        
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $messages = array(
            'created' => __('Contract created successfully.', 'freelance-studio'),
            'updated' => __('Contract updated successfully.', 'freelance-studio'),
            'deleted' => __('Contract deleted successfully.', 'freelance-studio'),
            'sent' => __('Contract sent successfully! The client will receive an email with a link to review and sign.', 'freelance-studio'),
            'sent_no_email' => __('Contract marked as sent, but email delivery failed. Consider using an SMTP plugin or share the link manually.', 'freelance-studio'),
            'duplicated' => __('Contract duplicated successfully.', 'freelance-studio'),
            'signed' => __('Contract has been signed.', 'freelance-studio'),
            'error' => __('An error occurred. Please try again.', 'freelance-studio'),
            'archived' => __('Contract archived successfully.', 'freelance-studio'),
            'unarchived' => __('Contract restored from archive.', 'freelance-studio'),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/contracts/list.php';
    }

    /**
     * Add new contract form
     */
    public function add() {
        $contract = null;
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Contract::get_statuses();
        $frequencies = FS_Contract::get_billing_frequencies();
        $next_contract_number = FS_Contract::generate_contract_number();
        $is_new = true;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        // Check if creating from proposal
        $proposal_id = isset($_GET['proposal_id']) ? intval($_GET['proposal_id']) : 0;
        $proposal = null;
        $selected_client_id = 0;
        
        if ($proposal_id) {
            $proposal = FS_Proposal::get($proposal_id);
            if ($proposal) {
                $selected_client_id = $proposal->client_id;
            }
        } elseif (isset($_GET['client_id'])) {
            $selected_client_id = intval($_GET['client_id']);
        }
        
        // Default values
        $default_hourly_rate = get_option('fs_default_hourly_rate', 65);
        $default_valid_days = get_option('fs_contract_valid_days', 30);
        $default_terms = FS_Contract::get_default_terms();
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/contracts/form.php';
    }

    /**
     * Edit contract form
     */
    public function edit($id) {
        $contract = FS_Contract::get($id);
        
        if (!$contract) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=not_found'));
            exit;
        }
        
        $clients = FS_Client::get_for_dropdown();
        $statuses = FS_Contract::get_statuses();
        $frequencies = FS_Contract::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);
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/contracts/form.php';
    }

    /**
     * View contract (preview)
     */
    public function view($id) {
        $contract = FS_Contract::get($id);
        
        if (!$contract) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=not_found'));
            exit;
        }
        
        $client = FS_Client::get($contract->client_id);
        $settings = $this->get_business_settings();
        $statuses = FS_Contract::get_statuses();
        $frequencies = FS_Contract::get_billing_frequencies();
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        $messages = array(
            'created' => __('Contract created successfully.', 'freelance-studio'),
            'updated' => __('Contract updated successfully.', 'freelance-studio'),
            'sent' => __('Contract sent successfully! The client will receive an email with a link to review and sign.', 'freelance-studio'),
            'sent_no_email' => __('Contract marked as sent, but email delivery failed. Consider using an SMTP plugin or share the link manually below.', 'freelance-studio'),
            'signed' => __('Contract has been signed by the client.', 'freelance-studio'),
            'completed' => __('Contract marked as complete.', 'freelance-studio'),
            'cannot_complete' => __('Only signed contracts can be marked as complete.', 'freelance-studio'),
            'invoice_error' => __('Could not create invoice. Please check the contract has services defined.', 'freelance-studio'),
        );
        
        // Get linked invoices
        $linked_invoices = FS_Invoice::get_by_contract($id);
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/contracts/view.php';
    }

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

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

    /**
     * Generate PDF for contract
     */
    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-contracts&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();
        }
        
        $contract = FS_Contract::get($id);
        
        if (!$contract) {
            wp_die(esc_html__('Contract not found', 'freelance-studio'));
        }
        
        $client = FS_Client::get($contract->client_id);
        
        FS_PDF_Service::generate_contract($contract, $client);
    }

    /**
     * Counter-sign the contract (freelancer signature)
     */
    public function sign($id) {
        $contract = FS_Contract::get($id);
        
        if (!$contract) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=not_found'));
            exit;
        }
        
        // This would typically open a modal or signature pad
        // For now, redirect to view with sign mode
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $id . '&mode=sign'));
        exit;
    }

    /**
     * Create invoice from contract
     */
    public function create_invoice($id) {
        $contract = FS_Contract::get($id);
        
        if (!$contract) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=not_found'));
            exit;
        }
        
        // Get invoice type from query string
        $invoice_type = isset($_GET['type']) ? sanitize_text_field($_GET['type']) : 'full';
        
        // Create the invoice
        $invoice_id = FS_Invoice::create_from_contract($contract, $invoice_type);
        
        if ($invoice_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $invoice_id . '&message=created_from_contract'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $id . '&message=invoice_error'));
        }
        exit;
    }

    /**
     * Mark contract as complete
     */
    public function complete($id) {
        $contract = FS_Contract::get($id);
        
        if (!$contract) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&message=not_found'));
            exit;
        }
        
        // Only signed contracts can be completed
        if ($contract->status !== FS_Contract::STATUS_SIGNED) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $id . '&message=cannot_complete'));
            exit;
        }
        
        $result = FS_Contract::update($id, array('status' => FS_Contract::STATUS_COMPLETED));
        
        if ($result !== false) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $id . '&message=completed'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-contracts&action=view&id=' . $id . '&message=error'));
        }
        exit;
    }

    /**
     * Get business settings for contract 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', ''),
        );
    }
}
