<?php

namespace App\Http\Controllers;

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

class ExternalEngagementController extends Controller
{
    public function edit($id)
    {
        $externalEngagement = ExternalEngagement::findOrFail($id);

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

    public function update(Request $request, $id)
    {
        $externalEngagement = ExternalEngagement::findOrFail($id);

        // Validate the request data
        $validated = $request->validate([
            'activity' => 'required|string',
            'activity_description' => 'required|string',
            'inviting_organization' => '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 ($externalEngagement->proof && Storage::disk('public')->exists($externalEngagement->proof)) {
                Storage::disk('public')->delete($externalEngagement->proof);
            }

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

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

            // Create path structure: year/faculty_name
            $folderPath = 'proofs/' . $year . '/' . $username . '/External Engagement';

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

            $externalEngagement->proof = $proofPath;
        }


        // Update other fields
        $externalEngagement->activity = $validated['activity'];
        $externalEngagement->activity_description = $validated['activity_description'];
        $externalEngagement->inviting_organization = $validated['inviting_organization'];
        $externalEngagement->start_date = $validated['start_date'];
        $externalEngagement->end_date = $validated['end_date'];
        $externalEngagement->num_days = $validated['num_days'];

        $externalEngagement->save();

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

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

    public function destroy($id)
    {
        $externalEngagement = ExternalEngagement::findOrFail($id);

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

        $externalEngagement->delete();

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

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

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

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

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

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

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

                // View proof button for everyone
                if ($externalEngagement->proof) {
                    $actions[] = '<a href="' . asset('storage/' . $externalEngagement->proof) . '" target="_blank" class="btn btn-sm btn-primary mr-1">View</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.ExternalEngagement.edit', $externalEngagement->id);
                } elseif ($userRole === 'Coordinator') {
                    $editRoute = route('coordinator.ExternalEngagement.edit', $externalEngagement->id);
                } else {
                    $editRoute = route('faculty.ExternalEngagement.edit', $externalEngagement->id);
                }

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

                $deleteRoute = route('externalEngagement.destroy', $externalEngagement->id);
                $actions[] = '<button type="button" class="btn btn-sm btn-danger delete-btn" data-id="' . $externalEngagement->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([
            'activity' => 'required|string',
            'activity_description' => 'required|string',
            'inviting_organization' => '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
        $externalEngagement = new ExternalEngagement();
        $externalEngagement->activity = $validated['activity'];
        $externalEngagement->activity_description = $validated['activity_description'];
        $externalEngagement->inviting_organization = $validated['inviting_organization'];
        $externalEngagement->start_date = $validated['start_date'];
        $externalEngagement->end_date = $validated['end_date'];
        $externalEngagement->num_days = $validated['num_days'];
        $externalEngagement->faculty_id = $validated['faculty_id'];
        $externalEngagement->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 . '/External Engagement';

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

            $externalEngagement->proof = $proofPath;
        }

        $externalEngagement->save();

        return redirect()->route('faculty.ExternalEngagementResponses')
            ->with('status', 'External Engagement submitted successfully');
    }

}