<?php

namespace App\Http\Controllers;

use App\Models\LeftOverNote;
use App\Http\Requests\LeftOverNoteRequest;
use App\Models\Company;
use App\Models\StoreIssueRequisition;
use App\Models\StoreIssueRequisitionItem;
use App\Services\StoreIssueRequisitionService;
use App\Services\LeftOverNoteService;
use App\Services\DepartmentService;
use App\Services\ProductService;
use App\Services\CompanyService;
use App\Services\BatchService;
use App\Services\RawMaterialItemService;
use Illuminate\Http\Request;

class LeftOverNoteController extends Controller
{
    protected $storeIssueRequisitionService;
    protected $leftOverNoteService;
    protected $departmentService;
    protected $productService;
    protected $companyService;
    protected $batchService;
    protected $rawMaterialItemService;

    public function __construct(StoreIssueRequisitionService $storeIssueRequisitionService, LeftOverNoteService $leftOverNoteService, DepartmentService $departmentService, ProductService $productService, CompanyService $companyService, BatchService $batchService, RawMaterialItemService $rawMaterialItemService)
    {
        $this->storeIssueRequisitionService = $storeIssueRequisitionService;
        $this->leftOverNoteService = $leftOverNoteService;
        $this->departmentService = $departmentService;
        $this->productService = $productService;
        $this->companyService = $companyService;
        $this->batchService = $batchService;
        $this->rawMaterialItemService = $rawMaterialItemService;
    }

