<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Ticket;
use App\Models\TicketMeta;
use App\Models\TicketNote;
use App\Models\Comment;
use App\Models\Response;
use App\Models\Company;
use App\Models\CompanyMeta;
use App\Models\Tag;
use Carbon\Carbon;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class TicketController extends Controller
{
    public function get_canned_responses(){
         $companyId = getSelectedCompany();
        return  CompanyMeta::where('company_id', $companyId)->where('key', 'canned_responses')->get();
    }
    
    public function allTickets()
    {
        $companyId = getSelectedCompany();
        $tickets = get_current_company_tickets(['type' => 'chat']);
        $tags = Tag::where('company_id', $companyId)->get();
        return view('all-tickets', ['tickets' => $tickets, 'tags' => $tags]);
    }
    
    public function waiting()
    {
       
        $tickets = get_current_company_tickets(['status' => 'waiting']);
        return view('waiting', ['tickets' => $tickets]);
    }
    
    public function showTicket($id)
    {
        $companyId = getSelectedCompany();
        $tickets = get_current_company_tickets([
            
                'type' => 'inbox',
                'orderby' => 'id',
                'order' => 'desc',
                'with' => 'lastResponse'
                
                ]);
                
        $single_ticket = Ticket::find($id);
                
                
        $messages = [];
        $canned_response = $this->get_canned_responses();
        $email_signature = CompanyMeta::where('company_id', $companyId)->where('type', 'Email Signature')->first();
        
        return view('show-ticket', [
                'tickets' => $tickets,
                'single_ticket' => $single_ticket,
                'messages' => $messages,
                'canned_response' => $canned_response,
                'email_signature' => $email_signature?$email_signature->value:''
        ]);
    }
    
    public function updateStatus(Request $request, $ticketId)
    {
        $request->validate([
            'status' => 'required|in:open,waiting,done',
        ]);
        
        $ticket = Ticket::find($ticketId);
        $ticket->status = $request->status;
        $ticket->save();
    
        // Return a response if necessary
        return response()->json(['message' => 'Ticket status updated successfully']);
    }
    
    public function updateTicket(Request $request, $ticketId)
    {
        $ticket = Ticket::find($ticketId);
        //Update Ticket
        if(isset($request->priority)) {
            $ticket->priority = $request->priority;
        }
        if(isset($request->user_assigned)) {
            $ticket->user_assigned = $request->user_assigned;
        }
        $ticket->save();
        
        return response()->json(['success' => true, 'message' => 'Ticket Updated successfully!']);
    }
    
    public function storeTags(Request $request)
    {
        $company = getSelectedCompany();
        $ticket_id = $request->ticket_id;
        
        $tags = json_decode($request->tags);
        
        TicketMeta::where('key','tags')->where('ticket_id',$ticket_id)->delete();
       
        foreach($tags as $tag)
        {
            
            TicketMeta::create(
                ['ticket_id' => $ticket_id, 'key' => 'tags',
                'value' => $tag->value, 'type' => 'string']
            );
            
            //Update Tags Table
            Tag::updateOrCreate([
               'company_id' => $company,
               'name' => $tag->value
            ],[
               'company_id' => $company,
               'name' => $tag->value,
               'type' => 'inbox'
            ]);
            
            
            
            //Update Company Meta Table
            
            
            
            // CompanyMeta::updateOrCreate([
            //   'company_id' => $company,
            //   'value' => $tag->value
            // ],[
            //   'company_id' => $company,
            //   'value' => $tag->value,
            //   'key' => 'tag',
            //   'type' => 'tags'
            // ]);
        }
        
        return response()->json(['success' => true, 'message' => 'Tags Added Successfully']);
    }
    
    public function AssignTicket(Request $request)
    {
        $this->validate($request, [
            'user_assigned' => 'required|integer',
            'message' => 'required|string',
            'ticket_ids' => 'required|string',
        ]);
        
        $companyId = getSelectedCompany();
        
        $ticketIds = explode(',', $request->ticket_ids);
        foreach ($ticketIds as $ticket_id) {
            $ticket = Ticket::find($ticket_id);
        
            if ($ticket) {
                // Update Ticket
                $ticket->user_assigned = $request->user_assigned;
                $ticket->save();
                
                //Send Mail
                $company = Company::find($companyId);
                sendEmailViaMailgun($company->domain, $company->email, $ticket->from_email, $ticket->subject, $request->message);
                //Create Response
                $formattedMessage = '<p>' . $request->message . '</p>';
                createResponse($ticket_id,$formattedMessage,auth()->id());
            }
        }
        
        return response()->json(['success' => true, 'message' => 'Post Assigned Successfully']);
    }
    
    public function deleteTickets(Request $request)
    {
        $this->validate($request, [
            'ticket_ids' => 'required|string',
        ]);
        
        $ticketIds = explode(',', $request->ticket_ids);
        foreach ($ticketIds as $ticket_id) {
            $ticket = Ticket::find($ticket_id);
        
            if ($ticket) {
                // Delete Ticket
                Comment::where('ticket_id', $ticket_id)->delete();
                TicketMeta::where('ticket_id', $ticket_id)->delete();
                Response::where('ticket_id', $ticket_id)->delete();
                TicketNote::where('ticket_id', $ticket_id)->delete();
                //Delete Attachments
                $folderPath = "tickets/$ticket_id"; // Adjust the path according to your structure

                if (Storage::disk('public')->exists($folderPath)) {
                    Storage::disk('public')->deleteDirectory($folderPath);
                }
                $ticket->delete();
            }
        }
        
        return response()->json(['success' => true, 'message' => 'Tickets Deleted Successfully']);
    }
    
    public function updateTicketStatus(Request $request)
    {
        $this->validate($request, [
            'ticket_ids' => 'required|string',
            'status' => 'required|string'
        ]);
        
        $ticketIds = explode(',', $request->ticket_ids);
        foreach ($ticketIds as $ticket_id) {
            $ticket = Ticket::find($ticket_id);
        
            if ($ticket) {
                // Delete Ticket
                $ticket->status = $request->status;
                $ticket->save();
            }
        }
        
        return response()->json(['success' => true, 'message' => 'Tickets Status Updated Successfully']);
    }
    
    public function filter(Request $request)
    {
        $this->validate($request, [
            'filter' => 'required|string',
            'status' => 'required|string',
        ]);
        
        $companyId = getSelectedCompany();
        $company = get_company('id',$companyId);
        $now = \Carbon\Carbon::now();
        
        if(isset($request->type)) {
            $tickets = Ticket::where('to_email', $company->email)->where('type', $request->type)->where('status', '!=', 'done')->orderBy('created_at','desc');
        } else {
            $tickets = Ticket::where('to_email', $company->email)->where('status', '!=', 'done')->orderBy('created_at','desc');
        }
        
        if($request->filter == 'Assigned to') {
            $all_tickets = $tickets->where('user_assigned', $request->status)->get();
            return response()->json(['tickets' => $all_tickets]);
        } elseif($request->filter == 'With activity') {

            if ($request->status === 'last 24 hours') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subDay());
            } elseif ($request->status === 'last 3 days') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subDays(3));
            } elseif ($request->status === 'last week') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subWeek());
            } elseif ($request->status === 'last month') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subMonth());
            } elseif ($request->status === 'last 3 months') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subMonths(3));
            } elseif ($request->status === 'last 6 months') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subMonths(6));
            } elseif ($request->status === 'last year') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subYear());
            } elseif ($request->status === 'the past 2 years') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subYears(2));
            } elseif ($request->status === 'the past 3 years') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subYears(3));
            } elseif ($request->status === 'the past 4 years') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subYears(4));
            } elseif ($request->status === 'the past 5 years') {
                $all_tickets = $tickets->where('updated_at', '>=', $now->subYears(5));
            }
            
            $activity_tickets = $all_tickets->get();
            return response()->json(['tickets' => $activity_tickets]);
        } elseif($request->filter == 'No activity') {
            
            if ($request->status === 'last 24 hours') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subDay());
            } elseif ($request->status === 'last 3 days') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subDays(3));
            } elseif ($request->status === 'last week') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subWeek());
            } elseif ($request->status === 'last month') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subMonth());
            } elseif ($request->status === 'last 3 months') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subMonths(3));
            } elseif ($request->status === 'last 6 months') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subMonths(6));
            } elseif ($request->status === 'last year') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subYear());
            } elseif ($request->status === 'the past 2 years') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subYears(2));
            } elseif ($request->status === 'the past 3 years') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subYears(3));
            } elseif ($request->status === 'the past 4 years') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subYears(4));
            } elseif ($request->status === 'the past 5 years') {
                $all_tickets = $tickets->where('updated_at', '<=', $now->subYears(5));
            }

            
            $no_activity_tickets = $all_tickets->get();
            return response()->json(['tickets' => $no_activity_tickets]);
        } elseif($request->filter == 'Spam') {
            if($request->status == 'marked as spam') {
                $all_tickets = $tickets->where('status', 'spam')->get();
                return response()->json(['tickets' => $all_tickets]);
            } else {
                $all_tickets = $tickets->where('status', '!=', 'spam')->get();
                return response()->json(['tickets' => $all_tickets]);
            }
        } elseif($request->filter == 'Status') {
            $all_tickets = $tickets->where('status', $request->status)->get();
            return response()->json(['tickets' => $all_tickets]);
        } elseif($request->filter == 'Tags') {
            $ticket_meta = TicketMeta::where('value', $request->status)->pluck('ticket_id')->toArray();
            if(isset($request->type)) {
                $all_tickets = Ticket::where('to_email', $company->email)->where('type', $request->type)->where('status', '!=', 'done')->orderBy('created_at','desc')->whereIn('id', $ticket_meta)->get();
            } else {
                $all_tickets = Ticket::where('to_email', $company->email)->orderBy('created_at','desc')->where('status', '!=', 'done')->whereIn('id', $ticket_meta)->get();
            }
            return response()->json(['tickets' => $all_tickets]);
        }
    }
    
    public function defaultAllTickets(Request $request)
    {
        $companyId = getSelectedCompany();
        $company = get_company('id',$companyId);
        if(isset($request->type)) {
            $tickets = get_current_company_tickets(['type' => $request->type]);
        } else {
            $tickets = get_current_company_tickets();
        }
        return response()->json(['tickets' => $tickets]);
    }
}
