<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use App\Models\ActivitiesAttended;
use Illuminate\Support\Facades\Storage;
use App\Services\ProofDownloadService;

class ActivitiesAttendedController extends Controller
{

    public function edit($id)
    {
        $response = ActivitiesAttended::findOrFail($id);

        // Fetch unique organising institutes
        $organisingInstitutes = ActivitiesAttended::select('organising_institute')
            ->distinct()
            ->pluck('organising_institute');

        return view('pages.activities-attended.edit', compact('response', 'organisingInstitutes'));
    }

    public function update(Request $request, $id)
    {
        $response = ActivitiesAttended::findOrFail($id);

        // Validate the request data
        $validated = $request->validate([
            'title' => 'required|string',
            'organising_institute' => 'required|string',
            'address' => 'required|string',
            'start_date' => 'required|date',
            'start_time' => 'required|date_format:H:i',
            'end_date' => 'required|date',
            'end_time' => 'required|date_format:H:i',
            'num_days' => 'required|integer',
            'activity_type' => 'required|string',
            'category' => 'required|string',
            'level' => 'required|string',
            'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip,ppt,pptx|max:5120', // 5MB max
        ]);

        // Combine start date and time
        $startDateTime = date('Y-m-d H:i:s', strtotime("{$validated['start_date']} {$validated['start_time']}"));
        $endDateTime = date('Y-m-d H:i:s', strtotime("{$validated['end_date']} {$validated['end_time']}"));

        // Handle the file upload if a new file is provided
        if ($request->hasFile('proof')) {
            // Delete old file if exists
            if ($response->proof && Storage::disk('public')->exists($response->proof)) {
                Storage::disk('public')->delete($response->proof);
            }

            // Extract year from start_date
            $year = date('Y', strtotime($validated['start_date']));
            $username = $response->user->name;
            $userId = $response->user->id;

            $originalName = $request->file('proof')->getClientOriginalName();
            $fileName = $username . '_' . $originalName;

            // Create path structure: year/faculty_name
            $folderPath = 'proofs/' . $year . '/' . $userId . '_' . $username . '/Activities-Attended';

            // Store file in the specified path
            $proofPath = $request->file('proof')->storeAs($folderPath, $fileName, 'public');

            $response->proof = $proofPath;
        }

        // Update other fields
        $response->title = $validated['title'];
        $response->organising_institute = $validated['organising_institute'];
        $response->address = $validated['address'];
        $response->start_date = $startDateTime;
        $response->end_date = $endDateTime;
        $response->num_days = $validated['num_days'];
        $response->activity_type = $validated['activity_type'];
        $response->category = $validated['category'];
        $response->level = $validated['level'];

        $response->save();

        $userRole = auth()->user()->role->name;
        // dd($userRole);

        if ($userRole === 'Admin') {
            return redirect()->route('admin.ActivitiesAttendedResponses')
                ->with('status', 'Response updated successfully');
        } elseif ($userRole === 'Coordinator') {
            return redirect()->route('coordinator.ActivitiesAttendedResponses')
                ->with('status', 'Response updated successfully');
        } else {
            // For regular users
            return redirect()->route('faculty.ActivitiesAttendedResponses')
                ->with('status', 'Response updated successfully');
        }
        // return redirect()->route('admin.ActivitiesAttendedResponses')->with('status', 'Response updated successfully');
    }

    public function destroy($id)
    {
        $response = ActivitiesAttended::findOrFail($id);

        // Delete the file if it exists
        if ($response->proof && Storage::disk('public')->exists($response->proof)) {
            Storage::disk('public')->delete($response->proof);
        }

        $response->delete();

        return response()->json(['success' => 'Record deleted successfully']);
    }

    public function getActivitiesAttendedResponses(Request $request)
    {
        $user = auth()->user();
        $isAdmin = $user->role->name === 'Admin';
        $isCoordinator = $user->role->name === 'Coordinator';

        // Query based on role
        if ($isAdmin) {
            // Admin sees all records
            $responses = ActivitiesAttended::with('user', 'department');
        } elseif ($isCoordinator) {
            // Coordinator sees only their department's records
            $responses = ActivitiesAttended::with('user', 'department')
                ->whereHas('user', function ($query) use ($user) {
                    $query->where('department_id', $user->department_id);
                });
        } else {
            // Regular users see only their own records
            $responses = ActivitiesAttended::with('user', 'department')
                ->where('faculty_id', $user->id);
        }

        // Apply filters
        if ($request->has('department') && !empty($request->department)) {
            $responses->whereHas('department', function ($query) use ($request) {
                $query->where('id', $request->department);
            });
        }

        if ($request->has('category') && !empty($request->category)) {
            $responses->where('category', $request->category);
        }

        if ($request->has('dateFrom') && !empty($request->dateFrom)) {
            $responses->where('start_date', '>=', $request->dateFrom);
        }

        if ($request->has('dateTo') && !empty($request->dateTo)) {
            $responses->where('end_date', '<=', $request->dateTo);
        }

        return DataTables::of($responses)
            ->addColumn('user_name', function ($response) {
                return $response->user->name ?? 'Unknown';
            })
            ->addColumn('department_name', function ($response) {
                return $response->department->name ?? 'Unknown';
            })
            ->addColumn('start_date', function ($response) {
                return \Carbon\Carbon::parse($response->start_date)->format('d-m-Y');
            })
            ->addColumn('start_time', function ($response) {
                return \Carbon\Carbon::parse($response->start_date)->format('h:i A');
            })
            ->addColumn('end_date', function ($response) {
                return \Carbon\Carbon::parse($response->end_date)->format('d-m-Y');
            })
            ->addColumn('end_time', function ($response) {
                return \Carbon\Carbon::parse($response->end_date)->format('h:i A');
            })
            ->addColumn('action', function ($response) {
                $actions = [];

                // View proof button for everyone
                if ($response->proof) {
                    $actions[] = '<a href="' . asset('storage/' . $response->proof) . '" target="_blank" class="btn btn-sm btn-primary mr-1"><i class="fas fa-eye"></i></a>';
                } else {
                    $actions[] = '<span class="text-muted"><i class="fas fa-times-circle"></i></span>';
                }

                // Edit button with role-appropriate route
                $userRole = auth()->user()->role->name;
                // Determine the appropriate route based on user role
                if ($userRole === 'Admin') {
                    $editRoute = route('admin.ActivitiesAttended.edit', $response->id);
                } elseif ($userRole === 'Coordinator') {
                    $editRoute = route('coordinator.ActivitiesAttended.edit', $response->id);
                } else {
                    $editRoute = route('faculty.ActivitiesAttended.edit', $response->id);
                }

                $actions[] = '<a href="' . $editRoute . '" class="btn btn-sm btn-info mx-1"><i class="fas fa-edit"></i></a>';

                $deleteRoute = route('activitiesAttended.destroy', $response->id);
                $actions[] = '<button type="button" class="btn btn-sm btn-danger delete-btn" data-id="' . $response->id . '" data-url="' . $deleteRoute . '"><i class="fas fa-trash"></i></button>';

                return implode(' ', $actions);
            })
            ->rawColumns(['action'])
            ->make(true);
    }
}