    public function index()
    {
        if (!auth()->user()->hasPermission('Left Over Note List')) {
            abort(403, 'Unauthorized action.');
        }
        $leftOverNotes = $this->leftOverNoteService->getAll();
        return view('admin.left-over-notes.index', compact('leftOverNotes'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        if (!auth()->user()->hasPermission('Left Over Note Create')) {
            abort(403, 'Unauthorized action.');
        }
        if (auth()->user()->hasRole('Superadmin')) {
            $newLeftOverNoteCode = "LON";
        } else {
            $newLeftOverNoteCode = $this->leftOverNoteService->createCode(auth()->user()->employee->company_id);
        }
        $requisitions = $this->storeIssueRequisitionService->getAll();
        $departments = $this->departmentService->getAllDepartments();
        $companies = $this->companyService->getAllCompanies();
        $products = $this->productService->getAllProducts();
        $batches = $this->batchService->getAllBatches();
        $defaultCompanyId = Company::where('name', 'Benson Pharmaceuticals')->first()?->id;

        $rawMaterialItems = $this->rawMaterialItemService->getAllRawMaterialItems();
        return view('admin.left-over-notes.create', compact('requisitions', 'departments', 'companies', 'products', 'batches', 'newLeftOverNoteCode', 'defaultCompanyId', 'rawMaterialItems'));
    }

    public function getBatchSirs(Request $request)
    {
        // dd($request->all());
        if ($request->filled('batch_id') && $request->filled('raw_item_id')) {
            $sirItems = StoreIssueRequisitionItem::where('raw_material_item_id', $request->raw_item_id)
                ->whereHas('store_issue_requisition', function ($q) use ($request) {
                    $q->where('batch_id', $request->batch_id)->where('is_production', '1');
                })
                ->withSum('leftOverNotes as leftover_qty', 'quantity')
                ->havingRaw('COALESCE(leftover_qty, 0) < store_issue_requisition_items.quantity')
                // ->where(function ($query) {
                //     $query->whereDoesntHave('leftOverNotes') // no leftovers yet
                //         ->orWhereHas('leftOverNotes', function ($q) {
                //             $q->select(DB::raw('sir_item_id, SUM(quantity) as total_leftover_qty'))
                //                 ->groupBy('sir_item_id')
                //                 ->havingRaw('SUM(quantity) < (
                //                     SELECT quantity FROM store_issue_requisition_items 
                //                     WHERE id = left_over_note_items.sir_item_id
                //                 )');
                //         });
                // })
                ->with('store_issue_requisition')
                // ->orderByDesc('store_issue_requisition.created_at')
                ->orderByDesc(
                    StoreIssueRequisition::select('created_at')
                        ->whereColumn('store_issue_requisition_items.store_issue_requisition_id', 'store_issue_requisitions.id')
                        ->limit(1)
                )
                ->get();

            return response()->json([
                'success' => true,
                'sirItems' => $sirItems
            ]);

            // $sirs = StoreIssueRequisition::where('is_production', '1')
            //     ->where('batch_id', $request->batch_id)
            //     // ->where('product_variation_id', $request->batch_id)
            //     ->orderBy('code')->get();

            // return response()->json([
            //     'success' => true,
            //     'sirs' => $sirs
            // ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Select Batch & Raw Item First !'
            ]);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(LeftOverNoteRequest $request)
    {
        // dd($request->all());
        try {
            if (!auth()->user()->hasPermission('Left Over Note Create')) {
                abort(403, 'Unauthorized action.');
            }
            $leftOverNote = $this->leftOverNoteService->create($request->validated());
            return redirect()->route('left-over-notes.show', $leftOverNote->id)->with('success', 'Left Over Note created successfully.');
        } catch (\Throwable $th) {
            return redirect()->back()->with('error', $th->getMessage());
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        if (!auth()->user()->hasPermission('Left Over Note View')) {
            abort(403, 'Unauthorized action.');
        }
        $leftOverNote = $this->leftOverNoteService->getById($id);
        $previous = LeftOverNote::where('id', '<', $leftOverNote->id)
            ->orderBy('id', 'desc')
            ->first();

        $next = LeftOverNote::where('id', '>', $leftOverNote->id)
            ->orderBy('id', 'asc')
            ->first();

        // Get all purchase orders for the dropdown (ordered by creation date, newest first)
        $allLONs = LeftOverNote::orderBy('created_at', 'desc')
            ->select('id', 'code', 'created_at')
            ->get();
        return view('admin.left-over-notes.show', compact('leftOverNote', 'previous', 'next', 'allLONs'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        if (!auth()->user()->hasPermission('Left Over Note Update')) {
            abort(403, 'Unauthorized action.');
        }
        $leftOverNote = $this->leftOverNoteService->getById($id);
        $requisitions = $this->storeIssueRequisitionService->getAll();
        $departments = $this->departmentService->getAllDepartments();
        $companies = $this->companyService->getAllCompanies();
        $products = $this->productService->getAllProducts();
        $batches = $this->batchService->getAllBatches();
        $defaultCompanyId = Company::where('name', 'Benson Pharmaceuticals')->first()?->id;
        $rawMaterialItems = $this->rawMaterialItemService->getAllRawMaterialItems();
        return view('admin.left-over-notes.edit-new', compact('leftOverNote', 'requisitions', 'departments', 'companies', 'products', 'batches', 'defaultCompanyId', 'rawMaterialItems'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(LeftOverNoteRequest $request, LeftOverNote $leftOverNote)
    {
        // dd($request->all());
        if (!auth()->user()->hasPermission('Left Over Note Update')) {
            abort(403, 'Unauthorized action.');
        }
        $leftOverNote = $this->leftOverNoteService->update($leftOverNote, $request->validated());
        return redirect()->route('left-over-notes.show', $leftOverNote->id)->with('success', 'Left Over Note updated successfully');
    }

    public function destroy(LeftOverNote $leftOverNote)
    {
        if (!auth()->user()->hasPermission('Left Over Note Delete')) {
            abort(403, 'Unauthorized action.');
        }
        $this->leftOverNoteService->delete($leftOverNote);
        return redirect()->route('left-over-notes.index')->with('success', 'Left Over Note deleted successfully');
    }

    public function createCodeByCompany($companyId)
    {
        $left_over_note_code = $this->leftOverNoteService->createCode($companyId);
        return response()->json(['left_over_note_code' => $left_over_note_code]);
    }
}
