<?php

namespace App\Http\Controllers;

use App\Models\OnlineCourse;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Storage;

class OnlineCoursesController extends Controller
{
    public function edit($id)
    {
        $onlineCourse = OnlineCourse::findOrFail($id);

        return view('pages.onlineCourses.edit', compact('onlineCourse'));
    }

    public function update(Request $request, $id)
    {
        $onlineCourse = OnlineCourse::findOrFail($id);

        // Validate the request data
        $validated = $request->validate([
            'course' => 'required|string',
            'offered_by' => 'required|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'num_days' => 'required|integer',
            'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
        ]);

        // 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 ($onlineCourse->proof && Storage::disk('public')->exists($onlineCourse->proof)) {
                Storage::disk('public')->delete($onlineCourse->proof);
            }

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

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

            // Create path structure: year/faculty_name
            $folderPath = 'proofs/' . $year . '/' . $username . '/Online Courses';

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

            $onlineCourse->proof = $proofPath;
        }


        // Update other fields
        $onlineCourse->course = $validated['course'];
        $onlineCourse->offered_by = $validated['offered_by'];
        $onlineCourse->start_date = $validated['start_date'];
        $onlineCourse->end_date = $validated['end_date'];
        $onlineCourse->num_days = $validated['num_days'];

        $onlineCourse->save();

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

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

    public function destroy($id)
    {
        $onlineCourse = OnlineCourse::findOrFail($id);

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

        $onlineCourse->delete();

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

    public function getOnlineCoursesResponses(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
            $onlineCourses = OnlineCourse::with('user', 'department');
        } elseif ($isCoordinator) {
            // Coordinator sees only their department's records
            $onlineCourses = OnlineCourse::with('user', 'department')
                ->whereHas('user', function ($query) use ($user) {
                    $query->where('department_id', $user->department_id);
                });
        } else {
            // Regular users see only their own records
            $onlineCourses = OnlineCourse::with('user', 'department')
                ->where('faculty_id', $user->id);
        }

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

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

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

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

        return DataTables::of($onlineCourses)
            ->addColumn('user_name', function ($onlineCourse) {
                return $onlineCourse->user->name ?? 'Unknown';
            })
            ->addColumn('department_name', function ($onlineCourse) {
                return $onlineCourse->department->name ?? 'Unknown';
            })
            ->filterColumn('user_name', function($query, $keyword) {
                $query->whereHas('user', function($q) use ($keyword) {
                    $q->where('name', 'like', "%{$keyword}%");
                });
            })
            ->addColumn('course', function ($onlineCourse) {
                return $onlineCourse->course ?? 'Unknown';
            })
            ->filterColumn('course', function($query, $keyword) {
                $query->where('course', 'like', "%{$keyword}%");
            })
            ->addColumn('offered_by', function ($onlineCourse) {
                return $onlineCourse->offered_by ?? 'Unknown';
            })
            ->addColumn('start_date', function ($onlineCourse) {
                return \Carbon\Carbon::parse($onlineCourse->start_date)->format('d-m-Y');
            })
            ->addColumn('end_date', function ($onlineCourse) {
                return \Carbon\Carbon::parse($onlineCourse->end_date)->format('d-m-Y');
            })
            ->addColumn('num_days', function ($onlineCourse) {
                return $onlineCourse->num_days ?? 'Unknown';
            })
            ->filterColumn('num_days', function($query, $keyword) {
                $query->where('num_days', 'like', "%{$keyword}%");
            })
            ->addColumn('action', function ($onlineCourse) {
                $actions = [];

                // View proof button for everyone
                if ($onlineCourse->proof) {
                    $actions[] = '<a href="' . asset('storage/' . $onlineCourse->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.OnlineCourses.edit', $onlineCourse->id);
                } elseif ($userRole === 'Coordinator') {
                    $editRoute = route('coordinator.OnlineCourses.edit', $onlineCourse->id);
                } else {
                    $editRoute = route('faculty.OnlineCourses.edit', $onlineCourse->id);
                }

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

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

                return implode(' ', $actions);
            })
            ->rawColumns(['action'])
            ->make(true);
    }
    
    public function store(Request $request)
    {
        // Validate the request data
        $validated = $request->validate([
            'course' => 'required|string',
            'offered_by' => 'required|string',
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'num_days' => 'required|integer',            
            'faculty_id' => 'required|exists:users,id',
            'department_id' => 'required|exists:departments,id',
            'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
        ]);

        // Create new record
        $onlineCourse = new OnlineCourse();
        $onlineCourse->course = $validated['course'];
        $onlineCourse->offered_by = $validated['offered_by'];
        $onlineCourse->start_date = $validated['start_date'];
        $onlineCourse->end_date = $validated['end_date'];
        $onlineCourse->num_days = $validated['num_days'];
        $onlineCourse->faculty_id = $validated['faculty_id'];
        $onlineCourse->department_id = $validated['department_id'];

        // Handle the file upload
        if ($request->hasFile('proof')) {
            $user = auth()->user();
            $year = date('Y', strtotime($validated['start_date']));
            $username = $user->name;

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

            // Create path structure: year/faculty_name
            $folderPath = 'proofs/' . $year . '/' . $username . '/Online Courses';

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

            $onlineCourse->proof = $proofPath;
        }

        $onlineCourse->save();

        return redirect()->route('faculty.OnlineCoursesResponses')
            ->with('status', 'online Course submitted successfully');
    }

}