<?php

namespace Modules\Lpj\Services;

use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\PermohonanHistory;
use Modules\Lpj\Notifications\PermohonanNotif;
use Modules\Usermanagement\Models\User;

class PermohonanHistoryService
{
    public function createHistory(Permohonan $permohonan, string $status, ?string $keterangan, array $beforeRequest, array $afterRequest, ?string $filePath = null)
    {
        try {

            $history = PermohonanHistory::create([
                'permohonan_id' => $permohonan->id,
                'status' => $status,
                'keterangan' => $keterangan,
                'before_request' => json_encode($beforeRequest),
                'after_request' => json_encode($afterRequest),
                'file_path' => $filePath,
                'user_id' => auth()->id(),
            ]);

            $this->createNotification($permohonan, $status, $beforeRequest, $afterRequest);

        } catch (\Exception $e) {
            // Log the error
            \Log::error('Error creating PermohonanHistory: ' . $e->getMessage());

            // You might want to delete the uploaded file if the database operation fails
            if ($filePath) {
                \Storage::disk('public')->delete($filePath);
            }

            // Rethrow the exception or handle it as per your application's error handling policy
            throw new \Exception('Failed to create PermohonanHistory: ' . $e->getMessage());
        }
    }

    private function createNotification(Permohonan $permohonan, string $status, array $beforeRequest, array $afterRequest)
    {
        $beforeStatus = '';
        if(!empty($beforeRequest)){
            $beforeStatus = $beforeRequest['status'] ?? '';
        }

        if($beforeStatus !== $status){
            if($status === 'order'){
                $users = User::where(['branch_id' => $permohonan->branch_id])->whereHas('roles',function($q){
                    $q->where('name', 'pemohon-eo');
                })->get();

                foreach ($users as $user) {
                    $message = "telah diorder oleh {$permohonan->creator->name}, Mohon Lakukan konfirmasi";
                    $user->notify(new PermohonanNotif($permohonan,$message));
                }
            }
        }
    }
}
