<?php

namespace App\Http\Controllers;

use App\Models\Status;
use App\Models\ServiceName;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;

class VerifyPaymentController extends Controller
{
    /**
     * Show list of receipts pending verification
     */
    public function __construct()
    {
        $this->middleware('permission:application.verify_offline_reciept')->only('index');
    }
    public function index()
    {
        $user = auth()->user();
        $isSuperAdmin = $user->hasRole('Super Admin');

        $targetServices = ServiceName::select('model', 'service_id', 'service_name')->get();

        $items = $targetServices->flatMap(fn($service) =>
            $service->model::withWhereHas('statuses', fn($query) =>
                $query
                ->where('service_id', $service->service_id)
                    ->whereNotNull('offlinereceipt')
                    ->where('receipt_status', 0)
                    ->when(!$isSuperAdmin, fn($q) =>
                        $q->where('receipt_verifier_id', $user->id)
                    )
                    ->with(['serviceName'])
            )
            ->get()
        );

        $datas = $items->sortByDesc('created_at')->values();

        return view('verify_payment.index', compact('datas'));
    }
    /**
     * Show a specific receipt for verification
     */
    public function show($statusId)
    {
        $status = Status::with(['user', 'receiptVerifier', 'receiptVerifiedBy'])->findOrFail($statusId);

        return view('verify_payment.show', compact('status'));
    }

    /**
     * Verify a receipt (approve/reject)
     */
    public function verify(Request $request, $statusId)
    {
        $request->validate([
            'receipt_status' => 'required|in:1,2', // 1 = verified, 2 = rejected
            'receipt_remark' => 'nullable|string|max:500',
        ]);

        $status = Status::findOrFail($statusId);



        $status->receipt_status = $request->receipt_status;
        $status->receipt_remark = $request->receipt_remark;
        $status->receipt_verified_by = Auth::id();
        $status->save();

        Log::info("Receipt verification done", [
            'status_id' => $statusId,
            'verified_by' => Auth::id(),
            'receipt_status' => $request->receipt_status
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Receipt verification updated successfully.'
        ]);
    }
}
