<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Branch;
use App\Models\Transfer;
use App\Models\Product;
use App\Models\Inventory;
use App\Models\Carmodel;
use App\Models\Carvarient;
use App\Http\Requests\TransferRequest;
use App\Http\Requests\TransferAcceptRequest;
use App\Models\Notifications;
use Carbon\Carbon;
use Auth, DB, Mail, Validator, File, DataTables;
use App\Models\Ticket;

class TicketController extends Controller{
            
        public function index(Request $request)
        {
            
            if ($request->ajax()) {
                if (auth()->user()->id == 1) {
                    $data = Ticket::orderBy('id', 'DESC')->get();
                } else {
                    $data = Ticket::where('user_id', auth()->user()->id)
                                  ->orderBy('id', 'DESC')->get();
                }
        
                return Datatables::of($data)
                    ->addIndexColumn()
                    
                    ->addColumn('ticket_no', function ($data) {
                        $date = \Carbon\Carbon::parse($data->created_at)->format('dmY');
                        $id = str_pad($data->id, 2, '0', STR_PAD_LEFT);
                        return 'Ticket_' . $id . '_' . $date;
                    })
                    // Display user full name
                    ->addColumn('user_name', function ($data) {
                        return $data->user->first_name . ' ' . $data->user->last_name;
                    })
        
                    // Convert status to human-readable format
                    ->editColumn('status', function ($data) {
                        if($data->status == 'in_progress'){
                            return 'Work In Progress';
                        } elseif($data->status == 'pending'){
                            return 'Open';
                        } elseif($data->status == 'completed'){
                            return 'Completed';
                        } elseif($data->status == 'cancel'){
                            return 'Approve Or Cancel';
                        }
                    })
        
                    // Display priority
                    ->addColumn('priority', function ($data) {
                        return ucfirst($data->priority ?? '-');
                    })
        
                    // Display date (format as needed)
                    ->addColumn('date', function ($data) {
                        return $data->date ? \Carbon\Carbon::parse($data->date)->format('d-m-Y') : '-';
                    })
                    
                    // Display created date (format as needed)
                    ->addColumn('created_at', function ($data) {
                        return $data->created_at ? \Carbon\Carbon::parse($data->created_at)->format('d-m-Y') : '-';
                    })
        
                    // Display image thumbnail if exists
                    ->addColumn('image', function ($data) {
                        if ($data->image) {
                            $url = asset('storage/' . $data->image);
                            return '<img src="' . $url . '" alt="Image" width="50" height="50">';
                        }
                        return '-';
                    })
        
                    // Action buttons
                    ->addColumn('action', function ($data) {
                        $return = '<div class="btn-group">';
                        $return .= '<a href="' . route('ticket.view', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs"><i class="fa fa-eye"></i></a> &nbsp;';
                        $return .= '<a href="' . route('ticket.edit', ['id' => base64_encode($data->id)]) . '" class="btn btn-default btn-xs"><i class="fa fa-pencil"></i></a> &nbsp;';
                        $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown"><i class="fa fa-bars"></i></a> &nbsp;';
                        $return .= '<ul class="dropdown-menu">';
                        $return .= '<li><a class="dropdown-item" href="javascript:;" onclick="support_ticket(this);" data-status="' . $data->status . '" data-id="' . $data->id . '">Change Status</a></li>';
                        $return .= '</ul>';
                        $return .= '</div>';
                        return $return;
                    })
        
                    // Important: allow HTML rendering
                    ->rawColumns(['action', 'status', 'image'])
        
                    ->make(true);
            }
        
            return view('ticket.index');
        }

 
        public function create(Request $request)
        {
            return view('ticket.create');
        }
        public function ticket_save(Request $request)
        {
            $ticket = new Ticket();
            $ticket->user_id = auth()->user()->id;
            $ticket->contact = $request->input('contact');
            $ticket->email_id = $request->input('email');
            $ticket->title = $request->input('title');
            $ticket->description = $request->input('description');
            $ticket->status = 'pending';
        
            if ($request->hasFile('ticket_image')) {
                $image_arr = $request->file('ticket_image');
                $uploaded_file_names = [];
            
                foreach ($image_arr as $file) {
                    $filenameWithExt = $file->getClientOriginalName();
                    $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                    $extension = $file->getClientOriginalExtension();
                    $filenameToStore = time() . '_' . str_replace(' ', '_', $filename) . '.' . $extension;
            
                    $uploadPath = public_path('/uploads/tickets/');
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath, 0777, true);
                    }
            
                    $file->move($uploadPath, $filenameToStore);
                    $uploaded_file_names[] = $filenameToStore;
                }
            
                // Save as comma-separated list
                $ticket->ticket_image = implode(',', $uploaded_file_names);
            }
            
        
            $ticket->save();
            
            $ticket->ticket_no = 'Ticket_' . str_pad($ticket->id, 2, '0', STR_PAD_LEFT) . '_' . now()->format('dmY');
            $ticket->save();

            // $email = 'rmvala9@gmail.com';
                    
