<?php

namespace App\Http\Controllers;

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

class PatentsController extends Controller
{
    public function edit($id)
    {
        $patent = Patent::findOrFail($id);
        $organisingInstitutes = Publication::select('organizing_institute')
            ->distinct()
            ->pluck('organizing_institute');

        return view('pages.patents.edit', compact('patent', 'organisingInstitutes'));
    }

    public function update(Request $request, $id)
    {
        $patent = Patent::findOrFail($id);

        // Validate the request data
        $validated = $request->validate([
            'title' => 'required|string',
            'investigator' => 'required|string',
            'application_no' => 'required|string',
            'type' => 'required|string',
            'date_of_submission' => 'required|date',
            'date_of_filling' => 'required|date',
            'status' => 'required|string',
            '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 ($patent->proof && Storage::disk('public')->exists($patent->proof)) {
                Storage::disk('public')->delete($patent->proof);
            }

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

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

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

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

            $patent->proof = $proofPath;
        }


        // Update other fields
        $patent->title = $validated['title'];
        $patent->investigator = $validated['investigator'];
        $patent->application_no = $validated['application_no'];
        $patent->type = $validated['type'];
        $patent->date_of_submission = $validated['date_of_submission'];
        $patent->date_of_filling = $validated['date_of_filling'];
        $patent->status = $validated['status'];

        $patent->save();

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

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

    public function destroy($id)
    {
        $patent = Patent::findOrFail($id);

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

        $patent->delete();

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

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

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

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

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

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

        return DataTables::of($patents)
            ->addColumn('user_name', function ($patent) {
                return $patent->user->name ?? 'Unknown';
            })
            ->addColumn('department_name', function ($patent) {
                return $patent->department->name ?? 'Unknown';
            })
            ->addColumn('title', function ($patent) {
                return $patent->title ?? 'Unknown';
            })
            ->addColumn('investigator', function ($patent) {
                return $patent->investigator ?? 'Unknown';
            })
            ->addColumn('application_no', function ($patent) {
                return $patent->application_no ?? 'Unknown';
            })
            ->addColumn('type', function ($patent) {
                return $patent->type ?? 'Unknown';
            })
            ->addColumn('date_of_submission', function ($patent) {
                return \Carbon\Carbon::parse($patent->date_of_submission)->format('d-m-Y');
            })
            ->addColumn('date_of_filling', function ($patent) {
                return \Carbon\Carbon::parse($patent->date_of_filling)->format('d-m-Y');
            })
            ->addColumn('status', function ($patent) {
                return $patent->status ?? 'Unknown';
            })
            ->filterColumn('user_name', function($query, $keyword) {
                $query->whereHas('user', function($q) use ($keyword) {
                    $q->where('name', 'like', "%{$keyword}%");
                });
            })
            ->filterColumn('title', function($query, $keyword) {
                $query->where('title', 'like', "%{$keyword}%");
            })
            ->filterColumn('investigator', function($query, $keyword) {
                $query->where('investigator', 'like', "%{$keyword}%");
            })
            ->filterColumn('application_no', function($query, $keyword) {
                $query->where('application_no', 'like', "%{$keyword}%");
            })
            ->filterColumn('type', function($query, $keyword) {
                $query->where('type', 'like', "%{$keyword}%");
            })
            ->addColumn('action', function ($patent) {
                $actions = [];

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

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

                $deleteRoute = route('patents.destroy', $patent->id);
                $actions[] = '<button type="button" class="btn btn-sm btn-danger delete-btn" data-id="' . $patent->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([
            'title' => 'required|string',
            'investigator' => 'required|string',
            'application_no' => 'required|string',
            'type' => 'required|string',
            'date_of_submission' => 'required|date',
            'date_of_filling' => 'required|date',
            'status' => 'required|string',          
            '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
        $patent = new Patent();
        $patent->title = $validated['title'];
        $patent->investigator = $validated['investigator'];
        $patent->application_no = $validated['application_no'];
        $patent->type = $validated['type'];
        $patent->date_of_submission = $validated['date_of_submission'];
        $patent->date_of_filling = $validated['date_of_filling'];
        $patent->status = $validated['status'];
        $patent->faculty_id = $validated['faculty_id'];
        $patent->department_id = $validated['department_id'];

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

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

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

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

            $patent->proof = $proofPath;
        }

        $patent->save();

        return redirect()->route('faculty.PatentsResponses')
            ->with('status', 'patent submitted successfully');
    }

}