<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\FieldValue;
use Illuminate\Pagination\LengthAwarePaginator;
use GuzzleHttp\Client;

class AdminSupportController extends Controller
{
   
    public function index(Request $request)
    {
        $serviceAccount = base_path(env('FIREBASE_CREDENTIALS'));
        $projectId      = env('FIREBASE_PROJECT_ID');

        $fs = new FirestoreClient([
            'projectId'   => $projectId,
            'keyFilePath' => $serviceAccount,
            'transport'   => 'rest',
        ]);

        $coll     = $fs->collection('supportChats');
        $userDocs = $coll->listDocuments();
        $rows     = [];

        foreach ($userDocs as $userDoc) {
            $email = $userDoc->id();

            // 1) has admin replied?
            $replies = $coll
                ->document($email)
                ->collection('adminMessages')
                ->limit(1)
                ->documents();
            $done = false;
            foreach ($replies as $r) {
                if ($r->exists()) {
                    $done = true;
                    break;
                }
            }

            // 2) fetch the *latest* user message
            $msgs = $coll
                ->document($email)
                ->collection('messages')
                ->orderBy('timestamp','DESC')
                ->limit(1)
                ->documents();
            foreach ($msgs as $m) {
                if (! $m->exists()) {
                    continue;
                }
                $d  = $m->data();
                $ts = $d['timestamp'] ?? null;
                $dt = $ts && method_exists($ts,'get')
                   ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                   : null;

                $rows[] = [
                    'user_email' => $email,
                    'sender'     => $d['sender'] ?? $email,
                    'text'       => $d['text']   ?? '',
                    'timestamp'  => $dt,
                    'id'         => $m->id(),
                    'status'     => $done ? 'DONE' : 'PROGRESS',
                ];
            }
        }

        // sort by timestamp desc
        usort($rows, function($a,$b){
            return ($b['timestamp']?->getTimestamp()?:0)
                 <=> ($a['timestamp']?->getTimestamp()?:0);
        });

        // paginate
        $perPage = 5;
        $page    = $request->get('page',1);
        $slice   = array_slice($rows, ($page-1)*$perPage, $perPage);

        $paginator = new LengthAwarePaginator(
            $slice,
            count($rows),
            $perPage,
            $page,
            ['path'=>$request->url(),'query'=>$request->query()]
        );

        return view('awa.pages.tickets', ['tickets' => $paginator]);
    }



    public function show(Request $request)
    {
        $serviceAccount = base_path(env('FIREBASE_CREDENTIALS'));
        $projectId      = env('FIREBASE_PROJECT_ID');
    
        $fs = new FirestoreClient([
            'projectId'   => $projectId,
            'keyFilePath' => $serviceAccount,
            'transport'   => 'rest',
        ]);
    
        $supportChats = $fs->collection('supportChats');
        $userRefs     = $supportChats->listDocuments();
        $rows         = [];
    
        foreach ($userRefs as $userRef) {
            $email = $userRef->id();
    
            // 1) Check if admin has replied at all
            $adminMsgs = $supportChats
                ->document($email)
                ->collection('adminMessages')
                ->limit(1)
                ->documents();
            $hasReply = false;
            foreach ($adminMsgs as $m) {
                if ($m->exists()) {
                    $hasReply = true;
                    break;
                }
            }
    
            // 2) Grab *only the latest* user‐sent message
            $userMsgDocs = $supportChats
                ->document($email)
                ->collection('messages')
                ->orderBy('timestamp', 'DESC')
                ->limit(1)
                ->documents();
    
            foreach ($userMsgDocs as $msgDoc) {
                if (! $msgDoc->exists()) {
                    continue;
                }
                $data = $msgDoc->data();
                $ts   = $data['timestamp'] ?? null;
                $dt   = $ts && method_exists($ts, 'get')
                      ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                      : null;
    
                $rows[] = [
                    'user_email' => $email,
                    'sender'     => $data['sender']  ?? $email,
                    'text'       => $data['text']    ?? '',
                    'timestamp'  => $dt,
                    'id'         => $msgDoc->id(),
                    'status'     => $hasReply ? 'DONE' : 'PROGRESS',
                ];
            }
        }
    
        // sort by that one timestamp descending
        usort($rows, function($a, $b) {
            $ta = $a['timestamp']?->getTimestamp() ?: 0;
            $tb = $b['timestamp']?->getTimestamp() ?: 0;
            return $tb <=> $ta;
        });
    
        // paginate
        $perPage = 5;
        $page    = $request->get('page', 1);
        $slice   = array_slice($rows, ($page - 1) * $perPage, $perPage);
    
        $paginator = new LengthAwarePaginator(
            $slice,
            count($rows),
            $perPage,
            $page,
            [
                'path'  => $request->url(),
                'query' => $request->query(),
            ]
        );
    
        return view('awa.pages.support', [
            'tickets' => $paginator,
        ]);
    }
    


