<?php

namespace App\Repositories\Admin;

use App\Mail\CustomerQueryReplied;
use App\Models\CustomerQuery;
use App\Models\CustomerQueryReply;
use App\Repositories\Interfaces\Admin\CustomerQueryInterface;
use Illuminate\Support\Facades\Mail;

class CustomerQueryRepository implements CustomerQueryInterface
{
    public function all()
    {
        return CustomerQuery::latest()->paginate(10);
    }

    public function find($id)
    {
        return CustomerQuery::with('replies.admin')->findOrFail($id);
    }

    public function reply(int $id, string $replyText): CustomerQueryReply
    {
        $query = CustomerQuery::findOrFail($id);

        $reply = CustomerQueryReply::create([
            'customer_query_id' => $query->id,
            'admin_id' => auth()->id(),
            'reply' => $replyText,
        ]);

        // Send reply mail
        Mail::to($query->email)->send(new CustomerQueryReplied($query, $reply));

        // Optionally mark query as replied
        $query->update(['status' => 1]);

        return $reply;
    }
    public function store(array $data)
    {
        return CustomerQuery::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'subject' => $data['subject'],
            'message' => $data['message'],
            'status' => 0,
        ]);
    }
}