<?php

namespace App\Services;

use App\Models\Company;
use App\Models\LeftOverNote;
use App\Models\StoreIssueRequisitionItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class LeftOverNoteService
{
    public function getAll()
    {
        // if (auth()->user()->hasRole('Superadmin')) {
        $leftOverNotes = LeftOverNote::orderBy('created_at', 'asc')->get();
        // } else {
        //     $leftOverNotes = LeftOverNote::where('company_id', auth()->user()->employee->company_id)->orderBy('created_at', 'asc')->get();
        // }
        return $leftOverNotes;
    }

    public function create(array $data)
    {
        return DB::transaction(function () use ($data) {
            $defaultCompanyId = Company::where('name', 'Benson Pharmaceuticals')->first()?->id ?? null;
            $items = $data['items'] ?? [];

            $data['product_id'] = $data['product'];
            $data['batch_id'] = $data['batch'];
            $data['department_id'] = $data['department'] ?? null;
            // $data['store_issue_requisition_id'] = $data['store_issue_requisition'];
            $data['company_id'] = $defaultCompanyId;

            $leftOverNote = LeftOverNote::create($data);

            foreach ($items as $item) {
                $sirItem = StoreIssueRequisitionItem::find($item['sir_item_id']);
                $itemData = [
                    'left_over_note_id' => $leftOverNote->id,
                    'raw_material_item_id' => $item['raw_material_item'],
                    'quantity' => $item['quantity'],
                    'unit' => $item['unit'],
                    'unit_price' => $item['unit_price'],
                    'total' => $item['total_amount'],
                    'remarks' => $item['description'] ?? null,
                    'sir_item_id' => $item['sir_item_id'],
                    'sir_id' => $sirItem->store_issue_requisition_id,
                    'sir_item_qty' => $sirItem->quantity,
                ];
                // $item['raw_material_item_id'] = $item['raw_material_item'] ?? null;

                $leftOverNote->items()->create($itemData);
                // $item['company_id'] = $data['company_id'];
                $leftOverNote->stocks()->create([
                    'product_id' => $leftOverNote->product_id,
                    'raw_material_item_id' => $leftOverNote->raw_material_item_id,
                    'batch_id' => $leftOverNote->batch_id,
                    'store_issue_requisition_id' => $sirItem->store_issue_requisition_id,
                    'left_over_note_id' => $leftOverNote->id,
                    'quantity' => $item['quantity'],
                    'unit' => $item['unit'],
                    'unit_price' => $item['unit_price'],
                    'total' => $item['total_amount'],
                    'company_id' => $data['company_id'],
                    'created_by' => Auth::id(),
                ]);
            }

            return $leftOverNote;
        });
    }

    public function update(LeftOverNote $leftOverNote, array $data)
    {
        return DB::transaction(function () use ($leftOverNote, $data) {
            unset($data['code']);
            $items = $data['items'] ?? [];

            $data['product_id'] = $data['product'];
            $data['batch_id'] = $data['batch'];
            $data['department_id'] = $data['department'];
            // $data['store_issue_requisition_id'] = $data['store_issue_requisition'];
            $data['company_id'] = $data['company'];

            // $leftOverNote->update($data);

            $leftOverNote->items()->delete();
            $leftOverNote->stocks()->delete();

            foreach ($items as $item) {
                $sirItem = StoreIssueRequisitionItem::find($item['sir_item_id']);
                $itemData = [
                    'left_over_note_id' => $leftOverNote->id,
                    'raw_material_item_id' => $item['raw_material_item'],
                    'quantity' => $item['quantity'],
                    'unit' => $item['unit'],
                    'unit_price' => $item['unit_price'],
                    'total' => $item['total_amount'],
                    'remarks' => $item['description'] ?? null,
                    'sir_item_id' => $item['sir_item_id'],
                    'sir_id' => $sirItem->store_issue_requisition_id,
                    'sir_item_qty' => $sirItem->quantity,
                ];

                $leftOverNote->items()->create($itemData);
                $leftOverNote->stocks()->create([
                    'product_id' => $leftOverNote->product_id,
                    'raw_material_item_id' => $leftOverNote->raw_material_item_id,
                    'batch_id' => $leftOverNote->batch_id,
                    'store_issue_requisition_id' => $sirItem->store_issue_requisition_id,
                    'left_over_note_id' => $leftOverNote->id,
                    'quantity' => $item['quantity'],
                    'unit' => $item['unit'],
                    'unit_price' => $item['unit_price'],
                    'total' => $item['total_amount'],
                    'company_id' => $data['company_id'],
                    'created_by' => Auth::id(),
                ]);
            }

            // foreach ($items as $item) {
            //     $item['raw_material_item_id'] = $item['raw_material_item'] ?? null;

            //     $leftOverNote->items()->create($item);
            //     $item['company_id'] = $data['company_id'];
            //     $leftOverNote->stocks()->create($item);
            // }

            return $leftOverNote;
        });
    }

    public function delete(LeftOverNote $leftOverNote)
    {
        $leftOverNote->stocks()->delete();
        return $leftOverNote->delete();
    }

    public function getById($id)
    {
        return LeftOverNote::findOrFail($id);
    }

    public function createCode($company_id)
    {
        $lastLeftOverNoteCode = LeftOverNote::latest('id')->where('company_id', $company_id)->value('code');
        if ($lastLeftOverNoteCode) {
            $numberPart = (int) substr($lastLeftOverNoteCode, 3);
            $newNumberPart = $numberPart + 1;
            $newLeftOverNoteCode = 'LON' . str_pad($newNumberPart, 5, '0', STR_PAD_LEFT);
        } else {
            $newLeftOverNoteCode = 'LON00001';
        }
        return $newLeftOverNoteCode;
    }
}