    public function chat(string $userEmail)
    {
        $serviceAccount = base_path(env('FIREBASE_CREDENTIALS'));
        $projectId      = env('FIREBASE_PROJECT_ID');

        $fs = new FirestoreClient([
            'projectId'   => $projectId,
            'keyFilePath' => $serviceAccount,
            'transport'   => 'rest',
        ]);

        $baseRef = $fs
            ->collection('supportChats')
            ->document($userEmail);

        
        $userDocs = $baseRef
            ->collection('messages')
            ->documents();

       
        $adminDocs = $baseRef
            ->collection('adminMessages')
            ->documents();

        
        $messages = [];

        foreach ($userDocs as $doc) {
            if (!$doc->exists()) continue;
            $d = $doc->data();
            $ts = $d['timestamp'] ?? null;
            $dt = $ts && method_exists($ts,'get')
                  ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                  : null;
            $messages[] = [
                'sender'    => $d['sender'] ?? 'user',
                'text'      => $d['text']   ?? '',
                'timestamp' => $dt,
            ];
        }

        foreach ($adminDocs as $doc) {
            if (!$doc->exists()) continue;
            $d = $doc->data();
            $ts = $d['timestamp'] ?? null;
            $dt = $ts && method_exists($ts,'get')
                  ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                  : null;
            $messages[] = [
                'sender'    => 'admin',
                'text'      => $d['text']   ?? '',
                'timestamp' => $dt,
            ];
        }

      
        usort($messages, fn($a,$b)=>
            ($a['timestamp']?->getTimestamp()?:0)
            <=>
            ($b['timestamp']?->getTimestamp()?:0)
        );

        return view('awa.pages.chat', compact('userEmail','messages'));
    }

  
    public function send(Request $request, string $userEmail)
    {
        $request->validate([
            'text' => 'required|string',
        ]);

        $serviceAccount = base_path(env('FIREBASE_CREDENTIALS'));
        $projectId      = env('FIREBASE_PROJECT_ID');

        $fs = new FirestoreClient([
            'projectId'   => $projectId,
            'keyFilePath' => $serviceAccount,
            'transport'   => 'rest',
        ]);

        $fs->collection('supportChats')
           ->document($userEmail)
           ->collection('adminMessages')
           ->add([
               'text'      => $request->text,
               'timestamp' => FieldValue::serverTimestamp(),
           ]);

           // 3) Notify user via your external API

          
    try {
        $client = new Client([
            'base_uri' => config('services.admin_api.base_url'), 
            'timeout'  => 5,
        ]);

        $response = $client->post('/admin_send_notification', [
            'form_params' => [
                'from_email' => session('admin_email'),
                'to_email'   => $userEmail,
                'message'    => $request->text,
            ],
        ]);

        $body = json_decode((string) $response->getBody(), true);

        if (($body['status'] ?? 1) !== 0) {
            \Log::warning('Notification API returned error', $body);
        }
    } catch (\Exception $e) {
        \Log::error('Notification API exception: '.$e->getMessage());
    }
        
    
    
    return redirect()
            ->route('admin.tickets.chat',  ['userEmail' => $userEmail])
            ->with('success','Reply sent and user notified.');
    }




