<?php

namespace App\Repositories;

use Exception;
use App\Models\PurchaseOrderHeader;
use App\Models\PurchaseOrderItems;
use App\DTOs\PurchaseOrder\PurchaseOrderUpdateDto;
use App\DTOs\PurchaseOrder\PurchaseOrderCreateDto;
use App\Repositories\Interfaces\IPurchaseOrderRepository;

class PurchaseOrderRepository implements IPurchaseOrderRepository
{
    public function paginate(array $request)
    {
        $business_information = $request['business_information'];
        $ruc = $business_information['ruc_number'];


        $query = PurchaseOrderHeader::where('status', '=', 1)->where('ruc', '=', $ruc);

        // Filtrar por fecha si está presente en la solicitud
        if (isset($request['filters']['start_date']) && isset($request['filters']['end_date'])) {
            $start_date = $request['filters']['start_date'];
            $end_date = $request['filters']['end_date'];
            $query->whereBetween('issuance_date', [$start_date, $end_date]);
        }

        if (isset($request['filters']['estado'])) {
            $estado = $request['filters']['estado'];
            $query->where('estado', '=', $estado);
        }

        if (isset($request['search'])) {
            $search = $request['search'];
            $query->where('supplier_name', 'like', '%' . $search . '%');
        }

        if (isset($request['orderby']) && isset($request['orderdir'])) {
            $orderBy = $request['orderby'];
            $orderDir = $request['orderdir'];
            $query->orderBy($orderBy, $orderDir);
        }

        if (isset($request['start']) && isset($request['length'])) {
            $start = $request['start'];
            $length = $request['length'];
            $query->skip($start)->take($length);
        }

        $purchase_orders = $query->with(['items' => function ($itemQuery) {
            $itemQuery->where('status', '=', 1);
        }])->get();

        $purchase_order_count = $query->count();

        $respuesta['total'] = $purchase_order_count;
        $respuesta['list'] = $purchase_orders;

        return $respuesta;
    }

    public function find(int $id, string $business_ruc): ?PurchaseOrderHeader
    {
        return PurchaseOrderHeader::with(['items' => function ($query) {
            $query->where('status', 1);
        }])
            ->where('ruc', $business_ruc)
            ->where('status', 1)
            ->find($id);
    }

    public function store(PurchaseOrderCreateDto $store): PurchaseOrderHeader
    {
        $entry = new PurchaseOrderHeader();

        $entry->ruc = $store->ruc;
        $entry->issuance_date = $store->issuance_date;
        $entry->num_purchase_order = $store->num_purchase_order;
        $entry->supplier_id = $store->supplier_id;
        $entry->supplier_name = $store->supplier_name;
        $entry->supplier_ruc = $store->supplier_ruc;
        $entry->currency = $store->currency;
        $entry->exchange = $store->exchange;
        $entry->affected = $store->affected;
        $entry->non_affected = $store->non_affected;
        $entry->exonerated = $store->exonerated;
        $entry->total = $store->total;
        $entry->product_discount = $store->product_discount;
        $entry->order_discount_percentage = $store->order_discount_percentage;
        $entry->order_discount_percentage_value = $store->order_discount_percentage_value;
        $entry->order_discount_no_percentage_value = $store->order_discount_no_percentage_value;
        $entry->total_discount = $store->total_discount;
        $entry->product_tax = $store->product_tax;
        $entry->order_tax_id = $store->order_tax_id;
        $entry->order_tax = $store->order_tax;
        $entry->total_tax = $store->total_tax;
        $entry->tax_ICBPER = $store->tax_ICBPER;
        $entry->mult_ICBPER = $store->mult_ICBPER;
        $entry->subtotal = $store->subtotal;
        $entry->grand_total = $store->grand_total;
        $entry->total_items = $store->total_items;
        $entry->total_quantity = $store->total_quantity;
        $entry->note = $store->note;
        $entry->rounding = $store->rounding;
        $entry->attachment = $store->attachment;
        $entry->expiration_date = $store->expiration_date;
        $entry->canal_id = $store->canal_id;
        $entry->payment_method_id = $store->payment_method_id;
        $entry->num_quotation = $store->num_quotation;
        $entry->destination_address = $store->destination_address;
        $entry->destination_ubigeo = $store->destination_ubigeo;
        $entry->supplier_address = $store->supplier_address;
        $entry->supplier_contact_name = $store->supplier_contact_name;
        $entry->supplier_contact_phone = $store->supplier_contact_phone;
        $entry->supplier_contact_email = $store->supplier_contact_email;
        $entry->estado = $store->estado;
        $entry->created_by = $store->created_by;
        $entry->updated_by = $store->updated_by;
        $entry->created_at = $store->created_at;
        $entry->updated_at = $store->updated_at;
        $entry->status = $store->status;
        $entry->save();
        $idheader = $entry->id;

        foreach ($store->items as $itemData) {
            $item = new PurchaseOrderItems();
            $itemData['purchase_order_header_id'] = $idheader;

            $item->fill($itemData);
            $item->save();
            $items[] = $item;
        }
        $entry->items = $items;

        return $entry;
    }

