<?php

namespace Modules\ReportesBot\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Config;
use Barryvdh\DomPDF\Facade\Pdf;
use Exception;
use Illuminate\Support\Facades\Http;
use Modules\Contacts\Models\Contact;
use Modules\ReportesBot\Models\Reporte;
use Modules\Wpbox\Events\ContactReplies;
use Modules\Wpbox\Models\Message;
use Modules\Wpbox\Traits\Whatsapp;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use App\Exports\ReportesExport;
use Maatwebsite\Excel\Facades\Excel;
class Main extends Controller
{
    /**
     * Web RoutePath for the name of the routes.
     */
    private $webroute_path = 'reportesbot.';

    /**
     * View path.
     */
    private $view_path = 'ReportesBot::';

    /**
     * Parameter name.s
     */
    private $parameter_name = 'contact';

    /**
     * Title of this crud.
     */

    /**
     * Title of this crud in plural.
     */
    private $titlePlural = 'reportes';

    /**
     * Auth checker functin for the crud.
     */
    private function authChecker()
    {
        $this->ownerAndStaffOnly();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->authChecker();


        $query = Reporte::join('contacts', function ($join) {
            $join->on(\DB::raw("contacts.phone COLLATE utf8mb4_unicode_ci"), '=', \DB::raw("reportes.celular COLLATE utf8mb4_unicode_ci"));

            // $join->on(\DB::raw("contacts.phone"), '=', 'reportes.celular');
        })
            ->where('estatus', '!=', 'REGISTRANDO')
            ->select('reportes.*', 'contacts.name as nombre_contacto', 'contacts.id as id_contacto');

        if ($request->filled('folio')) {
            $query->where('reportes.folio', $request->folio);
        }

        if ($request->filled('tipo_reporte')) {
            $query->where('reportes.tipo_reporte', 'LIKE', '%' . $request->tipo_reporte . '%');
        }

        if ($request->filled('nombre_contacto')) {
            $query->where('contacts.name', 'LIKE', '%' . $request->nombre_contacto . '%');
        }

        if ($request->filled('ubicacion')) {
            $query->where('reportes.ubicacion', 'LIKE', '%' . $request->ubicacion . '%');
        }

        if ($request->filled('estatus')) {
            $query->where('reportes.estatus', $request->estatus);
        }
        if ($request->filled('estatusOpciones')) {
            $query->where('reportes.estatusOpciones', $request->estatusOpciones);
        }

        if ($request->filled('fecha_inicio')) {
            $query->whereDate('reportes.created_at', '>=', $request->fecha_inicio);
        }

        if ($request->filled('fecha_fin')) {
            $query->whereDate('reportes.created_at', '<=', $request->fecha_fin);
        }

        $perPage = $request->get('per_page', 10);

        $validPerPage = [10, 20, 50, 100];
        if (!in_array($perPage, $validPerPage)) {
            $perPage = 10;
        }

        $items = $query->orderBy('reportes.id', 'desc')->paginate($perPage)->appends($request->query());

        if (!$items->count()) {
            $emptyItem = collect([
                (object) [
                    'id' => 0,
                    'tipo_reporte' => '',
                    'nombre_contacto' => '',
                    'id_contacto' => '',
                    'descripcion_reporte' => '',
                    'ubicacion' => '',
                    'estatus' => '',
                    'foto_reporte' => '',
                    'foto_context_lugar' => '',
                    'created_at' => now(),
                    'estatusOpciones' => '',
                ]
            ]);
            $items = new LengthAwarePaginator(
                Collection::make([$emptyItem]),
                1,
                $perPage,
                1,
                ['path' => request()->url(), 'query' => request()->query()]
            );
        }

        return view($this->view_path . 'index', [
            'setup' => [
                'title' => __('crud.item_managment', ['item' => __($this->titlePlural)]),
                'items' => $items,
                'item_names' => $this->titlePlural,
                'webroute_path' => $this->webroute_path,
                'custom_table' => true,
                'parameter_name' => $this->parameter_name,
                'parameters' => count($request->all()) != 0,
            ]
        ]);
    }