    public function allNotifications(Request $request)
    {
        $serviceAccount = base_path(env('FIREBASE_CREDENTIALS'));
        $projectId      = env('FIREBASE_PROJECT_ID');

        $fs = new FirestoreClient([
            'projectId'   => $projectId,
            'keyFilePath' => $serviceAccount,
            'transport'   => 'rest',
        ]);

       
        $supportChats = $fs->collection('supportChats')->listDocuments();
        $notifications = [];

        foreach ($supportChats as $userRef) {
            $userEmail = $userRef->id();

          
            $docs = $userRef
                ->collection('adminMessages')
                ->documents();

            foreach ($docs as $doc) {
                if (! $doc->exists()) {
                    continue;
                }
                $data = $doc->data();
                $ts   = $data['timestamp'] ?? null;
                $time = ($ts && method_exists($ts, 'get'))
                      ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                      : null;

                $notifications[] = [
                    'user_email' => $userEmail,
                    'message'    => $data['text'] ?? '',
                    'timestamp'  => $time,
                ];
            }
        }

       
        usort($notifications, fn($a, $b) =>
            ($b['timestamp']?->getTimestamp() ?? 0)
            <=>
            ($a['timestamp']?->getTimestamp() ?? 0)
        );

        
        $perPage = 10;
        $page    = $request->get('page', 1);
        $offset  = ($page - 1) * $perPage;
        $slice   = array_slice($notifications, $offset, $perPage);

        $paginator = new LengthAwarePaginator(
            $slice,
            count($notifications),
            $perPage,
            $page,
            [
                'path'  => $request->url(),
                'query' => $request->query(),
            ]
        );

        return view('awa.pages.notifications', [
            'notifications' => $paginator,
        ]);
    }



    public function allMessages(Request $request)
    {
        $serviceAccount = base_path(env('FIREBASE_CREDENTIALS'));
        $projectId      = env('FIREBASE_PROJECT_ID');

        $fs = new FirestoreClient([
            'projectId'   => $projectId,
            'keyFilePath' => $serviceAccount,
            'transport'   => 'rest',
        ]);

      
        $supportChats = $fs->collection('supportChats')->listDocuments();
        $all = [];

        foreach ($supportChats as $userRef) {
            $userEmail = $userRef->id();

           
            $docs = $userRef
                ->collection('messages')
                ->documents();

            foreach ($docs as $doc) {
                if (! $doc->exists()) {
                    continue;
                }
                $data = $doc->data();
                $ts   = $data['timestamp'] ?? null;
                $time = ($ts && method_exists($ts, 'get'))
                      ? $ts->get()->setTimezone(new \DateTimeZone('Asia/Kolkata'))
                      : null;

                $all[] = [
                    'user_email' => $userEmail,
                    'text'       => $data['text'] ?? '',
                    'timestamp'  => $time,
                ];
            }
        }

      
        usort($all, fn($a, $b) =>
            ($b['timestamp']?->getTimestamp() ?? 0)
            <=>
            ($a['timestamp']?->getTimestamp() ?? 0)
        );

        
        $perPage = 10;
        $page    = $request->get('page', 1);
        $offset  = ($page - 1) * $perPage;
        $slice   = array_slice($all, $offset, $perPage);

        $paginator = new LengthAwarePaginator(
            $slice,
            count($all),
            $perPage,
            $page,
            [
                'path'  => $request->url(),
                'query' => $request->query(),
            ]
        );

        return view('awa.pages.messages', [
            'messages' => $paginator,
        ]);
    }

}
