<?php

namespace App\Http\Controllers\Web\Current\Admin;

use App\Events\CampaignDoneEvent;
use App\Events\TicketCreatedEvent;
use App\Events\TicketUpdatedEvent;
use App\Helpers\FilterHelper;
use App\Http\Controllers\Controller;
use App\Mail\WordMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Inertia\Inertia;

use App\Models\User;
use App\Models\DocumentConfig;
use App\Models\GeneralSettings;
use App\Models\Rider;
use App\Models\RiderEarning;
use App\Models\RiderPayout;
use App\Models\Staff;
use App\Models\Ticket;
use App\Models\TicketInvite;
use App\Models\TicketMessage;
use App\Models\Trip;
use App\Models\UserWalletTransaction;
use App\Notifications\StaffNotification;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;

class TicketController extends Controller
{
    public function __construct() {}

    public function index(Request $request)
    {
        $staff = auth("staff")->user();

        $from = isset($request->from) ? date("Y-m-d", strtotime($request->from)) : today()->startOfMonth();
        $to =  isset($request->to) ? date("Y-m-d", strtotime($request->to)) : today()->endOfMonth();

        $tickets = $staff->tickets()
            ->whereDate('created_at', ">=", $from)
            ->whereDate('created_at', "<=", $to)
            ->orderBy("updated_at", "desc")
            ->filter($request->only('filter'))
            ->get();

        if ($staff->role->value == "superadmin") {
            $tickets = Ticket::whereDate('created_at', ">=", $from)
                ->whereDate('created_at', "<=", $to)
                ->orderBy("updated_at", "desc")
                ->filter($request->only('filter'))
                ->get();
        }

        // $gg = date("Y-m-d H:i:s", strtotime($from));
        // dd($gg);

        $t = $tickets->map(function ($r) use ($staff) {
            return [
                "id" => $r->id,
                "uuid" => $r->uuid,
                "is_open" => $r->is_open,
                "status" => $r->status,
                "title" => $r->title ?? "",
                "initiator" => $r->staff_id == $staff->id ? "you" : $r->staff->fullname ?? "",
                "last_updated" => FilterHelper::dateObj($r->updated_at),
            ];
        });

        return Inertia::render("Admin/Ticket/Index", [
            'page_title' => "Support Tickets",
            'tickets' => $t,
            'filter_list' => [
                'all',
                'pending',
                'open',
                'resolved',
                'unresolved',
            ],
            'filters' => $request->only("filter"),
            'from' => $from,
            'to' => $to,
        ]);
    }

    public function create(Request $request)
    {
        $tickets = Ticket::all();
        $attached_to = null;

        if ($request->find_attached == true) {
            if ($request->find_uuid && $request->find_type) {
                if ($request->find_type == "staff") {
                    $rs = Staff::where("uuid", $request->find_uuid)->first();
                    if ($rs) {
                        $attached_to = $rs->fullname . " - " . $rs->email;
                    }
                }

                if ($request->find_type == "user") {
                    $ru = User::where("uuid", $request->find_uuid)->first();
                    if ($ru) {
                        $attached_to = $ru->fullname . " - " . $ru->email;
                    }
                }

                if ($request->find_type == "rider") {
                    $rr = Rider::where("uuid", $request->find_uuid)->first();
                    if ($rr) {
                        $attached_to = $rr->fullname . " - " . $rr->mobile;
                    }
                }
            }
        }

        if ($request->create_ticket == true) {
            $validator = Validator::make($request->all(), [
                'attached_to' => 'required',
                'attached_to_id' => 'required',
                'title' => 'required',
                'message' => 'required',
            ]);

            if ($validator->fails()) {
                return
                    back()
                    ->with('poperror', $validator->messages()->first());
            } else {
                $person = null;
                if ($request->attached_to == "staff") {
                    $person = Staff::where("uuid", $request->attached_to_id)->first();
                }

                if ($request->attached_to == "user") {
                    $person = User::where("uuid", $request->attached_to_id)->first();
                }

                if ($request->attached_to == "rider") {
                    $person = Rider::where("uuid", $request->attached_to_id)->first();
                }

                if (!$person) {
                    return
                        back()
                        ->with('poperror', "Wrong ID");
                }

                $staff = auth("staff")->user();

                $t = new Ticket();
                $t->uuid = strtoupper(Str::random(6));
                $t->staff_id = $staff->id;
                $t->title = $request->title;
                $t->message = $request->message;
                $t->attached_to = $request->attached_to;
                $t->attached_to_id = $person->id;
                $t->save();

                if ($request->attached_to == "staff") {
                    $person->notify(new StaffNotification("New Ticket #$t->uuid", $request->title, "/portal/ticket/$t->id"));
                }

                TicketCreatedEvent::dispatch($t->id, $staff->id);

                return redirect()->route("admin.ticket.view", $t->id)
                    ->with('popsuccess', "Ticket Created");
            }
        }

        return Inertia::render("Admin/Ticket/Create", [
            'page_title' => "Create Ticket",
            'tickets' => $tickets,
            'attached_to' => $attached_to,
        ]);
    }