    public function sendStatus($id)
    {
        $item = Reporte::find($id);
        $contact = Contact::where('phone', $item->celular)->first();
        if ($item->estatus == 'NO_SE_RESOLVIO') {
            $item->estatus = 'RESUELTO';
            $item->save();
            return redirect()->route('reportesbot.index')->withStatus(__('crud.item_has_been_updated', ['item' => '']));
        }
        try {
            $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;
            $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;
            $sendPhoneNumber = $contact->phone;
            $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                'Content-Type' => 'application/json',
            ])->post($url, [
                        "messaging_product" => "whatsapp",
                        "recipient_type" => "individual",
                        "to" => $sendPhoneNumber,
                        "type" => "template",
                        "template" => [
                            "name" => "verificacion_reportes",
                            "language" => [
                                "code" => "es"
                            ],
                            "components" => [
                                [
                                    "type" => "header",
                                    "parameters" => [
                                        [
                                            "type" => "image",
                                            "image" => [
                                                "link" => "https://soporte.aplicacionesng.com.mx/uploads/QuJEURUfOQb5YKUVKD2kus6eC3Pjs47KCt9vtPge.jpg"
                                            ]
                                        ]
                                    ]
                                ],
                                [
                                    "type" => "body",
                                    "parameters" => [
                                        [
                                            "type" => "text",
                                            "text" => $item->descripcion_reporte
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]);

            $context = $response['messages'][0]['id'] ?? null;

            if (isset($context)) {
                $item->estatus = 'PROCESANDO';
                $item->context = $context;
                $item->save();
            } else {
                throw new Exception('El mensaje no se envio');
            }

            return redirect()->route('reportesbot.index')->withStatus(__('crud.item_has_been_updated', ['item' => '']));
        } catch (Exception $e) {
            \Log::debug('Error en sendStatus reportes', [$e->getMessage()]);
        }
    }

    public function reporte_no_resueltas()
    {
        $reportes = Reporte::where('estatus', 'NO_SE_RESOLVIO')
            ->get()
            ->map(function ($reporte) {
                try {
                    if (!empty($reporte->foto_reporte)) {
                        $fotoReporteContent = file_get_contents($reporte->foto_reporte);
                        $reporte->foto_reporte = 'data:image/jpeg;base64,' . base64_encode($fotoReporteContent);
                    }

                    if (!empty($reporte->foto_context_lugar)) {
                        $fotoContextContent = file_get_contents($reporte->foto_context_lugar);
                        $reporte->foto_context_lugar = 'data:image/jpeg;base64,' . base64_encode($fotoContextContent);
                    }
                } catch (Exception $ignore) {
                }

                return $reporte;
            });

        $pdf = Pdf::loadView('reportes.reportes_no_resueltos', ['reportes' => $reportes]);
        $pdf->setOption([
            "defaultPaperSize" => "letter",
            'isHtml5ParserEnabled' => true,
            "defaultFont" => "tahoma"
        ]);
        return $pdf->download('reportes_no_resueltos.pdf');
    }
    public function imprimirReporte($id)
    {
        try {
            $reporte = Reporte::findOrFail($id);

            if (!empty($reporte->foto_reporte) && file_exists($reporte->foto_reporte)) {
                $fotoReporteContent = file_get_contents($reporte->foto_reporte);
                $reporte->foto_reporte = 'data:image/jpeg;base64,' . base64_encode($fotoReporteContent);
            }

            if (!empty($reporte->foto_context_lugar) && file_exists($reporte->foto_context_lugar)) {
                $fotoContextContent = file_get_contents($reporte->foto_context_lugar);
                $reporte->foto_context_lugar = 'data:image/jpeg;base64,' . base64_encode($fotoContextContent);
            }

            $contacto = \DB::selectOne("SELECT id,name FROM contacts c WHERE c.phone = ?", [$reporte->celular]);
            $groupName = \DB::selectOne("SELECT g.name FROM `groups` g
                JOIN groups_contacts gc ON g.id = gc.group_id
                WHERE gc.contact_id = ?",
                [$contacto->id]
            );

            $pdf = Pdf::loadView('reportes.reporte', [
                'reporte' => $reporte,
                'name' => $groupName->name ?? 'Sin Grupo',
                'contact_name' => $contacto->name
            ]);

            $pdf->setOption([
                "defaultPaperSize" => "letter",
                'isHtml5ParserEnabled' => true,
                "defaultFont" => "tahoma"
            ]);

            return $pdf->download('reporte_folio_R' . $reporte->id . '.pdf');
        } catch (Exception $e) {
            \Log::debug($e->getMessage());
            // return response()->json(['error' => $e->getTrace()], 500);
        }
    }

    public function reportePendientes()
    {
        $reportes = Reporte::where('estatus', 'PENDIENTE')
            ->get()
            ->map(function ($reporte) {
                try {
                    if (!empty($reporte->foto_reporte)) {
                        $fotoReporteContent = file_get_contents($reporte->foto_reporte);
                        $reporte->foto_reporte = 'data:image/jpeg;base64,' . base64_encode($fotoReporteContent);
                    }

                    if (!empty($reporte->foto_context_lugar)) {
                        $fotoContextContent = file_get_contents($reporte->foto_context_lugar);
                        $reporte->foto_context_lugar = 'data:image/jpeg;base64,' . base64_encode($fotoContextContent);
                    }
                } catch (Exception $ignore) {
                }

                return $reporte;
            });

        $pdf = Pdf::loadView('reportes.reportes_no_resueltos', ['reportes' => $reportes]);
        $pdf->setOption([
            "defaultPaperSize" => "letter",
            'isHtml5ParserEnabled' => true,
            "defaultFont" => "tahoma"
        ]);
        return $pdf->download('reportes_no_resueltos.pdf');
    }
    public function reporteExcel(Request $request)
    {
        \Log::debug('filtros',[$request->all()]);
        $filters = $request->only([
            'folio', 'tipo_reporte', 'nombre_contacto', 'ubicacion',
            'fecha_inicio', 'fecha_fin', 'estatus', 'estatusOpciones'
        ]);

        // Generar y descargar el Excel con los filtros aplicados
        return Excel::download(new ReportesExport($filters), 'reportes.xlsx');
    }

    public function guardarCambios(Request $request)
    {

        $cambios = $request->input('cambios');  // Asegura capturar el JSON

        foreach ($cambios as $cambio) {
            $reporte = Reporte::find($cambio['id']);
            if ($reporte) {
                if ($cambio['opcion'] < $reporte->estatusOpciones) {
                    continue;
                }
                $reporte->estatusOpciones = $cambio['opcion'];
                $reporte->save();
                switch ($reporte->estatusOpciones) {
                    case 2:
                        \Log::debug('Escogio la opcion 2');
                        $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;

                        $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;

                        $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
                        $contact = Contact::where('phone', $reporte->celular)->get()->first();
                        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                            'Content-Type' => 'application/json',
                        ])->post($url, [
                                    "messaging_product" => "whatsapp",
                                    "recipient_type" => "individual",
                                    "to" => $reporte->celular,
                                    "type" => "template",
                                    "template" => [
                                        "name" => "reportar_estatus",
                                        "language" => [
                                            "code" => "es_MX"
                                        ],
                                        "components" => [
                                            [
                                                "type" => "body",
                                                "parameters" => [
                                                    [
                                                        "type" => "text",
                                                        "text" => 'reporte'
                                                    ],
                                                    [
                                                        "type" => "text",
                                                        "text" => $reporte->folio
                                                    ],
                                                    [
                                                        "type" => "text",
                                                        "text" => 'Analizando solicitud'
                                                    ],
                                                ]
                                            ]
                                        ]
                                    ]
                                ]);
                        $content = json_decode($response->body(), true);

                        $message = Message::create([
                            'fb_message_id' => $content['messages'][0]['id'],
                            'contact_id' => $contact->id,
                            'buttons' => '[]',
                            'header_image' => '',
                            'value' => "Cambio de estatus a {$reporte->estatusOpciones} del reporte: {$reporte->folio}",
                            'is_message_by_contact' => 1,
                            'components' => '',
                            'company_id' => 1,
                        ]);
                        event(new ContactReplies(auth()->user(), $message, $contact));
                        break;
                    case 3:
                        $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;

                        $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;

                        $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
                        $contact = Contact::where('phone', $reporte->celular)->get()->first();
                        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                            'Content-Type' => 'application/json',
                        ])->post($url, [
                                    "messaging_product" => "whatsapp",
                                    "recipient_type" => "individual",
                                    "to" => $reporte->celular,
                                    "type" => "template",
                                    "template" => [
                                        "name" => "reportar_estatus",
                                        "language" => [
                                            "code" => "es_MX"
                                        ],
                                        "components" => [
                                            [
                                                "type" => "body",
                                                "parameters" => [
                                                    [
                                                        "type" => "text",
                                                        "text" => 'reporte'
                                                    ],
                                                    [
                                                        "type" => "text",
                                                        "text" => $reporte->folio
                                                    ],
                                                    [
                                                        "type" => "text",
                                                        "text" => 'En ejecución'
                                                    ],
                                                ]
                                            ]
                                        ]
                                    ]
                                ]);
                        $content = json_decode($response->body(), true);

                        $message = Message::create([
                            'fb_message_id' => $content['messages'][0]['id'],
                            'contact_id' => $contact->id,
                            'buttons' => '[]',
                            'header_image' => '',
                            'value' => "Cambio de estatus a {$reporte->estatusOpciones} del reporte: {$reporte->folio}",
                            'is_message_by_contact' => 1,
                            'components' => '',
                            'company_id' => 1,
                        ]);
                        event(new ContactReplies(auth()->user(), $message, $contact));
                        break;
                    default:
                        // \Log::debug("ninguno de los casos");
                        break;

                }
            }
        }

