<?php

namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use PHPMailer\PHPMailer\PHPMailer;  
use PHPMailer\PHPMailer\Exception;
use DateTime;
use DatePeriod;
use DateInterval;
use DB;
use Mail;
use ZipArchive;

class AsynchroneController extends Controller
{
    //**
    
    public function requestExport(Request $request)
    {
        // Validation de l'ID utilisateur envoyé par le front
        
        $userId = $request->user_id;
        
        /*
        $exportJob = ExportJob::create([
            'user_id' => $userId,
            'status' => 'pending'
        ]);
        */
        
        $exportJob = DB::table('ebm_export_jobs')->insertGetId([
            'id_user' => $userId,
            'status' => 'pending'
        ]);


        // Traitement SYNCHRONE avec l'ID reçu
        $this->processExport($userId, $exportJob);
        
        return response()->json([
            'job_id' => $exportJob,
            'status' => 'completed',
            'download_url' => "https://touszone.com/mobileappebm/public/exports/export_{$exportJob}.zip"
        ]);
    }
    
    private function processExport($userId, $jobId)
    {
        //$user = \App\Models\User::find($userId);
        //$user = DB::table('ebm_users')->where('id_user', $userId)->first();
        
        
        //-----------------------------  GROUPE DE PRIÈRE  -----------------------------------------------------
        
        $historiqueData = [];

        $allforums = DB::select('
            SELECT g.id_groupe, g.titregroupe
            FROM ebm_groupe g
            INNER JOIN ebm_groupe_posts gp ON g.id_groupe = gp.id_groupe
            WHERE gp.id_user = ?
            GROUP BY g.id_groupe, g.titregroupe
        ', [$userId]);
        
        foreach ($allforums as $forum) {
            $forumId = $forum->id_groupe;
        
            $historiqueData[$forumId] = [
                'id' => $forum->id_groupe,
                'name_groupe' => $forum->titregroupe,
                'historique' => [],
            ];
        
            $groupeposts = DB::select('
                SELECT * FROM ebm_groupe_posts
                WHERE id_user = ? AND id_groupe = ?
                ORDER BY date_publication DESC
            ', [$userId, $forumId]);
        
            foreach ($groupeposts as $post) {
                // Récupérer les réponses pour ce post
                $reponses = DB::select('
                    SELECT r.*, u.nom, u.prenom
                    FROM ebm_groupe_posts_reponses r
                    INNER JOIN ebm_users u ON r.id_user = u.id_user
                    WHERE r.id_groupepost = ?
                    ORDER BY r.date_reponse DESC
                ', [$post->id_groupepost]);
        
                // Préparer la liste des réponses
                $formattedReplies = [];
                foreach ($reponses as $rep) {
                    $formattedReplies[] = [
                        'id_user' => $rep->id_user,
                        'name' => $rep->nom . ' ' . $rep->prenom,
                        'content' => $rep->content,
                        'date_reponse' => $rep->date_reponse,
                    ];
                }
        
                $historiqueData[$forumId]['historique'][] = [
                    'id_user' => $post->id_user,
                    'content' => $post->content,
                    'date_publication' => $post->date_publication,
                    'reponses' => $formattedReplies,
                ];
            }
        }
        
        //-----------------------------  FORUM  -----------------------------------------------------
        
        $forum = DB::table('ebm_forum_posts')->where('id_user', $userId)->get();
        
        //-----------------------------  TÉMOIGNAGE  -----------------------------------------------------
        
        $temoignage = DB::table('ebm_temoignage')->where('id_user', $userId)->get();
        
        //-----------------------------  PRIÈRE  -----------------------------------------------------
        
        $priere = DB::table('ebm_events_home_screen')
        ->where('id_user', $userId)
        ->where('type', 'prière')
        ->where('type_users', 'Usager')
        ->get();
        
        // Résultat final à exporter
        $data = [
            'groupe' => array_values($historiqueData),
            'forum' => $forum->values()->all(),
            'temoignage' => $temoignage->values()->all(),
            'priere' => $priere->values()->all(),
            'exported_at' => now()->toISOString()
        ];

        
        // Créer le dossier exports s'il n'existe pas
        $exportDir = public_path('exports');
        if (!is_dir($exportDir)) {
            mkdir($exportDir, 0755, true);
        }
        
        // Créer le ZIP
        
        $zip = new ZipArchive();
        //$zipPath = public_path("exports/export_{$jobId}.zip");
        $zipPath = $exportDir . "/export_{$jobId}.zip";
        
        if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
            //$zip->addFromString('data.json', json_encode($data, JSON_PRETTY_PRINT));
            $zip->addFromString('data.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            $zip->close();
        }
        
        // Mettre à jour le statut  //https://votre-site.com/exports/export_1.zip http://votre-site.com/exports/export_2.zip
        
        DB::table('ebm_export_jobs')
        ->where('id', $jobId)
        ->update([
            'status' => 'completed',
            'download_url' => "https://touszone.com/mobileappebm/public/exports/export_{$jobId}.zip",
            'completed_at' => now()
        ]);
        /*
        ExportJob::where('id', $jobId)
        ->update([
            'status' => 'completed',
            'download_url' => "exports/export_{$jobId}.zip",
            'completed_at' => now()
        ]);
        */
    }
    
    public function getJobStatus($jobId)
    {
        //$exportJob = ExportJob::findOrFail($jobId);
        
        $exportJob = DB::table('ebm_export_jobs')->where('id', $jobId)->first();

        return response()->json([
            'job_id' => $exportJob->id,
            'status' => $exportJob->status,
            'download_url' => $exportJob->download_url ? 
                "/{$exportJob->download_url}" : 
                null
        ]);
    }
    
}
