<?php

namespace App\Controllers\Salary;

use App\Controllers\Controller;
use App\Models\EmployeeDismissal;
use App\Models\SalaryEmployee;
use App\Models\SalaryDeduction;
use App\Services\Salary\DismissalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DismissalController extends Controller
{
    protected $dismissalService;
    
    public function __construct(DismissalService $dismissalService)
    {
        $this->dismissalService = $dismissalService;
    }
    
    /**
     * List all dismissal requests
     */
    public function index()
    {
        try {
            // Get pending dismissals
            $pendingDismissals = EmployeeDismissal::with(['employee', 'requestedBy'])
                ->where('status', 'pending')
                ->orderBy('created_at', 'asc')
                ->get();
            
            // Get approved dismissals
            $approvedDismissals = EmployeeDismissal::with(['employee', 'approvedBy'])
                ->where('status', 'approved')
                ->orderBy('approved_at', 'desc')
                ->get();
            
            // Get processed/completed dismissals
            $processedDismissals = EmployeeDismissal::with(['employee', 'processedBy'])
                ->whereIn('status', ['completed', 'processing']) // Include both if needed
                ->orderBy('processed_at', 'desc')
                ->limit(50)
                ->get();
            
            // Get rejected dismissals
            $rejectedDismissals = EmployeeDismissal::with(['employee', 'rejectedBy'])
                ->where('status', 'rejected')
                ->orderBy('rejected_at', 'desc')
                ->limit(50)
                ->get();
            
            // Statistics
            $stats = [
                'pending' => EmployeeDismissal::where('status', 'pending')->count(),
                'approved' => EmployeeDismissal::where('status', 'approved')->count(),
                'processing' => EmployeeDismissal::where('status', 'processing')->count(),
                'completed' => EmployeeDismissal::where('status', 'completed')->count(),
                'rejected' => EmployeeDismissal::where('status', 'rejected')->count(),
            ];
            
            return view('salary.dismissals.index', compact(
                'pendingDismissals', 
                'approvedDismissals', 
                'processedDismissals',
                'rejectedDismissals',
                'stats'
            ));
            
        } catch (\Exception $e) {
            Log::error('Error loading dismissals index: ' . $e->getMessage());
            
            // Return view with empty collections to avoid errors
            return view('salary.dismissals.index', [
                'pendingDismissals' => collect([]),
                'approvedDismissals' => collect([]),
                'processedDismissals' => collect([]),
                'rejectedDismissals' => collect([]),
                'stats' => [
                    'pending' => 0,
                    'approved' => 0,
                    'processing' => 0,
                    'completed' => 0,
                    'rejected' => 0,
                ]
            ]);
        }
    }

    /**
     * Show form for creating a new dismissal request
     */
    public function create()
    {
        $employees = SalaryEmployee::where('status', 'active')
            ->whereDoesntHave('dismissals', function($query) {
                $query->whereIn('status', ['pending', 'approved', 'processing']);
            })
            ->orderBy('name', 'asc')
            ->get();
            
        return view('salary.dismissals.create', compact('employees'));
    }
    
    /**
     * Store a new dismissal request
     */
    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'employee_id' => 'required|exists:salary_employees,id',
                'dismissal_type' => 'required|string',
                'reason' => 'required|string|min:20',
                'effective_date' => 'required|date|after_or_equal:today',
                'comments' => 'nullable|string',
                'deduction_amount' => 'nullable|numeric|min:0',
                'deduction_reason' => 'required_if:deduction_amount,!=,null|nullable|string'
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }
            
            $dismissal = EmployeeDismissal::create([
                'employee_id' => $request->employee_id,
                'dismissal_type' => $request->dismissal_type,
                'dismissal_reason' => $request->reason,
                'details' => $request->reason,
                'effective_date' => $request->effective_date,
                'requested_by' => Auth::id(),
                'requested_at' => now(),
                'hr_notes' => $request->comments,
                'status' => 'pending',
                'total_deductions_amount' => $request->deduction_amount ?? 0,
            ]);
            
            // Create deduction if provided
            if (!empty($request->deduction_amount) && $request->deduction_amount > 0) {
                SalaryDeduction::create([
                    'employee_id' => $request->employee_id,
                    'dismissal_id' => $dismissal->id,
                    'amount' => $request->deduction_amount,
                    'reason' => $request->deduction_reason,
                    'deduction_type' => 'dismissal_related',
                    'status' => 'pending',
                    'deduction_date' => now(),
                    'created_by' => Auth::id()
                ]);
            }
            
            return response()->json([
                'success' => true,
                'message' => 'Dismissal request created successfully',
                'redirect_url' => route('salary.dismissals.show', $dismissal->id)
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error creating dismissal: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to create dismissal: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Show dismissal details
     */
    public function show($id)
    {
        $dismissal = EmployeeDismissal::with([
            'employee', 
            'requestedBy', 
            'approvedBy', 
            'rejectedBy', 
            'processedBy'
        ])->findOrFail($id);
        
        return view('salary.dismissals.show', compact('dismissal'));
    }
    
    /**
     * Approve dismissal request
     */
    public function approve(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:500'
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }
            
            // Find the dismissal
            $dismissal = EmployeeDismissal::findOrFail($id);
            
            // Check if dismissal is pending
            if ($dismissal->status !== 'pending') {
                return response()->json([
                    'success' => false,
                    'message' => 'Only pending dismissals can be approved. Current status: ' . $dismissal->status
                ], 400);
            }
            
            // Update dismissal status
            $dismissal->update([
                'status' => 'approved',
                'approved_by' => Auth::id(),
                'approved_at' => now(),
                'approval_comments' => $request->comments
            ]);
            
            Log::info('Dismissal approved', [
                'dismissal_id' => $id,
                'approved_by' => Auth::id(),
                'status' => $dismissal->status
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Dismissal request approved successfully',
                'dismissal' => $dismissal
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error approving dismissal: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to approve dismissal: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Reject dismissal request
     */
    public function reject(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'reason' => 'required|string|min:10|max:500'
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }
            
            $dismissal = EmployeeDismissal::findOrFail($id);
            
            // Check if dismissal is pending
            if ($dismissal->status !== 'pending') {
                return response()->json([
                    'success' => false,
                    'message' => 'Only pending dismissals can be rejected. Current status: ' . $dismissal->status
                ], 400);
            }
            
            $dismissal->update([
                'status' => 'rejected',
                'rejected_by' => Auth::id(),
                'rejected_at' => now(),
                'rejection_reason' => $request->reason
            ]);
            
            Log::info('Dismissal rejected', [
                'dismissal_id' => $id,
                'rejected_by' => Auth::id(),
                'reason' => $request->reason
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Dismissal request rejected',
                'dismissal' => $dismissal
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error rejecting dismissal: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to reject dismissal: ' . $e->getMessage()
            ], 500);
        }
    }
    
    /**
     * Process dismissal (after approval)
     */
    public function process(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'effective_date' => 'required|date',
                'notes' => 'nullable|string|max:1000',
                'settlement_amount' => 'nullable|numeric|min:0'
            ]);
            
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'errors' => $validator->errors()
                ], 422);
            }
            
            $dismissal = EmployeeDismissal::findOrFail($id);
            
            // Check if dismissal is approved
            if ($dismissal->status !== 'approved') {
                return response()->json([
                    'success' => false,
                    'message' => 'Only approved dismissals can be processed. Current status: ' . $dismissal->status
                ], 400);
            }
            
            // Update last working date (day before effective date)
            $lastWorkingDate = date('Y-m-d', strtotime($request->effective_date . ' -1 day'));
            
            $dismissal->update([
                'status' => 'completed',
                'effective_date' => $request->effective_date,
                'last_working_date' => $lastWorkingDate,
                'processed_by' => Auth::id(),
                'processed_at' => now(),
                'processing_notes' => $request->notes,
                'final_settlement_amount' => $request->settlement_amount,
                'settlement_paid' => !empty($request->settlement_amount),
                'settlement_paid_at' => !empty($request->settlement_amount) ? now() : null
            ]);
            
            // Update employee status - only use columns that exist
            $employeeData = [
                'status' => 'terminated',
                'dismissal_id' => $dismissal->id,
                'dismissal_date' => $request->effective_date,
                'dismissal_reason' => $dismissal->dismissal_reason
            ];
            
            $dismissal->employee->update($employeeData);
            
            Log::info('Dismissal processed', [
                'dismissal_id' => $id,
                'processed_by' => Auth::id(),
                'effective_date' => $request->effective_date
            ]);
            
            return response()->json([
                'success' => true,
                'message' => 'Dismissal processed successfully. Employee status updated.',
                'dismissal' => $dismissal
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error processing dismissal: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to process dismissal: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get employee details for AJAX request
     */
    public function getEmployeeDetails($id)
    {
        try {
            $employee = SalaryEmployee::findOrFail($id);
            
            // Check for existing active dismissal
            $activeDismissal = EmployeeDismissal::where('employee_id', $id)
                ->whereIn('status', ['pending', 'approved', 'processing'])
                ->first();
            
            $hasActiveDismissal = !is_null($activeDismissal);
            
            // Get pending deductions
            $pendingDeductions = SalaryDeduction::where('employee_id', $id)
                ->where('status', 'pending')
                ->get()
                ->map(function($deduction) {
                    return [
                        'id' => $deduction->id,
                        'amount' => $deduction->amount,
                        'reason' => $deduction->reason,
                        'created_at' => $deduction->created_at->format('Y-m-d')
                    ];
                });
            
            return response()->json([
                'success' => true,
                'employee' => [
                    'id' => $employee->id,
                    'full_name' => $employee->name,
                    'department' => $employee->station ?? 'Not Assigned',
                    'position' => $employee->position,
                    'join_date' => $employee->created_at->format('Y-m-d'),
                    'basic_salary' => $employee->base_salary ?? 0,
                    'has_active_dismissal' => $hasActiveDismissal,
                    'active_dismissal_status' => $activeDismissal ? $activeDismissal->status : null,
                    'pending_deductions' => $pendingDeductions
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('Error fetching employee details: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to load employee details'
            ], 500);
        }
    }
}