<commit_before><?php

namespace App\Controllers;

use App\Facades\Messages;
use App\Facades\Utils;
use App\Models\Clients;
use App\Models\Products;
use App\Models\Receipts;
use App\Models\ReceiptsProducts;
use App\Models\Settings;
use Silver\Core\Controller;
use Silver\Database\Query;
use Silver\Http\Request;
use Silver\Http\View;

/**
 * generating controller
 */
class GeneratingController extends Controller {
    
    public function index() {
        return View::make('generating')
                   ->with('receiptNumber', $this->getLastReceiptNumber())
                   ->with('receiptDate',  Utils::dateNow($this->getDateFormat()));
    }
    
    private function getLastReceiptNumber() {
        $lastReceipt = Receipts::query()
                               ->orderBy('receipt_number', 'desc')
                               ->first();
        
        if ($lastReceipt) {
            return intval($lastReceipt->receipt_number) + 1;
        }
        
        return 1;
    }
    
    private function getDateFormat() {
        $dateFormat = Settings::where('option_key', '=', 'setting_date_format')
                              ->first();
        
        if (!$dateFormat) {
            return 'Y-m-d';
        }
        
        return $dateFormat->option_value;
    }
    
    public function dataPDF(Request $request) {
        if (!$request->ajax()) {
            //TODO: mensaje de error.
            return "";
        }
        
        $dataJSON = [
            'client'   => NULL,
            'products' => [],
            'receipt'  => NULL,
            'options'  => NULL,
        ];
        
        $receiptId = $request->input('receipt_id', FALSE);
        
        if ($receiptId && $receipt = Receipts::find($receiptId)) {
            $client                = Clients::find($receipt->client_id)
                                            ->data();
            $receipt->receipt_date = Utils::stringToDate($receipt->receipt_date, 'Y-m-d', $this->getDateFormat());
            $dataJSON              = [
                'client'   => $client,
                'products' => $this->getDataPDFProducts($receiptId),
                'receipt'  => $receipt->data(),
                'options'  => $this->getDataPDFSettings(),
            ];
        }
        
        return json_encode($dataJSON);
    }
    
    private function getDataPDFProducts($receiptId) {
        $receiptsProducts = ReceiptsProducts::where('receipt_id', '=', $receiptId)
                                            ->all();
        $products         = [];
        
        array_walk($receiptsProducts, function($receiptProduct) use (&$products) {
            $products[] = [
                'product'              => Products::find($receiptProduct->product_id)
                                                  ->data(),
                'receipt_product_unit' => $receiptProduct->receipt_product_unit,
            ];
        });
        
        return $products;
    }
    
    private function getDataPDFSettings() {
        $settingsQuery = Settings::query()
                                 ->all();
        $settings      = [];
        array_walk($settingsQuery, function($setting) use (&$settings) {
            $settings[$setting->option_key] = $setting->option_value;
        });
        
        return $settings;
    }
    
    public function generate(Request $request) {
        if (!$request->ajax()) {
            //TODO: mensaje de error.
            return "";
        }
        
        //[{"id":3,"receipt_product_unit":"1"}]
        $products = (array)json_decode($request->input('receipt_products', []));
        $clientId = $request->input('client_id', FALSE);
        
        if (count($products) == 0 || empty($clientId)) {
            Messages::addDanger('Por favor, seleccione un cliente y mínimo un producto.');
            
            return json_encode(FALSE);
        }
        
        if ($receipt = $this->insertReceipt($request, $products)) {
            Messages::addSuccess('Factura creada correctamente.');
            
            return json_encode(['receipt_id' => $receipt->id]);
        }
        
        return json_encode(FALSE);
    }
    
