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

class FS_Expenses_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 'duplicate':
                $this->duplicate($id);
                break;
            default:
                $this->index();
                break;
        }
    }

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

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

        $data = array(
            'project_id' => !empty($_POST['project_id']) ? intval($_POST['project_id']) : null,
            'expense_date' => sanitize_text_field(wp_unslash($_POST['expense_date'])),
            'expense_name' => sanitize_text_field(wp_unslash($_POST['expense_name'])),
            'category' => sanitize_text_field(wp_unslash($_POST['category'])),
            'amount' => floatval($_POST['amount']),
            'is_billable' => isset($_POST['is_billable']) ? 1 : 0,
            'is_reimbursable' => isset($_POST['is_reimbursable']) ? 1 : 0,
            'is_recurring' => isset($_POST['is_recurring']) ? 1 : 0,
            'recurring_frequency' => isset($_POST['recurring_frequency']) ? sanitize_text_field(wp_unslash($_POST['recurring_frequency'])) : null,
            'recurring_day' => !empty($_POST['recurring_day']) ? intval($_POST['recurring_day']) : null,
            'recurring_end_date' => !empty($_POST['recurring_end_date']) ? sanitize_text_field(wp_unslash($_POST['recurring_end_date'])) : null,
            'notes' => sanitize_textarea_field(wp_unslash($_POST['notes'])),
        );

        if ($action === 'update' && $id) {
            $result = FS_Expense::update($id, $data);
            
            // Handle receipt deletion
            if (isset($_POST['delete_receipt']) && $_POST['delete_receipt'] == '1') {
                $receipt_info = FS_Expense::get_receipt_info($id);
                if ($receipt_info) {
                    FS_File_Handler::delete_receipt($receipt_info['attachment_id'], $id);
                }
            }
            
            // Handle new receipt upload
            if (!empty($_FILES['receipt_file']['name'])) {
                $upload_result = FS_File_Handler::handle_upload($_FILES['receipt_file'], $id);
                if (!is_wp_error($upload_result)) {
                    FS_Expense::update_receipt($id, $upload_result);
                }
            }
            
            $message = $result !== false ? 'updated' : 'error';
            
            // Redirect back to project if we came from there
            if ($from_project) {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-projects&action=view&id=' . $from_project . '&tab=expenses&message=' . $message));
            } else {
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $id . '&message=' . $message));
            }
        } else {
            $expense_id = FS_Expense::create($data);
            if ($expense_id) {
                // Handle receipt upload for new expense
                if (!empty($_FILES['receipt_file']['name'])) {
                    $upload_result = FS_File_Handler::handle_upload($_FILES['receipt_file'], $expense_id);
                    if (!is_wp_error($upload_result)) {
                        FS_Expense::update_receipt($expense_id, $upload_result);
                    }
                }
                
                // Redirect back to project if we came from there, otherwise go to expense list
                if ($from_project) {
                    FS_Admin::safe_redirect(admin_url('admin.php?page=fs-projects&action=view&id=' . $from_project . '&tab=expenses&message=expense_created'));
                } else {
                    FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&message=created'));
                }
            } else {
                if ($from_project) {
                    FS_Admin::safe_redirect(admin_url('admin.php?page=fs-projects&action=view&id=' . $from_project . '&tab=expenses&message=error'));
                } else {
                    FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&message=error'));
                }
            }
        }
        exit;
    }

    /**
     * List all expenses
     */
    public function index() {
        $category_filter = isset($_GET['category']) ? sanitize_text_field($_GET['category']) : null;
        $project_filter = isset($_GET['project_id']) ? intval($_GET['project_id']) : null;
        $start_date = isset($_GET['start_date']) ? sanitize_text_field($_GET['start_date']) : null;
        $end_date = isset($_GET['end_date']) ? sanitize_text_field($_GET['end_date']) : null;
        
        // 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(
            'limit' => $per_page,
            'offset' => $offset,
        );
        $count_args = array();
        if ($category_filter) {
            $args['category'] = $category_filter;
            $count_args['category'] = $category_filter;
        }
        if ($project_filter) {
            $args['project_id'] = $project_filter;
            $count_args['project_id'] = $project_filter;
        }
        if ($start_date) {
            $args['start_date'] = $start_date;
            $count_args['start_date'] = $start_date;
        }
        if ($end_date) {
            $args['end_date'] = $end_date;
            $count_args['end_date'] = $end_date;
        }
        
        $expenses = FS_Expense::get_all($args);
        $total_items = FS_Expense::count($count_args);
        $total_pages = ceil($total_items / $per_page);
        
        $categories = FS_Expense::get_categories();
        $projects = FS_Project::get_for_dropdown();
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        // Get summary by category for the filter period
        $category_totals = FS_Expense::get_by_category($start_date, $end_date);
        $total_expenses = array_reduce($category_totals, function($carry, $cat) {
            return $carry + floatval($cat->total);
        }, 0);
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/expenses/list.php';
    }

    /**
     * Add new expense form
     */
    public function add() {
        $expense = null;
        $categories = FS_Expense::get_categories();
        $projects = FS_Project::get_for_dropdown();
        $is_new = true;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        // Pre-select project if passed in URL
        $selected_project_id = isset($_GET['project_id']) ? intval($_GET['project_id']) : 0;
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/expenses/form.php';
    }

    /**
     * Edit expense form
     */
    public function edit($id) {
        $expense = FS_Expense::get($id);
        
        if (!$expense) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&message=not_found'));
            exit;
        }
        
        $categories = FS_Expense::get_categories();
        $projects = FS_Project::get_for_dropdown();
        $receipt_info = FS_Expense::get_receipt_info($id);
        $is_new = false;
        $message = isset($_GET['message']) ? sanitize_text_field($_GET['message']) : '';
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/expenses/form.php';
    }

    /**
     * Duplicate an expense
     */
    public function duplicate($id) {
        $expense = FS_Expense::get($id);
        
        if (!$expense) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&message=not_found'));
            exit;
        }
        
        $data = array(
            'project_id' => $expense->project_id,
            'expense_date' => current_time('Y-m-d'),
            'expense_name' => $expense->expense_name . ' (copy)',
            'category' => $expense->category,
            'amount' => $expense->amount,
            'is_billable' => $expense->is_billable,
            'is_reimbursable' => $expense->is_reimbursable,
            'is_recurring' => $expense->is_recurring,
            'recurring_frequency' => $expense->recurring_frequency,
            'recurring_day' => $expense->recurring_day,
            'recurring_end_date' => $expense->recurring_end_date,
            'notes' => $expense->notes,
        );
        
        $new_id = FS_Expense::create($data);
        
        if ($new_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&action=edit&id=' . $new_id . '&message=duplicated'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=expenses&message=error'));
        }
        exit;
    }
}
