<?php

namespace App\Services\Ticket;

use App\Models\Ticket;
use App\Models\TicketLog;
use Illuminate\Support\Facades\DB;

class TicketService
{
    public function create(array $data): Ticket
    {
        return DB::transaction(function () use ($data) {

            $ticket = Ticket::create([
                'ticket_no'      => $this->generateTicketNo(),
                'ticket_type_id' => $data['ticket_type_id'],
                'customer_id'    => $data['customer_id'] ?? null,
                'title'          => $data['title'],
                'description'    => $data['description'] ?? null,
                'priority'       => $data['priority'],
                'status'         => 'open',
                'created_by'     => 1
            ]);

            TicketLog::create([
                'ticket_id' => $ticket->id,
                'user_id'   => 1,
                'activity'  => 'Ticket Created',
                'notes'     => 'Ticket dibuat oleh sistem',
                'created_at'=> now()
            ]);

            return $ticket;
        });
    }

    public function update(Ticket $ticket, array $data): Ticket
    {
        $ticket->update($data);

        return $ticket->fresh();
    }

    public function delete(Ticket $ticket): Ticket
    {
        $ticket->update([
            'status' => 'cancelled'
        ]);

        return $ticket;
    }

    private function generateTicketNo(): string
    {
        $prefix = 'TCK-' . now()->format('Ym');

        $lastTicket = Ticket::where(
            'ticket_no',
            'like',
            $prefix . '%'
        )
        ->latest('id')
        ->first();

        $number = 1;

        if ($lastTicket) {
            $number = ((int) substr($lastTicket->ticket_no, -6)) + 1;
        }

        return $prefix . '-' . str_pad(
            $number,
            6,
            '0',
            STR_PAD_LEFT
        );
    }
}