<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Report;
use App\Models\ReportComment;
use App\Models\FinishedContracts;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use OneSignal;
use Stripe\Stripe;
use Stripe\Refund;

class ReportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //
        $request->session()->put('search', $request
              ->has('search') ? strip_tags($request->get('search')) : ($request->session()
              ->has('search') ? strip_tags($request->session()->get('search')) : ''));

        $request->session()->put('field', $request
                ->has('field') ? strip_tags($request->get('field')) : ($request->session()
                ->has('field') ? strip_tags($request->session()->get('field')) : 'id'));

        $request->session()->put('sort', $request
                ->has('sort') ? strip_tags($request->get('sort')) : ($request->session()
                ->has('sort') ? strip_tags($request->session()->get('sort')) : 'asc'));

        //$headers = $request->get('header') != '' ? $request->get('header') : -1;

        $reports = new Report();
        $reports = $reports->where('id', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                       ->orwhere('contract_id', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                       ->orwhere('moderator_id', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                       ->orwhere('veredict', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                        ->orderBy(strip_tags($request->session()->get('field')), strip_tags($request->session()->get('sort')))
                        ->paginate(10);

        if ($request->ajax()) {
            return view('reports.index', compact('reports'));
          } else {
            return view('reports.ajax', compact('reports'));
          }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Report  $report
     * @return \Illuminate\Http\Response
     */
    public function show(Report $report)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Report  $report
     * @return \Illuminate\Http\Response
     */
    public function veredict(Request $request, $id)
    {
        if ($request->isMethod('get'))
            return view('reports.veredict', ['report' => Report::with('finishedcontracts')->find($id)]);

        $rules = [
            'veredict'        => 'required|string',
            'contract_status' => 'nullable|in:8,9',
        ];

        $messages = [
            'veredict.required' => 'Se requiere un veredicto',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return redirect()->back()->withInput($request->all())->withErrors($validator);
        }

        $report = Report::with('finishedcontracts')->find($id);
        $report->veredict = strip_tags($request->veredict);
        $report->save();

        if ($request->filled('contract_status')) {
            $contract  = $report->finishedcontracts;
            $newStatus = (int) $request->contract_status;

            if ($newStatus === 8) {
                $tid = $contract->transaction_id ?? null;
                if ($tid && $tid !== 'NO APPLY' && !str_starts_with($tid, 'BYPASS_')) {
                    try {
                        Stripe::setApiKey(env('STRIPE_SECRET'));
                        Refund::create(['payment_intent' => $tid]);
                    } catch (\Exception $e) {
                        // reembolso fallido: se registra pero no bloquea el flujo
                    }
                }
            }

            $contract->status_id = $newStatus;
            $contract->save();
        }

        return redirect('reports');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Report  $report
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Report $report)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Report  $report
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Report::destroy($id);
        return redirect('reports');
    }

    public function getcomments(Request $request, $id)
    {
        $user     = Auth::user();
        $report   = Report::with('finishedcontracts.suppliers')->find($id);

        if (!$report) {
            return response()->json(['message' => 'Reporte no encontrado'], 404);
        }

        $contract       = $report->finishedcontracts;
        $supplierUserId = $contract->suppliers->user_id ?? null;

        if ($user->id !== $contract->user_id && $user->id !== $supplierUserId) {
            return response()->json(['message' => 'No autorizado'], 403);
        }

        $comments = ReportComment::with('user')
            ->where('report_id', $id)
            ->orderBy('created_at', 'asc')
            ->get()
            ->map(function ($c) use ($contract, $supplierUserId) {
                $isSupplier = $c->user_id === $supplierUserId;
                $isClient   = $c->user_id === $contract->user_id;
                return [
                    'id'          => $c->id,
                    'sender_id'   => $c->user_id,
                    'sender_name' => $isSupplier
                                         ? ($contract->suppliers->company_name ?? null)
                                         : ($c->user->name ?? null),
                    'role_id'     => $c->user->role_id ?? null,
                    'sender_type' => !$isClient && !$isSupplier ? 'moderator' : null,
                    'comment'     => $c->comment,
                    'created_at'  => $c->created_at,
                ];
            });

        return response()->json($comments);
    }

    public function storecomment(Request $request, $id)
    {
        $validator = Validator::make($request->all(), ['comment' => 'required|string']);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $user   = Auth::user();
        $report   = Report::with('finishedcontracts.suppliers')->find($id);

        if (!$report) {
            return response()->json(['message' => 'Reporte no encontrado'], 404);
        }

        $contract       = $report->finishedcontracts;
        $supplierUserId = $contract->suppliers->user_id ?? null;

        if ($user->id !== $contract->user_id && $user->id !== $supplierUserId) {
            return response()->json(['message' => 'No autorizado'], 403);
        }

        $comment            = new ReportComment();
        $comment->report_id = $id;
        $comment->user_id   = $user->id;
        $comment->comment   = strip_tags($request->comment);
        $comment->save();

        $supplierUserId = $contract->suppliers->user_id ?? null;
        $isSupplier     = $user->id === $supplierUserId;
        $isClient       = $user->id === $contract->user_id;

        $recipientId = $isClient ? $supplierUserId : $contract->user_id;
        if ($recipientId) {
            try {
                OneSignal::sendNotificationCustom([
                    'include_external_user_ids' => [(string) $recipientId],
                    'contents' => [
                        'es' => $user->name . ': ' . $comment->comment,
                        'en' => $user->name . ': ' . $comment->comment,
                    ],
                    'headings' => [
                        'es' => 'Nueva actividad en tu reporte',
                        'en' => 'New activity on your report',
                    ],
                ]);
            } catch (\Exception $e) {}
        }

        return response()->json([
            'id'          => $comment->id,
            'sender_id'   => $user->id,
            'sender_name' => $isSupplier ? ($contract->suppliers->company_name ?? null) : $user->name,
            'role_id'     => $user->role_id,
            'sender_type' => !$isClient && !$isSupplier ? 'moderator' : null,
            'comment'     => $comment->comment,
            'created_at'  => $comment->created_at,
        ], 201);
    }

    public function getsupplierreports(Request $request)
    {
        $user = Auth::user();

        if (!$user->suppliers) {
            return response()->json(['success' => false, 'message' => 'No tienes un perfil de proveedor registrado'], 400);
        }

        $contractIds = FinishedContracts::where('supplier_id', $user->suppliers->id)->pluck('id');

        $reports = Report::with([
                'finishedcontracts.suppliers.user',
                'finishedcontracts.categories',
                'finishedcontracts.technician.user',
            ])
            ->whereIn('contract_id', $contractIds)
            ->orderBy('created_at', 'desc')
            ->get();

        $data = $reports->map(function ($report) {
            $contract = $report->finishedcontracts;
            $technician = $contract->technical_id
                ? ($contract->technician->user->name ?? null)
                : ($contract->suppliers->user->name ?? null);
            return [
                'id'          => $report->id,
                'technician'  => $technician,
                'company'     => $contract->suppliers->company_name ?? null,
                'category'    => $contract->categories->name ?? null,
                'en_category' => $contract->categories->en_name ?? null,
                'appointment' => $contract->appointment,
                'address'     => $contract->address,
                'amount'      => $contract->amount,
                'veredict'    => $report->veredict,
            ];
        });

        return response()->json($data);
    }

    public function getreports(Request $request)
    {
        $user = Auth::user();

        $contractIds = FinishedContracts::where('user_id', $user->id)->pluck('id');

        $reports = Report::with([
                'finishedcontracts.suppliers.user',
                'finishedcontracts.categories',
            ])
            ->whereIn('contract_id', $contractIds)
            ->orderBy('created_at', 'desc')
            ->get();

        $data = $reports->map(function ($report) {
            $contract = $report->finishedcontracts;
            return [
                'id'          => $report->id,
                'supplier'    => $contract->suppliers->user->name ?? null,
                'company'     => $contract->suppliers->company_name ?? null,
                'category'    => $contract->categories->name ?? null,
                'en_category' => $contract->categories->en_name ?? null,
                'appointment' => $contract->appointment,
                'address'     => $contract->address,
                'amount'      => $contract->amount,
                'veredict'    => $report->veredict,
            ];
        });

        return response()->json($data);
    }

    public function report(Request $request) {

      $rules = [
        'contract_id' => 'required|numeric',
        'comment' => 'required|string',
      ];

      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails()) {
        return redirect()->back()->withInput($request->all())->withErrors($validator);
      } else {

        $user = Auth::user();
        $contract = FinishedContracts::where('id', $request->contract_id)->first();

        if ($user->id == $contract->user_id) {
          $report = new Report();
          $report->contract_id = $contract->id;

          $moderator = User::where('role_id', 5)->get();
          if ($moderator != '[]') {
            $report->moderator_id = $moderator->random()->id;
          } else {
            $report->moderator_id = User::where('role_id', 7)->first()->id;
          }
          $report->save();

          $reportcomment = new ReportComment();
          $reportcomment->report_id = $report->id;
          $reportcomment->user_id = $user->id;
          $reportcomment->comment = strip_tags($request->comment);
          $reportcomment->save();

          $contract->status_id = 6;
          $contract->save();

          return response()->json([
              'message' => 'Reporte registrado con éxito, nos comunicaremos con usted por correo electrónico a la brevedad para continuar con el caso'
          ]);
        }
      }
    }
}