        return response()->json(['status' => 'success', 'message' => 'Cambios guardados correctamente.']);
    }

    public function cancelarReporte($id)
    {
        $reporte = Reporte::find($id);

        if (!$reporte) {
            return redirect()->back()->with('error', 'El reporte no existe.');
        }
        $whatsappPhoneId = Config::where('key', '=', 'whatsapp_phone_number_id')->get()->first()->value;

        $whatsappPermanentAccesToken = Config::where('key', '=', 'whatsapp_permanent_access_token')->get()->first()->value;

        $url = Whatsapp::$facebookAPI . $whatsappPhoneId . '/messages';
        $contact = Contact::where('phone', $reporte->celular)->get()->first();
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
            'Content-Type' => 'application/json',
        ])->post($url, [
                    "messaging_product" => "whatsapp",
                    "recipient_type" => "individual",
                    "to" => $reporte->celular,
                    "type" => "template",
                    "template" => [
                        "name" => "cancelaciones",
                        "language" => [
                            "code" => "es_MX"
                        ],
                        "components" => [
                            [
                                "type" => "body",
                                "parameters" => [
                                    [
                                        "type" => "text",
                                        "text" => $reporte->folio
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]);
        $content = json_decode($response->body(), true);

        $message = Message::create([
            'fb_message_id' => $content['messages'][0]['id'],
            'contact_id' => $contact->id,
            'buttons' => '[]',
            'header_image' => '',
            'value' => "Cancelacion del reporte: {$reporte->folio}",
            'is_message_by_contact' => 1,
            'components' => '',
            'company_id' => 1,
        ]);
        event(new ContactReplies(auth()->user(), $message, $contact));
        $reporte->estatus = 'CANCELADO';
        $reporte->save();

        return redirect()->back()->with('success', 'Reporte cancelado correctamente.');
    }

}
