<?php

namespace routes;

use classes\authentication;
use classes\economic;
use classes\invoice_store;
use objects\collected_order_invoices_o;
use objects\economic_module_orders;
use objects\logs_o;
use objects\orders_o;
use objects\users_o;
use traits\route_t;

class invoicesRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/invoices/draft', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('get_invoice_draft');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the invoice id is set
                if (!(string)$this->fromRequest('id')) {
                    $response->error('id parameter is required', 400);
                }
                // Create economic object
                $economic = new economic();
                // Get the draft invoice
                $result = $economic->invoices->draft->get($this->fromRequest('id'));
                if (isset($result->message)) {
                    $response->error($result->message, $result->httpStatusCode);
                }

                // Log the incident
                (new logs_o())->add('invoices', 'global', 1, $user->id, 'GET_INVOICE', 'Successfully retrieved invoice');
                // Return the list of departments
                $response->success(
                    $economic->invoices->draft->get($this->fromRequest('id'))
                );
            } else {
                // Log the incident
                (new logs_o())->add('orders', 'global', 1, 0, 'LIST_ORDERS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'get_invoice_draft' => 'Get invoice draft'
            ]
        );

        $this->post('/invoices/draft/close', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('close_invoice_draft');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the invoice id is set
                if (!$this->fromRequest('id')) {
                    $response->error('id parameter is required', 400);
                }
                // Create economic object
                $economic_module_orders = new economic_module_orders();
                // Get the user object from the draft invoice id
                /** @var users_o $target_user */
                $target_user = $economic_module_orders->getUserFromDraftId($this->fromRequest('id'));
                // Get the draft invoice
                $target_user->unsetOpenInvoiceDraft();
                // Log the incident
                (new logs_o())->add('invoices', 'global', 1, $user->id, 'CLOSE_INVOICE', 'Successfully closed invoice');
                // Return the list of departments
                $response->success(
                    ['message' => 'Invoice closed']
                );
            } else {
                // Log the incident
                (new logs_o())->add('orders', 'global', 1, 0, 'LIST_ORDERS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'close_invoice_draft' => 'Close invoice draft'
            ]
        );

        $this->get('/invoices/pdf', function () {
            // Require the user to be logged in
            global $response;
            $this->requirePermission('get_invoice_pdf');
            // Get the user object
            $user = (new authentication())->get_user();
            // Check if the request was successful
            if ($user) {
                // Check if the invoice id is set
                if (!$this->fromRequest('id')) {
                    $response->error('id parameter is required', 400);
                }
                // Get the collected order invoice object
                $collected_order_invoice = (new collected_order_invoices_o())->select((int)$this->fromRequest('id'));
                // Make sure the user owns the invoice
                if ((int)$collected_order_invoice->customer_number->value() !== (int)$user->customer_number->value()) {
                    $response->error('You do not have permission to access this invoice', 403);
                }
                // Check if the invoice is booked
                $is_booked = $collected_order_invoice->isBooked();
                if (!$is_booked) {
                    $response->error('Invoice is not booked yet', 400);
                }
                $booked_invoice_id = (int)$collected_order_invoice->booked_invoice_id->value();
                // Create economic object
                $economic = new economic();
                // Get the draft invoice
                $invoicePathFile = $economic->invoices->pdf->get($booked_invoice_id);
                // Add the pdf to the invoice store
                $invoice_store = new invoice_store();
                $invoice_store->uploadFile('invoice_' . $booked_invoice_id . '.pdf', $invoicePathFile);

                // Log the incident
                (new logs_o())->add('invoices', 'global', 1, $user->id, 'GET_INVOICE_PDF', 'Successfully retrieved invoice pdf');
                // Remove the file
                unlink($invoicePathFile);
                // Return the download link
                $response->success(
                    ['message' => 'Invoice PDF retrieved', 'url' => $invoice_store->getInvoiceDownloadUrl($booked_invoice_id)]
                );
            } else {
                // Log the incident
                (new logs_o())->add('orders', 'global', 1, 0, 'LIST_ORDERS', 'No user found, or invalid session');
                // Return an error
                $response->error('Invalid session', 400);
            }
        },
            [
                'get_invoice_pdf' => 'Get invoice pdf'
            ]
        );
    }
}