<?php

namespace Modules\Solicitudes\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Config;
use Barryvdh\DomPDF\Facade\Pdf;
use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Modules\Contacts\Models\Contact;
use Modules\Solicitudes\Models\Solicitud;
use Modules\Wpbox\Events\ContactReplies;
use Modules\Wpbox\Models\Message;
use Modules\Wpbox\Traits\Whatsapp;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

use App\Exports\SolicitudesExport;
use Maatwebsite\Excel\Facades\Excel;
class Main extends Controller
{
    /**
     * Web RoutePath for the name of the routes.
     */
    private $webroute_path = 'solicitudes.';

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

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

    /**
     * Title of this crud.
     */

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

    /**
     * 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 = Solicitud::join('contacts', function ($join) {
            // $join->on(
            //     \DB::raw("contacts.phone"),
            //     '=',
            //     \DB::raw("solicitudes.celular")
            // );
            $join->on(\DB::raw("contacts.phone COLLATE utf8mb4_unicode_ci"), '=', \DB::raw("solicitudes.celular COLLATE utf8mb4_unicode_ci"));

        })
            ->where('estatus', '!=', 'REGISTRANDO')
            ->select(
                'solicitudes.*',
                'contacts.id as id_contacto',
                'contacts.name as nombre_contacto'
            );

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

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

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

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

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

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

            if ($request->filled('fecha_fin')) {
                $query->whereDate('solicitudes.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('solicitudes.id', 'desc')->paginate($perPage)->appends($request->query());


        $items = $query->orderBy('solicitudes.id', 'desc')
            ->paginate(config('settings.paginate'));
            if (!$items->count()) {
                $emptyItem = collect([
                    (object) [
                        'id' => 0,
                        'tipo_solicitud' => '',
                        'descripcion_solicitud' => '',
                        'nombre_persona' => '',
                        'celular' => '',
                        'ubicacion' => '',
                        'estatus' => '',
                        'estatusOpciones' => '',
                        'folio' => '',
                    ]
                ]);
                $items = new LengthAwarePaginator(
                    Collection::make([$emptyItem]), // Los datos vacíos
                    1, // Total de resultados
                    config('settings.paginate'), // Elementos por página
                    1, // Página actual
                    ['path' => request()->url(), 'query' => request()->query()] // Mantener parámetros de búsqueda
                );
            }
        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($_GET) != 0,
            ]
        ]);
    }

    public function sendStatus($id)
    {
        $item = Solicitud::find($id);
        $contact = Contact::where('phone', $item->celular)->first();
        if ($item->estatus == 'NO_SE_RESOLVIO') {
            $item->estatus = 'RESUELTO';
            $item->save();
            return redirect()->route('solicitudes.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_de_reportes",
                            "language" => [
                                "code" => "es_MX"
                            ],
                            "components" => [
                                [
                                    "type" => "header",
                                    "parameters" => [
                                        [
                                            "type" => "image",
                                            "image" => [
                                                "link" => "https://soporte.aplicacionesng.com.mx/uploads/QuJEURUfOQb5YKUVKD2kus6eC3Pjs47KCt9vtPge.jpg"
                                            ]
                                        ]
                                    ]
                                ],
                                [
                                    "type" => "body",
                                    "parameters" => [
                                        [
                                            "type" => "text",
                                            "text" => $item->tipo_solicitud
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]);

            $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('solicitudes.index')->withStatus(__('crud.item_has_been_updated', ['item' => '']));
        } catch (Exception $e) {
            \Log::debug('Error en sendStatus reportes', [$e->getMessage()]);
        }
    }

    public function solicitudesPendientes()
    {
        $reportes = Solicitud::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('solicitudes pendientes.pdf');
    }

    public function reporte_no_resueltas()
    {
        $solicitudes = Solicitud::where('estatus', 'NO_SE_RESOLVIO')
            ->get();

        $pdf = Pdf::loadView('reportes.solicitudes_no_resueltas', ['solicitudes' => $solicitudes]);
        $pdf->setOption([
            "defaultPaperSize" => "letter",
            'isHtml5ParserEnabled' => true,
            "defaultFont" => "tahoma"
        ]);
        return $pdf->download('solicitudes_no_resueltas.pdf');
    }

    public function imprimirSolicitud($id)
    {
        try {
            $solicitud = Solicitud::findOrFail($id);

            $contacto = \DB::selectOne("SELECT id,name FROM contacts c WHERE c.phone = ?", [$solicitud->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.solicitud', [
                'solicitud' => $solicitud,
                'name' => $groupName->name ?? 'Sin Grupo',
                'contact_name' => $contacto->name
            ]);

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

            return $pdf->download('solicitud_folio_S' . $solicitud->id . '.pdf');
        } catch (Exception $e) {
            \Log::debug($e->getMessage());
            // return response()->json(['error' => $e->getTrace()], 500);
        }
    }
    public function guardarCambios(Request $request)
    {

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

        foreach ($cambios as $cambio) {
            $solicitud = Solicitud::find($cambio['id']);
            if ($solicitud) {
                if ($cambio['opcion'] < $solicitud->estatusOpciones) {
                    continue;
                }
                $solicitud->estatusOpciones = $cambio['opcion'];
                $solicitud->save();
                switch ($solicitud->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', $solicitud->celular)->get()->first();
                        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                            'Content-Type' => 'application/json',
                        ])->post($url, [
                                    "messaging_product" => "whatsapp",
                                    "recipient_type" => "individual",
                                    "to" => $solicitud->celular,
                                    "type" => "template",
                                    "template" => [
                                        "name" => "reportar_estatus",
                                        "language" => [
                                            "code" => "es_MX"
                                        ],
                                        "components" => [
                                            [
                                                "type" => "body",
                                                "parameters" => [
                                                    [
                                                        "type" => "text",
                                                        "text" => 'solicitud'
                                                    ],
                                                    [
                                                        "type" => "text",
                                                        "text" => $solicitud->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 {$solicitud->estatusOpciones} del solicitud: {$solicitud->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', $solicitud->celular)->get()->first();
                        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
                            'Content-Type' => 'application/json',
                        ])->post($url, [
                                    "messaging_product" => "whatsapp",
                                    "recipient_type" => "individual",
                                    "to" => $solicitud->celular,
                                    "type" => "template",
                                    "template" => [
                                        "name" => "reportar_estatus",
                                        "language" => [
                                            "code" => "es_MX"
                                        ],
                                        "components" => [
                                            [
                                                "type" => "body",
                                                "parameters" => [
                                                    [
                                                        "type" => "text",
                                                        "text" => 'solicitud'
                                                    ],
                                                    [
                                                        "type" => "text",
                                                        "text" => $solicitud->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 {$solicitud->estatusOpciones} del solicitud: {$solicitud->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 solicitudesExcel(Request $request)
    {

        return Excel::download(new SolicitudesExport, 'todas las solicitudes.xlsx');
    }

    public function cancelarSolicitud($id)
    {
        $solicitud = Solicitud::find($id);

        if (!$solicitud) {
            return redirect()->back()->with('error', 'El solicitud 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',$solicitud->celular)->get()->first();
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $whatsappPermanentAccesToken,
            'Content-Type' => 'application/json',
        ])->post($url, [
            "messaging_product" => "whatsapp",
            "recipient_type" => "individual",
            "to" => $solicitud->celular,
            "type" => "template",
            "template" => [
                "name" => "cancelaciones",
                "language" => [
                    "code" => "es_MX"
                ],
                "components" => [
                    [
                        "type" => "body",
                        "parameters" => [
                            [
                                "type" => "text",
                                "text" => $solicitud->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 solicitud: {$solicitud->folio}",
            'is_message_by_contact' => 1,
            'components' => '',
            'company_id' => 1,
        ]);
        event(new ContactReplies(auth()->user(), $message, $contact));
        $solicitud->estatus = 'CANCELADO';
        $solicitud->save();

        return redirect()->back()->with('success', 'Solicitud cancelada correctamente.');
    }
}
