<?php
namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\{ClientUser, Ticket, Invoice};
use App\Services\TicketService;
use Illuminate\Http\Request;

class PortalController extends Controller
{
    private function clientUser(): ClientUser
    {
        return ClientUser::with('client')->findOrFail(session('client_user_id'));
    }

    public function dashboard()
    {
        $user   = $this->clientUser();
        $client = $user->client;
        $stats  = [
            'open'     => Ticket::where('client_id',$client->id)->where('status','open')->count(),
            'progress' => Ticket::where('client_id',$client->id)->where('status','in_progress')->count(),
            'resolved' => Ticket::where('client_id',$client->id)->where('status','resolved')->count(),
        ];
        $recent          = Ticket::where('client_id',$client->id)->orderByDesc('created_at')->limit(5)->get();
        $pendingInvoices = Invoice::where('client_id',$client->id)->whereIn('status',['sent','overdue'])->get();
        return view('client.dashboard', compact('user','client','stats','recent','pendingInvoices'));
    }

    public function tickets()
    {
        $user    = $this->clientUser();
        $tickets = Ticket::where('client_id',$user->client_id)->orderByDesc('created_at')->paginate(15);
        return view('client.tickets', compact('user','tickets'));
    }

    public function createTicket()
    {
        $user    = $this->clientUser();
        $devices = $user->client->devices;
        return view('client.create_ticket', compact('user','devices'));
    }

    public function storeTicket(Request $request)
    {
        $user = $this->clientUser();
        $data = $request->validate([
            'subject'     => 'required|string|max:255',
            'description' => 'required|string',
            'priority'    => 'required|in:critical,high,medium,low',
            'category'    => 'required|in:network,hardware,software,cctv,other',
            'device_id'   => 'nullable|exists:devices,id',
        ]);
        $data['client_id']      = $user->client_id;
        $data['client_user_id'] = $user->id;
        $data['division']       = $user->client->division;
        $data['source']         = 'portal';

        $ticket = app(TicketService::class)->create($data, 1);
        return redirect()->route('client.tickets.show', $ticket)->with('success','Tiket berhasil dibuat.');
    }

    public function showTicket(Ticket $ticket)
    {
        $user = $this->clientUser();
        if ($ticket->client_id !== $user->client_id) abort(403);
        $ticket->load(['assignedTo','comments.user','comments.clientUser','attachments']);
        return view('client.show_ticket', compact('ticket','user'));
    }

    public function addComment(Request $request, Ticket $ticket)
    {
        $user = $this->clientUser();
        if ($ticket->client_id !== $user->client_id) abort(403);
        $request->validate(['body'=>'required|string']);
        $ticket->comments()->create([
            'client_user_id' => $user->id,
            'body'           => $request->body,
            'is_internal'    => false,
        ]);
        return back()->with('success','Komentar ditambahkan.');
    }

    public function invoices()
    {
        $user     = $this->clientUser();
        $invoices = Invoice::where('client_id',$user->client_id)->orderByDesc('issue_date')->paginate(15);
        return view('client.invoices', compact('user','invoices'));
    }
}
