<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\PrintQueue;
use Illuminate\Http\Request;

class PrintQueueController extends Controller
{


public function index(Request $request)
{
    try {

        $query = PrintQueue::with([
            'cheque',
            'statusAction'
        ]);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('cheque_id')) {
            $query->where('cheque_id', $request->cheque_id);
        }

        if ($request->filled('print_status')) {

            if ($request->print_status == 'printed') {
                $query->whereNotNull('printed_at');
            }

            if ($request->print_status == 'pending') {
                $query->whereNull('printed_at');
            }
        }

        if ($request->filled('search')) {

            $search = trim($request->search);

            $query->where(function ($q) use ($search) {

                $q->where('print_queues_id', 'like', "%{$search}%")
                  ->orWhere('priority', 'like', "%{$search}%");

                $q->orWhereHas('cheque', function ($cheque) use ($search) {
                    $cheque->where('cheque_no', 'like', "%{$search}%");
                });

                $q->orWhereHas('statusAction', function ($status) use ($search) {
                    $status->where('St_Name', 'like', "%{$search}%");
                });
            });
        }

        return response()->json(
            $query->orderByDesc('print_queues_id')
                ->paginate($request->per_page ?? 15)
                ->through(function ($item) {

                    if ($item->statusAction) {
                        $item->statusAction->setHidden([
                            'authorities_details',
                            'viewers_details'
                        ]);
                    }

                    return $item;
                })
        );

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong while fetching print queues.'
        ], 500);
    }
}

public function getAll(Request $request)
{
    try {

        $query = PrintQueue::with([
            'cheque',
            'statusAction'
        ]);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('cheque_id')) {
            $query->where('cheque_id', $request->cheque_id);
        }

        if ($request->filled('print_status')) {

            if ($request->print_status == 'printed') {
                $query->whereNotNull('printed_at');
            }

            if ($request->print_status == 'pending') {
                $query->whereNull('printed_at');
            }
        }

        if ($request->filled('search')) {

            $search = trim($request->search);

            $query->where(function ($q) use ($search) {

                $q->where('print_queues_id', 'like', "%{$search}%")
                  ->orWhere('priority', 'like', "%{$search}%");

                $q->orWhereHas('cheque', function ($cheque) use ($search) {
                    $cheque->where('cheque_no', 'like', "%{$search}%");
                });

                $q->orWhereHas('statusAction', function ($status) use ($search) {
                    $status->where('St_Name', 'like', "%{$search}%");
                });
            });
        }

        $data = $query->orderByDesc('print_queues_id')->get();

        $data->each(function ($item) {

            if ($item->statusAction) {
                $item->statusAction->setHidden([
                    'authorities_details',
                    'viewers_details'
                ]);
            }
        });

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

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong while fetching print queues.'
        ], 500);
    }
}

    public function store(Request $request)
    {
        $validated = $request->validate([
            'cheque_id' => 'nullable|exists:cheques,cheque_id',
            'status'    => 'nullable|exists:action_master,Act_Id',
            'queued_at' => 'nullable|date',
            'priority'  => 'nullable|integer',
            'printed_at'=> 'nullable|date',
        ]);

        $record = PrintQueue::create([
            'cheque_id' => $validated['cheque_id'] ?? null,
            'status'    => $validated['status'] ?? null,
            'queued_at' => $validated['queued_at'] ?? now(),
            'priority'  => $validated['priority'] ?? 5,
            'printed_at'=> $validated['printed_at'] ?? null,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Print Queue created successfully.',
            'data'    => $record->load(['cheque','statusAction'])
        ], 201);
    }

public function show($id)
{
    try {

        $record = PrintQueue::with([
            'cheque',
            'statusAction'
        ])->findOrFail($id);

        if ($record->statusAction) {
            $record->statusAction->setHidden([
                'authorities_details',
                'viewers_details'
            ]);
        }

        return response()->json([
            'success' => true,
            'message' => 'Print queue details fetched successfully.',
            'data' => $record
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Print queue not found.'
        ], 404);
    }
}

    public function update(Request $request, $id)
    {
        $record = PrintQueue::findOrFail($id);

        $validated = $request->validate([
            'cheque_id' => 'nullable|exists:cheques,cheque_id',
            'status'    => 'nullable|exists:action_master,Act_Id',
            'queued_at' => 'nullable|date',
            'priority'  => 'nullable|integer',
            'printed_at'=> 'nullable|date',
        ]);

        $record->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Print Queue updated successfully.',
            'data' => $record->load(['cheque','statusAction'])
        ]);
    }

    public function destroy($id)
    {
        $record = PrintQueue::findOrFail($id);

        $record->delete();

        return response()->json([
            'success' => true,
            'message' => 'Print Queue deleted successfully.'
        ]);
    }
}
