<?php

namespace App\Http\Controllers;

use App\Models\EmployeeDocument;
use App\Models\ProfileUpdateRequest;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;

class ProfileApprovalController extends Controller
{
    public function index()
    {
        $this->authorizeAdminOrManager();
        return view('admin.approvals.profile');
    }

    public function getProfileData()
    {
        $requests = ProfileUpdateRequest::with('employee')->where('status', 'pending');
        
        if (!auth()->user()->hasRole('Admin')) {
            $requests->whereHas('employee', function($q) {
                $q->where('manager_id', auth()->user()->employee_id);
            });
        }
        
        return DataTables::of($requests)
            ->addColumn('employee_name', function($row) {
                return $row->employee->name;
            })
            ->addColumn('changes_view', function($row) {
                $html = '<ul class="list-unstyled mb-0">';
                foreach($row->changes as $key => $value) {
                    $label = ucwords(str_replace('_', ' ', $key));
                    $html .= "<li class='mb-1'><span class='badge bg-light text-dark border me-2'>{$label}</span> <span class='text-muted small'>{$value}</span></li>";
                }
                $html .= '</ul>';
                return $html;
            })
            ->addColumn('action', function($row) {
                if (auth()->user()->canAccess('employees.edit')) {
                    return '<div class="d-flex gap-1 justify-content-center">
                                <button class="btn-crm-approve approve-profile" data-id="'.$row->id.'" title="Approve Request"><i class="fas fa-check"></i></button>
                                <button class="btn-crm-reject reject-profile" data-id="'.$row->id.'" title="Reject Request"><i class="fas fa-times"></i></button>
                            </div>';
                }
                return '';
            })
            ->rawColumns(['changes_view', 'action'])
            ->make(true);
    }

    public function approveProfile($id)
    {
        $request = ProfileUpdateRequest::with('employee')->find($id);
        
        if (!$request) {
           // Fallback for potential ID mismatch or employee_id usage
           $request = ProfileUpdateRequest::with('employee')->where('employee_id', $id)->where('status', 'pending')->firstOrFail();
        }

        $user = auth()->user();
        if (!$user->hasRole('Admin')) {
            if (!$user->employee || $request->employee->manager_id != $user->employee_id) {
                return response()->json(['error' => 'Unauthorized. You can only approve requests for your subordinates.'], 403);
            }
        }

        $employee = $request->employee;

        // Apply changes to employee model
        $employee->update($request->changes);
        
        $request->update(['status' => 'approved']);

        return response()->json(['success' => 'Profile update approved and applied.']);
    }

    public function rejectProfile(Request $request, $id)
    {
        $profileRequest = ProfileUpdateRequest::with('employee')->find($id);

        if (!$profileRequest) {
            $profileRequest = ProfileUpdateRequest::with('employee')->where('employee_id', $id)->where('status', 'pending')->firstOrFail();
        }

        $user = auth()->user();
        if (!$user->hasRole('Admin')) {
            if (!$user->employee || $profileRequest->employee->manager_id != $user->employee_id) {
                return response()->json(['error' => 'Unauthorized. You can only reject requests for your subordinates.'], 403);
            }
        }

        $profileRequest->update([
            'status' => 'rejected',
            'rejection_reason' => $request->reason
        ]);

        return response()->json(['success' => 'Profile update rejected.']);
    }

    public function documents()
    {
        $this->authorizeAdminOrManager();
        return view('admin.approvals.documents');
    }

    public function getDocumentData()
    {
        $docs = EmployeeDocument::with('employee')->where('status', 'pending');

        if (!auth()->user()->hasRole('Admin')) {
            $docs->whereHas('employee', function($q) {
                $q->where('manager_id', auth()->user()->employee_id);
            });
        }

        return DataTables::of($docs)
            ->addColumn('employee_name', function($row) {
                return $row->employee->name;
            })
            ->addColumn('file_link', function($row) {
                return '<a href="'.asset('storage/'.$row->file_path).'" target="_blank" class="text-primary"><i class="fas fa-file-download me-1"></i> View File</a>';
            })
            ->addColumn('action', function($row) {
                if (auth()->user()->canAccess('employees.edit')) {
                    return '<div class="d-flex gap-1 justify-content-center">
                                <button class="btn-crm-approve approve-doc" data-id="'.$row->id.'" title="Approve Document"><i class="fas fa-check"></i></button>
                                <button class="btn-crm-reject reject-doc" data-id="'.$row->id.'" title="Reject Document"><i class="fas fa-times"></i></button>
                            </div>';
                }
                return '';
            })

            ->rawColumns(['file_link', 'action'])
            ->make(true);
    }

    public function approveDocument($id)
    {
        $doc = EmployeeDocument::with('employee')->findOrFail($id);
        
        $user = auth()->user();
        if (!$user->hasRole('Admin')) {
            if (!$user->employee || $doc->employee->manager_id != $user->employee_id) {
                return response()->json(['error' => 'Unauthorized. You can only approve documents for your subordinates.'], 403);
            }
        }

        $doc->update(['status' => 'approved']);

        return response()->json(['success' => 'Document approved.']);
    }

    public function rejectDocument(Request $request, $id)
    {
        $doc = EmployeeDocument::with('employee')->findOrFail($id);
        
        $user = auth()->user();
        if (!$user->hasRole('Admin')) {
            if (!$user->employee || $doc->employee->manager_id != $user->employee_id) {
                return response()->json(['error' => 'Unauthorized. You can only reject documents for your subordinates.'], 403);
            }
        }

        $doc->update([
            'status' => 'rejected',
            'rejection_reason' => $request->reason
        ]);

        return response()->json(['success' => 'Document rejected.']);
    }

    private function authorizeAdminOrManager()
    {
        $user = auth()->user();
        if ($user->hasRole('Admin') || $user->canAccess('employees.edit')) {
            return;
        }

        $isManager = $user->employee && $user->employee->subordinates()->exists();
        if (!$isManager) {
            abort(403, 'Unauthorized action.');
        }
    }
}
