<?php
/**
 * Finances Controller
 * 
 * Routes to the appropriate sub-controller based on the active tab.
 * Handles the unified Finances menu (Invoices, Recurring, Other Income, 
 * Expenses, Reporting, Tax, Bank Transactions).
 *
 * @package Freelance_Studio
 */

class FS_Finances_Controller {

    /**
     * Handle the request
     */
    public function handle_request() {
        $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'invoices';

        // Handle POST requests BEFORE any output (redirects need clean headers)
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if ($tab === 'tax') {
                $this->handle_tax_post();
                return;
            }
            // For other tabs, let the sub-controller handle the POST
            // These all redirect via safe_redirect() which cleans output buffers
            $this->route_to_sub_controller($tab);
            return;
        }

        // Set context flag so sub-views skip their own wrap/h1
        $GLOBALS['fs_in_finances'] = true;

        // Open the finances layout (wrap, h1, sidebar nav, content div)
        include JEEB_FS_PLUGIN_DIR . 'includes/views/finances/index.php';

        // Render sub-content inside the finances content area
        $this->route_to_sub_controller($tab);

        // Close: fs-settings-content, fs-settings-layout, wrap
        echo '</div></div></div>';

        unset($GLOBALS['fs_in_finances']);
    }

    /**
     * Route to the appropriate sub-controller based on tab
     */
    private function route_to_sub_controller($tab) {
        switch ($tab) {
            case 'invoices':
                $controller = new FS_Invoices_Controller();
                $controller->handle_request();
                break;

            case 'recurring':
                if (function_exists('fs_studio_is_free_plan') && fs_studio_is_free_plan()) {
                    $upgrade_url = function_exists('freelance_studio_fs') ? freelance_studio_fs()->get_upgrade_url() : '#';
                    ?>
                    <div class="fs-premium-required">
                        <div class="fs-premium-required-icon"><?php echo esc_html('🔄'); ?></div>
                        <h1><?php esc_html_e('Recurring Invoices', 'freelance-studio'); ?></h1>
                        <p><?php esc_html_e('Automate your billing with recurring invoice schedules for retainer clients and ongoing projects.', 'freelance-studio'); ?></p>
                        <a href="<?php echo esc_url($upgrade_url); ?>" class="fs-btn fs-btn-primary" style="margin-top:16px;">
                            <?php esc_html_e('Upgrade to Pro', 'freelance-studio'); ?>
                        </a>
                        <p class="fs-premium-help">
                            <?php esc_html_e('All Pro features include a 14-day free trial — no credit card required.', 'freelance-studio'); ?>
                        </p>
                    </div>
                    <?php
                } else {
                    $controller = new FS_Recurring_Invoices_Controller();
                    $controller->handle_request();
                }
                break;

            case 'income':
                $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
                switch ($action) {
                    case 'add':
                        $_GET['action'] = 'add_income';
                        break;
                    case 'edit':
                        $_GET['action'] = 'edit_income';
                        break;
                    case 'duplicate':
                        $_GET['action'] = 'duplicate_income';
                        break;
                    default:
                        $_GET['action'] = 'income';
                        break;
                }
                $controller = new FS_Invoices_Controller();
                $controller->handle_request();
                break;

            case 'expenses':
                $controller = new FS_Expenses_Controller();
                $controller->handle_request();
                break;

            case 'reporting':
                $controller = new FS_Reporting_Controller();
                $controller->index();
                break;

            case 'tax':
                $this->render_tax();
                break;

            case 'transactions':
                $this->render_transactions();
                break;

            default:
                $controller = new FS_Invoices_Controller();
                $controller->handle_request();
                break;
        }
    }

    /**
     * Handle POST requests for the Tax tab
     */
    private function handle_tax_post() {
        ob_start();

        if (isset($_POST['fs_settings_nonce'])) {
            // Tax settings (state, federal bracket, filing status)
            $this->save_tax_settings();
        } elseif (isset($_POST['fs_deduction_nonce'])) {
            $this->save_annual_deduction();
        } elseif (isset($_POST['fs_copy_nonce'])) {
            $this->copy_deductions();
        } elseif (isset($_POST['fs_quarterly_nonce'])) {
            $this->save_quarterly_payments();
        } elseif (isset($_POST['fs_tax_reminder_nonce'])) {
            $this->save_tax_reminder_settings();
        } else {
            ob_end_clean();
            $this->render_tax();
        }
    }

    /**
     * Save tax settings (state, federal bracket, filing status)
     */
    private function save_tax_settings() {
        if (!wp_verify_nonce($_POST['fs_settings_nonce'], 'fs_save_settings')) {
            ob_end_clean();
            wp_die(__('Security check failed.', 'freelance-studio'));
        }

        if (isset($_POST['fs_tax_state'])) {
            update_option('fs_tax_state', sanitize_text_field($_POST['fs_tax_state']));
        }
        if (isset($_POST['fs_federal_tax_bracket'])) {
            update_option('fs_federal_tax_bracket', floatval($_POST['fs_federal_tax_bracket']));
        }
        if (isset($_POST['fs_filing_status'])) {
            update_option('fs_filing_status', sanitize_text_field($_POST['fs_filing_status']));
        }
        if (isset($_POST['fs_quarterly_tax_enabled'])) {
            update_option('fs_quarterly_tax_enabled', '1');
        } else {
            update_option('fs_quarterly_tax_enabled', '0');
        }

        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&message=saved'));
    }

    /**
     * Save annual deduction
     */
    private function save_annual_deduction() {
        if (!wp_verify_nonce($_POST['fs_deduction_nonce'], 'fs_save_annual_deduction')) {
            ob_end_clean();
            wp_die(__('Security check failed.', 'freelance-studio'));
        }

        $deduction_id = isset($_POST['deduction_id']) ? intval($_POST['deduction_id']) : 0;
        $year = isset($_POST['deduction_year']) ? intval($_POST['deduction_year']) : intval(gmdate('Y'));

        $data = array(
            'year'                 => $year,
            'name'                 => sanitize_text_field(wp_unslash($_POST['deduction_name'])),
            'category'             => sanitize_text_field(wp_unslash($_POST['deduction_category'])),
            'annual_amount'        => floatval($_POST['deduction_amount']),
            'deduction_percentage' => isset($_POST['deduction_percentage']) ? floatval($_POST['deduction_percentage']) : 100,
            'notes'                => isset($_POST['deduction_notes']) ? sanitize_textarea_field(wp_unslash($_POST['deduction_notes'])) : '',
            'is_active'            => isset($_POST['deduction_active']) ? 1 : 1,
        );

        if ($deduction_id) {
            FS_Annual_Deduction::update($deduction_id, $data);
        } else {
            FS_Annual_Deduction::create($data);
        }

        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $year . '&message=saved'));
    }

    /**
     * Copy deductions from previous year
     */
    private function copy_deductions() {
        if (!wp_verify_nonce($_POST['fs_copy_nonce'], 'fs_copy_deductions')) {
            ob_end_clean();
            wp_die(__('Security check failed.', 'freelance-studio'));
        }

        $from_year = intval($_POST['from_year']);
        $to_year = intval($_POST['to_year']);

        $source_deductions = FS_Annual_Deduction::get_all($from_year);
        foreach ($source_deductions as $deduction) {
            FS_Annual_Deduction::create(array(
                'category'             => $deduction->category,
                'name'                 => $deduction->name,
                'annual_amount'        => $deduction->annual_amount,
                'deduction_percentage' => $deduction->deduction_percentage,
                'notes'                => isset($deduction->notes) ? $deduction->notes : '',
                'year'                 => $to_year,
                'user_id'              => get_current_user_id(),
            ));
        }

        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $to_year . '&message=saved'));
    }

    /**
     * Save quarterly tax payments
     */
    private function save_quarterly_payments() {
        if (!wp_verify_nonce($_POST['fs_quarterly_nonce'], 'fs_save_quarterly_payment')) {
            ob_end_clean();
            wp_die(__('Security check failed.', 'freelance-studio'));
        }

        $year = isset($_POST['payment_year']) ? intval($_POST['payment_year']) : intval(gmdate('Y'));
        $payments = isset($_POST['payments']) ? $_POST['payments'] : array();

        foreach ($payments as $quarter => $data) {
            $amount = isset($data['amount']) ? floatval($data['amount']) : 0;
            $date = isset($data['date']) && !empty($data['date']) ? sanitize_text_field($data['date']) : null;

            if ($amount > 0 || $date) {
                FS_Tax_Calculator::record_payment($year, $quarter, $amount, $date);
            }
        }

        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $year . '&message=saved'));
    }

    /**
     * Save tax reminder settings
     */
    private function save_tax_reminder_settings() {
        if (!wp_verify_nonce($_POST['fs_tax_reminder_nonce'], 'fs_save_tax_reminder_settings')) {
            ob_end_clean();
            wp_die(__('Security check failed.', 'freelance-studio'));
        }

        $enabled = isset($_POST['fs_quarterly_tax_reminder_enabled']) ? '1' : '0';
        update_option('fs_quarterly_tax_reminder_enabled', $enabled);

        if (isset($_POST['fs_quarterly_tax_reminder_days'])) {
            update_option('fs_quarterly_tax_reminder_days', intval($_POST['fs_quarterly_tax_reminder_days']));
        }

        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&message=saved'));
    }

    /**
     * Render the Tax page (consolidated from Settings + Reporting)
     */
    private function render_tax() {
        // Gather all tax-related data
        $current_year = gmdate('Y');
        $selected_year = isset($_GET['year']) ? intval($_GET['year']) : intval($current_year);
        $show_success = isset($_GET['message']) && $_GET['message'] === 'saved';

        // Tax settings
        $tax_state = get_option('fs_tax_state', '');
        $federal_bracket = get_option('fs_federal_tax_bracket', 22);
        $filing_status = get_option('fs_filing_status', 'single');
        $quarterly_tax_enabled = get_option('fs_quarterly_tax_enabled', '0');
        $states = FS_Tax_Rates::get_states();

        // Annual deductions
        $annual_deductions = FS_Annual_Deduction::get_all($selected_year);
        $deduction_categories = FS_Annual_Deduction::get_categories();
        $deduction_presets = FS_Annual_Deduction::get_presets();
        $editing_deduction = isset($_GET['edit_deduction']) ? FS_Annual_Deduction::get(intval($_GET['edit_deduction'])) : null;
        $total_deductions = FS_Annual_Deduction::get_total($selected_year);

        // Tax calculation data
        $reporting_controller = new FS_Reporting_Controller();
        $tax_data = $reporting_controller->get_tax_data_public($selected_year);

        // Quarterly tax records
        $user_id = get_current_user_id();
        $quarterly_records = FS_Quarterly_Tax::get_year_records($user_id, $selected_year);

        // Available years for dropdown
        global $wpdb;
        $inv_table = $wpdb->prefix . 'fs_invoices';
        $exp_table = $wpdb->prefix . 'fs_expenses';
        $available_years = array();
        $inv_years = $wpdb->get_col("SELECT DISTINCT YEAR(issue_date) FROM {$inv_table} WHERE issue_date IS NOT NULL AND issue_date != '0000-00-00'");
        $exp_years = $wpdb->get_col("SELECT DISTINCT YEAR(date) FROM {$exp_table} WHERE date IS NOT NULL AND date != '0000-00-00'");
        $available_years = array_unique(array_merge($inv_years, $exp_years, array($current_year)));
        sort($available_years);

        // Tax reminder settings
        $reminder_enabled = get_option('fs_quarterly_tax_reminder_enabled', '0');
        $reminder_days = get_option('fs_quarterly_tax_reminder_days', 14);

        include JEEB_FS_PLUGIN_DIR . 'includes/views/finances/tax.php';
    }

    /**
     * Render the Bank Transactions page
     */
    private function render_transactions() {
        // Handle batch delete
        if (isset($_GET['delete_batch']) && isset($_GET['_wpnonce'])) {
            $batch = sanitize_text_field($_GET['delete_batch']);
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_batch_' . $batch)) {
                FS_Transaction::delete_batch($batch);
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=transactions&deleted_batch=1'));
                exit;
            }
        }

        include JEEB_FS_PLUGIN_DIR . 'includes/views/finances/transactions.php';
    }
}