    public function view($ticket_id, Request $request)
    {
        $ticket = Ticket::find($ticket_id);
        $staff = auth("staff")->user();

        if (!$ticket) {
            return redirect()->route("admin.ticket")
                ->with('poperror', "Ticket Not Found");
        }

        if ($request->reply_ticket == true) {
            $validator = Validator::make($request->all(), [
                'message' => 'required',
            ]);

            if ($validator->fails()) {
                return
                    back()
                    ->with('poperror', $validator->messages()->first());
            } else {

                $t = new TicketMessage();
                $t->uuid = strtoupper(Str::random(5));
                $t->staff_id = $staff->id;
                $t->ticket_id = $ticket->id;
                $t->message = $request->message;
                $t->save();

                $ticket->status = "open";
                $ticket->save();

                TicketInvite::where("ticket_id", $ticket->id)->where("staff_id", $staff->id)->update(["is_accepted" => 1]);

                TicketUpdatedEvent::dispatch($ticket->id, $staff->id);

                return back()
                    ->with('popsuccess', "Reply Done");
            }
        }

        if ($request->send_invite == true) {
            $validator = Validator::make($request->all(), [
                'staff_id' => 'required',
            ]);

            if ($validator->fails()) {
                return
                    back()
                    ->with('poperror', $validator->messages()->first());
            } else {

                $s = Staff::where("uuid", $request->staff_id)->first();
                if (!$s) {
                    return
                        back()
                        ->with('poperror', "Invalid Staff ID");
                }

                if ($s->id == $ticket->staff_id) {
                    return
                        back()
                        ->with('poperror', "you cant invite yourself");
                }

                if (in_array($s->id, $ticket->staffs->toArray())) {
                    return
                        back()
                        ->with('poperror', "$s->fullname already invited");
                }

                $t = new TicketInvite();
                $t->staff_id = $s->id;
                $t->invited_by_id = $staff->id;
                $t->ticket_id = $ticket->id;
                $t->message = $request->message;
                $t->save();

                $s->notify(new StaffNotification("Ticket Invitation #$ticket->uuid", $t->message, "/portal/ticket/$ticket->id"));

                $ticket_link = route("admin.ticket.view", $ticket->id);

                $m = "<p>
                        Hi, $s->fullname.
                        <br/>
                        <br/>
                        You have a ticket invitation on Shride Portal. Follow the link below.
                        <br/>
                        <br/>
                        Invitation Message
                        <br/>
                        $t->message_html
                        <br/>
                        <br/>
                        <a href='$ticket_link'>$ticket_link </a>
                       </p>
                ";

                try {
                    Mail::to($s->email)->send(new WordMail("Ticket Invitation #$ticket->uuid", $m));
                } catch (\Throwable $e) {
                }

                return back()
                    ->with('popsuccess', "Invite Sent");
            }
        }

        if ($request->update_status == true) {
            $ticket->status = $request->status;
            $ticket->save();

            TicketUpdatedEvent::dispatch($ticket->id, $staff->id);

            return back()
                ->with('popsuccess', "Status Updated");
        }

        $t = [
            "id" => $ticket->id,
            "uuid" => $ticket->uuid,
            "is_open" => $ticket->is_open,
            "title" => $ticket->title,
            "message" => $ticket->message,
            "message_html" => $ticket->message_html,
            "staff_fullname" => $ticket->staff_fullname,
            "staff_id" => $ticket->staff_id,
            "attached_to" => $ticket->attached_to,
            "attached_to_id" => $ticket->attached_to_id,
            "status" => $ticket->status,
            "for" => $ticket->for() ? ["fullname" => $ticket->for()->fullname, "uuid" => $ticket->for()->uuid] : null,
            "created_at_obj" => $ticket->created_at_obj,
        ];

        $messages = $ticket->messages()->orderBy("id", "asc")->get();
        $m = $messages->map(function ($r) {
            return [
                "id" => $r->id,
                "uuid" => $r->uuid,
                "message" => $r->message,
                "message_html" => $r->message_html,
                "staff_fullname" => $r->staff_fullname,
                "staff_id" => $r->staff_id,
                "created_at_obj" => $r->created_at_obj,
            ];
        });

        $i = $ticket->invitations->map(function ($r) {
            return [
                "id" => $r->id,
                "staff" => $r->staff ?
                    [
                        "fullname" => $r->staff->fullname ?? "",
                        "uuid" => $r->staff->uuid ?? "",
                        "avatar" => $r->staff->avatar_url ?? ""
                    ]
                    : null,
                "is_accepted" => $r->is_accepted,
                "created_at_obj" => $r->created_at_obj,
            ];
        });

        return Inertia::render("Admin/Ticket/View", [
            'page_title' => "Ticket #$ticket->uuid",
            'ticket' => $t,
            'messages' => $m,
            'invites' => $i
        ]);
    }
}
