<?php
/**
 * Recurring Invoices Controller
 *
 * @package Freelance_Studio
 */

class FS_Recurring_Invoices_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 'view':
                $this->view($id);
                break;
            case 'generate':
                $this->generate_now($id);
                break;
            default:
                $this->index();
                break;
        }
    }

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

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

        // Build items array
        $items = array();
        if (!empty($_POST['item_description'])) {
            foreach ($_POST['item_description'] as $key => $desc) {
                if (empty($desc)) continue;
                
                $qty = isset($_POST['item_quantity'][$key]) ? floatval($_POST['item_quantity'][$key]) : 1;
                $rate = isset($_POST['item_rate'][$key]) ? floatval($_POST['item_rate'][$key]) : 0;
                
                $items[] = array(
                    'description' => sanitize_text_field($desc),
                    'quantity' => $qty,
                    'rate' => $rate,
                    'amount' => $qty * $rate,
                );
            }
        }

        // Calculate total amount
        $amount = 0;
        foreach ($items as $item) {
            $amount += $item['amount'];
        }

        $data = array(
            'client_id' => intval($_POST['client_id']),
            'project_id' => !empty($_POST['project_id']) ? intval($_POST['project_id']) : null,
            'name' => sanitize_text_field(wp_unslash($_POST['name'])),
            'frequency' => sanitize_text_field(wp_unslash($_POST['frequency'])),
            'amount' => $amount,
            'items' => $items,
            'next_invoice_date' => !empty($_POST['next_invoice_date']) ? sanitize_text_field(wp_unslash($_POST['next_invoice_date'])) : null,
            'end_date' => !empty($_POST['end_date']) ? sanitize_text_field(wp_unslash($_POST['end_date'])) : null,
            'status' => sanitize_text_field(wp_unslash($_POST['status'])),
            'auto_send' => isset($_POST['auto_send']) ? 1 : 0,
            'include_time_entries' => isset($_POST['include_time_entries']) ? 1 : 0,
            'time_grouping' => isset($_POST['time_grouping']) ? sanitize_text_field(wp_unslash($_POST['time_grouping'])) : 'task',
            'mark_time_invoiced' => isset($_POST['mark_time_invoiced']) ? 1 : 0,
        );

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

        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=recurring&action=view&id=' . $redirect_id . '&message=saved'));
        exit;
    }

    /**
     * List all recurring invoices
     */
    private function index() {
        // Get filters
        $status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';
        $client_id = isset($_GET['client_id']) ? intval($_GET['client_id']) : 0;

        $args = array();
        if ($status) {
            $args['status'] = $status;
        }
        if ($client_id) {
            $args['client_id'] = $client_id;
        }

        $recurring_invoices = FS_Recurring_Invoice::get_all($args);
        $clients = FS_Client::get_all(array('orderby' => 'name', 'order' => 'ASC'));
        $statuses = FS_Recurring_Invoice::get_statuses();
        $frequencies = FS_Recurring_Invoice::get_frequencies();

        // Count by status
        $counts = array(
            'all' => FS_Recurring_Invoice::count(),
            'active' => FS_Recurring_Invoice::count(array('status' => 'active')),
            'paused' => FS_Recurring_Invoice::count(array('status' => 'paused')),
        );

        include JEEB_FS_PLUGIN_DIR . 'includes/views/recurring-invoices/list.php';
    }

    /**
     * Add/Edit form
     */
    private function form($id = 0) {
        $recurring = $id ? FS_Recurring_Invoice::get($id) : null;
        $clients = FS_Client::get_all(array('orderby' => 'name', 'order' => 'ASC'));
        $projects = FS_Project::get_all(array('orderby' => 'name', 'order' => 'ASC'));
        $statuses = FS_Recurring_Invoice::get_statuses();
        $frequencies = FS_Recurring_Invoice::get_frequencies();

        // Parse items
        $items = array();
        if ($recurring && $recurring->items) {
            $items = json_decode($recurring->items, true) ?: array();
        }

        include JEEB_FS_PLUGIN_DIR . 'includes/views/recurring-invoices/form.php';
    }

    /**
     * View single recurring invoice
     */
    private function view($id) {
        $recurring = FS_Recurring_Invoice::get($id);
        
        if (!$recurring) {
            wp_die(esc_html__('Recurring invoice not found', 'freelance-studio'));
        }

        $statuses = FS_Recurring_Invoice::get_statuses();
        $frequencies = FS_Recurring_Invoice::get_frequencies();
        $items = json_decode($recurring->items, true) ?: array();
        $generated_invoices = FS_Recurring_Invoice::get_generated_invoices($id);

        include JEEB_FS_PLUGIN_DIR . 'includes/views/recurring-invoices/view.php';
    }

    /**
     * Generate invoice now
     */
    private function generate_now($id) {
        $invoice_id = FS_Recurring_Invoice::generate_invoice($id);
        
        if ($invoice_id) {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=invoices&action=edit&id=' . $invoice_id . '&message=generated'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=recurring&action=view&id=' . $id . '&error=generate_failed'));
        }
        exit;
    }
}