    public function update(PurchaseOrderUpdateDto $store): void
    {
        $entry = PurchaseOrderHeader::find($store->id);

        $entry->ruc = $store->ruc;
        $entry->issuance_date = $store->issuance_date;
        $entry->num_purchase_order = $store->num_purchase_order;
        $entry->supplier_id = $store->supplier_id;
        $entry->supplier_name = $store->supplier_name;
        $entry->supplier_ruc = $store->supplier_ruc;
        $entry->currency = $store->currency;
        $entry->exchange = $store->exchange;
        $entry->affected = $store->affected;
        $entry->non_affected = $store->non_affected;
        $entry->exonerated = $store->exonerated;
        $entry->total = $store->total;
        $entry->product_discount = $store->product_discount;
        $entry->order_discount_percentage = $store->order_discount_percentage;
        $entry->order_discount_percentage_value = $store->order_discount_percentage_value;
        $entry->order_discount_no_percentage_value = $store->order_discount_no_percentage_value;
        $entry->total_discount = $store->total_discount;
        $entry->product_tax = $store->product_tax;
        $entry->order_tax_id = $store->order_tax_id;
        $entry->order_tax = $store->order_tax;
        $entry->total_tax = $store->total_tax;
        $entry->tax_ICBPER = $store->tax_ICBPER;
        $entry->mult_ICBPER = $store->mult_ICBPER;
        $entry->subtotal = $store->subtotal;
        $entry->grand_total = $store->grand_total;
        $entry->total_items = $store->total_items;
        $entry->total_quantity = $store->total_quantity;
        $entry->note = $store->note;
        $entry->rounding = $store->rounding;
        $entry->attachment = $store->attachment;
        $entry->expiration_date = $store->expiration_date;
        $entry->canal_id = $store->canal_id;
        $entry->payment_method_id = $store->payment_method_id;
        $entry->num_quotation = $store->num_quotation;
        $entry->destination_address = $store->destination_address;
        $entry->destination_ubigeo = $store->destination_ubigeo;
        $entry->supplier_address = $store->supplier_address;
        $entry->supplier_contact_name = $store->supplier_contact_name;
        $entry->supplier_contact_phone = $store->supplier_contact_phone;
        $entry->supplier_contact_email = $store->supplier_contact_email;
        $entry->estado = $store->estado;
        $entry->created_by = $store->created_by;
        $entry->updated_by = $store->updated_by;
        $entry->created_at = $store->created_at;
        $entry->updated_at = $store->updated_at;
        $entry->status = $store->status;

        $entry->save();

        $idheader = $entry->id;

        //1 Traigo los items de la orden de compra a actualizar
        //2 Todos los Items a status = 0
        //3 volver a insertar todo junto a los items nuevos

        PurchaseOrderItems::where("purchase_order_header_id", $store->id)->update(["status" => 0]);
        // dd(PurchaseOrderItems::where("purchase_order_header_id", $store->id)->get());


        $items = [];

        foreach ($store->items as $itemData) {
            $item = new PurchaseOrderItems();
            $itemData['purchase_order_header_id'] = $idheader;

            // Asegúrate de que $itemData sea un array antes de usar fill()
            if (is_array($itemData)) {
                $item->fill($itemData);
                $item->save();
                $items[] = $item;
            }
        }
        $entry->items = $items;

        // return $entry;

    }

    public function change_estado(int $id): void
    {
        PurchaseOrderHeader::where('id', $id)->update([
            'estado' => 1
        ]);
    }

    public function destroy(int $id): void
    {
        PurchaseOrderHeader::where('id', $id)->update([
            'status' => 0
        ]);
    }
}