    private function insertReceipt(Request $request, $products) {
        $receipt                        = new Receipts();
        $receipt->receipt_type          = $request->input('receipt_type');
        $receipt->receipt_number        = $request->input('receipt_number');
        $receipt->receipt_date          = Utils::stringToDate($request->input('receipt_date'), $this->getDateFormat());
        $receipt->receipt_license_plate = $request->input('receipt_license_plate');
        $receipt->client_id             = $request->input('client_id');
        
        try {
            if (!($receipt = $receipt->save()) || !$this->productsClients($products, $receipt)) {
                $receipt->delete();
                $receipt = FALSE;<commit_msg>Si la factura es de tipo presupuesto, el numero de factura sera 0.<commit_after><?php

namespace App\Controllers;

use App\Facades\Messages;
use App\Facades\Utils;
use App\Models\Clients;
use App\Models\Products;
use App\Models\Receipts;
use App\Models\ReceiptsProducts;
use App\Models\Settings;
use Silver\Core\Controller;
use Silver\Database\Query;
use Silver\Http\Request;
use Silver\Http\View;

/**
 * generating controller
 */
class GeneratingController extends Controller {
    
    public function index() {
        return View::make('generating')
                   ->with('receiptNumber', $this->getLastReceiptNumber())
                   ->with('receiptDate', Utils::dateNow($this->getDateFormat()));
    }
    
    private function getLastReceiptNumber() {
        $lastReceipt = Receipts::query()
                               ->orderBy('receipt_number', 'desc')
                               ->first();
        
        if ($lastReceipt) {
            return intval($lastReceipt->receipt_number) + 1;
        }
        
        return 1;
    }
    
    private function getDateFormat() {
        $dateFormat = Settings::where('option_key', '=', 'setting_date_format')
                              ->first();
        
        if (!$dateFormat) {
            return 'Y-m-d';
        }
        
        return $dateFormat->option_value;
    }
    
    public function dataPDF(Request $request) {
        if (!$request->ajax()) {
            //TODO: mensaje de error.
            return "";
        }
        
        $dataJSON = [
            'client'   => NULL,
            'products' => [],
            'receipt'  => NULL,
            'options'  => NULL,
        ];
        
        $receiptId = $request->input('receipt_id', FALSE);
        
        if ($receiptId && $receipt = Receipts::find($receiptId)) {
            $client                = Clients::find($receipt->client_id)
                                            ->data();
            $receipt->receipt_date = Utils::stringToDate($receipt->receipt_date, 'Y-m-d', $this->getDateFormat());
            $dataJSON              = [
                'client'   => $client,
                'products' => $this->getDataPDFProducts($receiptId),
                'receipt'  => $receipt->data(),
                'options'  => $this->getDataPDFSettings(),
            ];
        }
        
        return json_encode($dataJSON);
    }
    
    private function getDataPDFProducts($receiptId) {
        $receiptsProducts = ReceiptsProducts::where('receipt_id', '=', $receiptId)
                                            ->all();
        $products         = [];
        
        array_walk($receiptsProducts, function($receiptProduct) use (&$products) {
            $products[] = [
                'product'              => Products::find($receiptProduct->product_id)
                                                  ->data(),
                'receipt_product_unit' => $receiptProduct->receipt_product_unit,
            ];
        });
        
        return $products;
    }
    
    private function getDataPDFSettings() {
        $settingsQuery = Settings::query()
                                 ->all();
        $settings      = [];
        array_walk($settingsQuery, function($setting) use (&$settings) {
            $settings[$setting->option_key] = $setting->option_value;
        });
        
        return $settings;
    }
    
    public function generate(Request $request) {
        if (!$request->ajax()) {
            //TODO: mensaje de error.
            return "";
        }
        
        //[{"id":3,"receipt_product_unit":"1"}]
        $products = (array)json_decode($request->input('receipt_products', []));
        $clientId = $request->input('client_id', FALSE);
        
        if (count($products) == 0 || empty($clientId)) {
            Messages::addDanger('Por favor, seleccione un cliente y mínimo un producto.');
            
            return json_encode(FALSE);
        }
        
        if ($receipt = $this->insertReceipt($request, $products)) {
            Messages::addSuccess('Factura creada correctamente.');
            
            return json_encode(['receipt_id' => $receipt->id]);
        }
        
        return json_encode(FALSE);
    }
    
    private function insertReceipt(Request $request, $products) {
        $receipt                        = new Receipts();
        $receipt->receipt_type          = $request->input('receipt_type');
        $receipt->receipt_number        = $request->input('receipt_number');
        $receipt->receipt_date          = Utils::stringToDate($request->input('receipt_date'), $this->getDateFormat());
        $receipt->receipt_license_plate = $request->input('receipt_license_plate');
        $receipt->client_id             = $request->input('client_id');
        
        //TODO: temporalmente
        if ($receipt->receipt_type == 'Presupuesto') {
            $receipt->receipt_number = 0;
        }
        
        try {
            if (!($receipt = $receipt->save()) || !$this->productsClients($products, $receipt)) {
                $receipt->delete();
                $receipt = FALSE;
{'fraction_non_alphanumeric': 0.13780463641767388, 'fraction_numerical': 0.0011888250445809391, 'mean_word_length': 1.6912823247134097, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 117, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5311515', 'n_tokens_mistral': 2891, 'n_tokens_neox': 2717, 'n_words': 456}