<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Manage\TransactionRequest;
use App\Models\Customer;
use App\Models\Service;
use App\Models\Transaction;
use App\Models\User;
use App\Traits\DeleteAttachment;
use App\Traits\UploadAttachment;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class TransactionController extends Controller
{
    use DeleteAttachment, UploadAttachment;

    public function index(): View
    {
        return view('pages.admin.manage.transaction.index', [
            'pageTitle' => 'Transaksi',
            'transactions' => Transaction::with(['user', 'user.biography'])
                ->barbershop()
                ->when(auth()->user()->role_id === 5, function ($query) {
                    return $query->where('user_id', auth()->id());
                })
                ->latest()
                ->get(),
        ]);
    }

    public function create(): View
    {
        return view('pages.admin.manage.transaction.create', [
            'pageTitle' => 'Tambah Transaksi',
            'services' => Service::query()->barbershop()->latest()->get(),
            'customers' => Customer::query()->barbershop()->latest()->get(),
            'barber' => User::with('biography')->barbershop()->barber()->latest()->get(),
        ]);
    }

    public function store(TransactionRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();
        $findCustomer = Customer::find($validatedData['customer']);
        DB::transaction(function () use ($validatedData, $findCustomer) {
            $customer = null;
            $userId = Auth::id();
            $barbershopId = Auth::user()->barbershop_id;
            if (! $findCustomer) {
                $customer = Customer::create([
                    'user_id' => $userId,
                    'barbershop_id' => $barbershopId,
                    'name' => $validatedData['customer'],
                ]);
            }
            $newTransaction = Transaction::create(array_merge($validatedData, [
                'user_id' => $validatedData['barber'],
                'barbershop_id' => $barbershopId,
                'service_id' => $validatedData['service'],
                'customer_id' => $customer ? $customer->id : $validatedData['customer'],
            ]));
            if (isset($validatedData['image'])) {
                $this->uploadAttachment($validatedData['image'], 'transactions', Transaction::class, $newTransaction->id, 'transaction');
            }
        });

        notify()->success('Data berhasil ditambahkan', 'Berhasil');

        return redirect('dashboard/manage/transactions');
    }

    public function edit(Transaction $transaction): View
    {
        return view('pages.admin.manage.transaction.edit', [
            'pageTitle' => 'Edit Transaksi',
            'services' => Service::query()->barbershop()->latest()->get(),
            'customers' => Customer::query()->barbershop()->latest()->get(),
            'barber' => User::with('biography')->barbershop()->barber()->latest()->get(),
            'transaction' => $transaction,
        ]);
    }

    public function update(Transaction $transaction, TransactionRequest $request): RedirectResponse
    {
        $validatedData = $request->validated();

        DB::transaction(function () use ($validatedData, $transaction) {
            $transaction->update(array_merge($validatedData, [
                'user_id' => $validatedData['barber'],
                'service_id' => $validatedData['service'],
                'customer_id' => $validatedData['customer'],
            ]));
            if (isset($validatedData['image'])) {
                $this->uploadAttachment($validatedData['image'], 'transactions', Transaction::class, $transaction->id, 'transaction');
            }
        });

        notify()->success('Data berhasil diubah', 'Berhasil');

        return redirect('dashboard/manage/transactions');
    }

    public function delete(Transaction $transaction): RedirectResponse
    {
        DB::transaction(function () use ($transaction) {
            $this->deleteAttachment('transactions', $transaction);
            $transaction->delete();
        });

        notify()->success('Data berhasil dihapus', 'Berhasil');

        return back();
    }

    public function getPrice(string $serviceId): JsonResponse
    {
        $service = Service::find($serviceId);

        if (! $service) {
            return response()->json([
                'status' => false,
                'message' => 'Service not found',
            ], 404);
        }

        return response()->json([
            'status' => true,
            'message' => 'Data retrieved successfully',
            'data' => formatToRupiah($service->price),
        ], 200);
    }
}