            //  Mail::send('ticket/mail_template',["name"=>$request->input('name'),'contact_no'=>$request->input('contact'),'email'=>$request->input('email'),'title'=>$request->input('title'),'description'=>$request->input('description')], function($message) use ($email){
            //     // $message->parameters($url); 
            //      $message->to($email);
            //      $message->subject('Ticket Created');  
            //     });
            
            \DB::table('logs')->insert([
                'module_nm' => 'ticket_create',
                'module_id' => $ticket->id,
                'status' => $ticket->status ?? 'pending',
                'remark' => $ticket->description,
                'created_by' => auth()->id(),
                'created_at' => now(),
            ]);

            Notifications::create([
                'user_id'            => Auth::id(),                     // or assign to admin if needed
                'notification_text'  => 'New ticket created: ' . $ticket->title,
                'notification_link'  => route('ticket.view', $ticket->id), // or a relative link
                'status'             => 'unread',
                'created_at'         => Carbon::now(),
                'created_by'         => Auth::id(),
            ]);

            try {
                $email = 'hiralhada1501@gmail.com';
            
                Mail::send([], [], function ($message) use ($email) {
                    $message->to($email)
                            ->subject('Ticket Created Successfully')
                            ->setBody('<p>Your support ticket has been created successfully. Our team will get back to you soon.</p>', 'text/html');
                });
            } catch (\Exception $e) {
                \Log::error('Ticket creation email failed: ' . $e->getMessage());
            }
    
            return redirect()->back()->with(['message' => $ticket->ticket_no . ' generated successfully']);

        }


        public function view(Request $request)
        {
             $id = base64_decode($request->id);
             $data = Ticket::where(['id' => $id])->first(); 
             return view('ticket.view',compact('data'));
        }

        public function edit(Request $request)
        {
            $id = base64_decode($request->id);
            $data = Ticket::with('user')->findOrFail($id);
            return view('ticket.edit', compact('data'));
        }


        public function update(Request $request)
        {
            $id = $request->id;
            $ticket = Ticket::findOrFail($id);
        
            // Update basic fields
            $ticket->contact = $request->input('contact');
            $ticket->email_id = $request->input('email');
            $ticket->title = $request->input('title');
            $ticket->description = $request->input('description');
            $ticket->comment = $request->input('comment');
        
            if ($request->filled('status')) {
                $ticket->status = $request->input('status');
            }
        
            if ($request->hasFile('ticket_image')) {
                $image_arr = $request->file('ticket_image');
                $uploaded_file_names = [];
        
                foreach ($image_arr as $file) {
                    $filenameWithExt = $file->getClientOriginalName();
                    $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                    $extension = $file->getClientOriginalExtension();
                    $filenameToStore = time() . '_' . str_replace(' ', '_', $filename) . '.' . $extension;
        
                    $uploadPath = public_path('/uploads/tickets/');
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath, 0777, true);
                    }
        
                    $file->move($uploadPath, $filenameToStore);
                    $uploaded_file_names[] = $filenameToStore;
                }
        
                $existing_images = $ticket->ticket_image ? explode(',', $ticket->ticket_image) : [];
                $ticket->ticket_image = implode(',', array_merge($existing_images, $uploaded_file_names));
            }
        
            $ticket->save();
            
            \DB::table('logs')->insert([
                'module_nm' => 'ticket_update',
                'module_id' => $ticket->id,
                'status' => $ticket->status ?? 'pending',
                'remark' => $ticket->comment ?? $ticket->description,
                'created_by' => auth()->id(),
                'created_at' => now(),
            ]);
        
            return redirect()->route('tickets')->with('success', $ticket->ticket_no . ' updated successfully');
        }

   
        
        public function status_update(Request $request)
        {
            try {
                $ticket = Ticket::findOrFail($request->id);
        
                $ticket->status = $request->status;
                $ticket->remark = $request->remark;
                $ticket->priority = $request->priority;
                $ticket->date = $request->date;
        
                if ($request->hasFile('image')) {
                    $image = $request->file('image');
                    $filename = time() . '_' . $image->getClientOriginalName();
                    $path = $image->storeAs('tickets', $filename, 'public');
                    $ticket->image = $path;
                }
        
                $ticket->save();
                \DB::table('logs')->insert([
                    'module_nm' => 'ticket_status_update',
                    'module_id' => $ticket->id,
                    'status' => $ticket->status,
                    'remark' => $ticket->remark,
                    'created_by' => auth()->id(),
                    'created_at' => now(),
                ]);

        
                $formattedDate = \Carbon\Carbon::parse($ticket->date)->format('d-m-Y');
        
                return response()->json([
                    'success' => true,
                    'message' => "Ticket #{$ticket->id} updated on {$formattedDate} successfully!",
                ]);
            } catch (\Exception $e) {
                \Log::error('Ticket status update error: ' . $e->getMessage());
        
                return response()->json([
                    'success' => false,
                    'message' => 'Failed to update status. Error: ' . $e->getMessage(),
                ], 500);
            }

}
}
