<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Surah;
use App\Models\Ayat;
use App\Models\Juz;
use App\Models\Sajdah;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;

class FetchQuranData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'quran:fetch-data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fetch and store Quran data from APIs';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting to fetch Quran data...');
        
        DB::beginTransaction();
        try {
            // Fetch and store Surahs
            $this->info('Fetching Surahs...');
            $this->fetchSurahs();
            
            // Fetch and store Juzs
            $this->info('Fetching Juzs...');
            $this->fetchJuzs();
            
            // Fetch and store Sajdahs
            $this->info('Fetching Sajdahs...');
            $this->fetchSajdahs();
            
            DB::commit();
            $this->info('All data fetched and stored successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            $this->error('Error: ' . $e->getMessage());
            return 1;
        }
        
        return 0;
    }

    /**
     * Fetch and store all Surahs with their Ayats
     */
    protected function fetchSurahs()
    {
        // Fetch list of all surahs
        $response = Http::get('https://quranapi.pages.dev/api/surah.json');
        
        if (!$response->successful()) {
            throw new \Exception('Failed to fetch surahs list');
        }
        
        $surahs = $response->json();
        
        $bar = $this->output->createProgressBar(count($surahs));
        $bar->start();
        
        $globalAyahNumber = 0; // Track global ayah number
        
        foreach ($surahs as $index => $surahData) {
            $surahNo = $index + 1;
            
            // Fetch surah detail
            $surahDetailResponse = Http::get("https://quranapi.pages.dev/api/{$surahNo}.json");
            
            if (!$surahDetailResponse->successful()) {
                $this->warn("Failed to fetch detail for Surah {$surahNo}");
                $bar->advance();
                continue;
            }
            
            $surahDetail = $surahDetailResponse->json();
            
            // Fetch transliteration
            $transliterationResponse = Http::get("https://alquran-api.pages.dev/api/quran/surah/{$surahNo}?lang=transliteration");
            $transliterationData = $transliterationResponse->successful() ? $transliterationResponse->json() : null;
            
            // Create or update Surah
            $surah = Surah::updateOrCreate(
                ['surah_no' => $surahNo],
                [
                    'surah_name' => $surahDetail['surahName'] ?? $surahData['surahName'],
                    'surah_name_arabic' => $surahDetail['surahNameArabic'] ?? $surahData['surahNameArabic'],
                    'surah_name_arabic_long' => $surahDetail['surahNameArabicLong'] ?? null,
                    'surah_name_translation' => $surahDetail['surahNameTranslation'] ?? $surahData['surahNameTranslation'],
                    'revelation_place' => $surahDetail['revelationPlace'] ?? $surahData['revelationPlace'],
                    'total_ayah' => $surahDetail['totalAyah'] ?? $surahData['totalAyah'],
                    'audio' => $surahDetail['audio'] ?? null,
                ]
            );
            
            // Store Ayats
            $arabic1 = $surahDetail['arabic1'] ?? [];
            $arabic2 = $surahDetail['arabic2'] ?? [];
            $english = $surahDetail['english'] ?? [];
            $transliterations = $transliterationData['verses'] ?? [];
            
            // Get ayah numbers from transliteration data for mapping
            $transliterationMap = [];
            if (!empty($transliterations)) {
                foreach ($transliterations as $verse) {
                    $transliterationMap[$verse['id']] = $verse['transliteration'] ?? null;
                }
            }
            
            for ($i = 0; $i < count($arabic1); $i++) {
                $ayahNo = $i + 1;
                $globalAyahNumber++;
                
                Ayat::updateOrCreate(
                    [
                        'surah_id' => $surah->id,
                        'ayah_no' => $ayahNo,
                    ],
                    [
                        'ayah_number' => $globalAyahNumber,
                        'arabic_text' => $arabic1[$i] ?? '',
                        'arabic_text_simple' => $arabic2[$i] ?? null,
                        'english_translation' => $english[$i] ?? '',
                        'transliteration' => $transliterationMap[$ayahNo] ?? null,
                    ]
                );
            }
            
            $bar->advance();
        }
        
        $bar->finish();
        $this->newLine();
    }

    /**
     * Fetch and store Juzs
     */
    protected function fetchJuzs()
    {
        for ($juzNo = 1; $juzNo <= 30; $juzNo++) {
            $response = Http::get("https://api.alquran.cloud/v1/juz/{$juzNo}/quran-uthmani");
            
            if (!$response->successful()) {
                $this->warn("Failed to fetch Juz {$juzNo}");
                continue;
            }
            
            $data = $response->json();
            
            if (isset($data['data'])) {
                Juz::updateOrCreate(
                    ['juz_number' => $juzNo],
                    ['ayahs_data' => $data['data']]
                );
            }
        }
        
        $this->info('Juzs fetched and stored.');
    }

    /**
     * Fetch and store Sajdahs
     */
    protected function fetchSajdahs()
    {
        $response = Http::get('https://api.alquran.cloud/v1/sajda/quran-uthmani');
        
        if (!$response->successful()) {
            throw new \Exception('Failed to fetch sajdahs');
        }
        
        $data = $response->json();
        
        if (!isset($data['data']['ayahs'])) {
            $this->warn('No sajdahs found in response');
            return;
        }
        
        foreach ($data['data']['ayahs'] as $ayahData) {
            $surahNumber = $ayahData['surah']['number'] ?? null;
            $ayahNumber = $ayahData['number'] ?? null;
            $numberInSurah = $ayahData['numberInSurah'] ?? null;
            
            if (!$surahNumber || !$ayahNumber) {
                continue;
            }
            
            $surah = Surah::where('surah_no', $surahNumber)->first();
            if (!$surah) {
                continue;
            }
            
            $ayat = Ayat::where('surah_id', $surah->id)
                ->where('ayah_no', $numberInSurah)
                ->first();
            
            $sajdahData = $ayahData['sajda'] ?? [];
            
            Sajdah::updateOrCreate(
                [
                    'surah_id' => $surah->id,
                    'ayah_number' => $ayahNumber,
                ],
                [
                    'ayat_id' => $ayat?->id,
                    'number_in_surah' => $numberInSurah,
                    'arabic_text' => $ayahData['text'] ?? '',
                    'recommended' => $sajdahData['recommended'] ?? false,
                    'obligatory' => $sajdahData['obligatory'] ?? false,
                    'juz' => $ayahData['juz'] ?? null,
                    'manzil' => $ayahData['manzil'] ?? null,
                    'page' => $ayahData['page'] ?? null,
                    'ruku' => $ayahData['ruku'] ?? null,
                    'hizb_quarter' => $ayahData['hizbQuarter'] ?? null,
                ]
            );
        }
        
        $this->info('Sajdahs fetched and stored.');
    }
}
