<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LeaveApplication;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Session;
use Carbon\Carbon;

class LeaveApplicationController extends Controller
{
    /**
     * Store a newly created leave application in storage.
     */
    public function store(Request $request)
    {
        // Clear any previous flash messages to prevent conflicts
        Session::forget(['success', 'error']);

        // Ensure this is a leave application request
        if (!$request->has('full_name') || !$request->has('leave_type')) {
            return redirect()->back()->with('error', 'Invalid leave application submission.');
        }

        // Validate the form data
        $validator = Validator::make($request->all(), [
            'full_name' => 'required|string|max:255',
            'service_number' => 'required|string|max:255',
            'rank' => 'required|string|max:100',
            'service_status' => 'required|string|max:100',
            'country' => 'required|string|max:100',
            'applicant_name' => 'required|string|max:255',
            'relationship' => 'required|string|max:100',
            'leave_type' => 'required|string|max:100',
            'leave_balance' => 'nullable|integer|min:0',
            'start_date' => 'required|date|after_or_equal:today',
            'end_date' => 'required|date|after_or_equal:start_date',
            'days_requested' => 'required|integer|min:1',
            'applicant_phone' => 'required|string|max:20',
            'applicant_email' => 'required|email|max:255',
            'leave_address' => 'required|string|max:1000',
            'justification' => 'required|string|max:2000',
        ], [
            'full_name.required' => 'Service member full name is required.',
            'service_number.required' => 'Service number/SSN is required.',
            'rank.required' => 'Military rank is required.',
            'service_status.required' => 'Service status is required.',
            'country.required' => 'Country of service is required.',
            'applicant_name.required' => 'Applicant name is required.',
            'relationship.required' => 'Relationship to service member is required.',
            'leave_type.required' => 'Type of leave is required.',
            'start_date.required' => 'Leave start date is required.',
            'start_date.after_or_equal' => 'Leave start date must be today or in the future.',
            'end_date.required' => 'Leave end date is required.',
            'end_date.after_or_equal' => 'Leave end date must be on or after the start date.',
            'days_requested.required' => 'Number of days requested is required.',
            'days_requested.min' => 'At least 1 day must be requested.',
            'applicant_phone.required' => 'Applicant phone number is required.',
            'applicant_email.required' => 'Applicant email address is required.',
            'applicant_email.email' => 'Please provide a valid email address.',
            'leave_address.required' => 'Service member address during leave is required.',
            'justification.required' => 'Justification for leave request is required.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error', 'Please correct the errors below and try again.');
        }

        try {
            // Create the leave application
            $leaveApplication = LeaveApplication::create([
                'full_name' => $request->full_name,
                'service_number' => $request->service_number,
                'rank' => $request->rank,
                'service_status' => $request->service_status,
                'country' => $request->country,
                'applicant_name' => $request->applicant_name,
                'relationship' => $request->relationship,
                'leave_type' => $request->leave_type,
                'leave_balance' => $request->leave_balance,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'days_requested' => $request->days_requested,
                'applicant_phone' => $request->applicant_phone,
                'applicant_email' => $request->applicant_email,
                'leave_address' => $request->leave_address,
                'justification' => $request->justification,
                'status' => 'pending',
                'submitted_at' => Carbon::now(),
            ]);

            // Set success message and redirect
            return redirect()->route('apply-now')
                ->with('success', 'Your leave application has been submitted successfully! Application ID: #' . str_pad($leaveApplication->id, 6, '01234556gsfddattyyywehAs', STR_PAD_LEFT) . '. You will be contacted within 3-5 business days regarding the status of your request.')
                ->with('application_id', $leaveApplication->id);

        } catch (\Exception $e) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'There was an error submitting your application. Please try again or contact personnel support if the problem persists.');
        }
    }

    /**
     * Display all leave applications for admin (admin dashboard)
     */
    public function index(Request $request)
    {
        $query = LeaveApplication::query();

        // Filter by status if provided
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        // Search functionality
        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('full_name', 'LIKE', "%{$search}%")
                  ->orWhere('service_number', 'LIKE', "%{$search}%")
                  ->orWhere('applicant_name', 'LIKE', "%{$search}%")
                  ->orWhere('applicant_email', 'LIKE', "%{$search}%");
            });
        }

        // Get applications with pagination
        $applications = $query->orderBy('submitted_at', 'desc')->paginate(15);

        // Get statistics
        $stats = [
            'total' => LeaveApplication::count(),
            'pending' => LeaveApplication::where('status', 'pending')->count(),
            'approved' => LeaveApplication::where('status', 'approved')->count(),
            'rejected' => LeaveApplication::where('status', 'rejected')->count(),
            'recent' => LeaveApplication::where('submitted_at', '>=', Carbon::now()->subDays(7))->count(),
        ];

        $title = 'Leave Applications Management';

        return view('admin.leave-applications.index', compact('applications', 'stats', 'title'));
    }

    /**
     * Display the specified leave application
     */
    public function show(LeaveApplication $leaveApplication)
    {
        $title = 'Leave Application Details - ID: ' . str_pad($leaveApplication->id, 6, '0', STR_PAD_LEFT);

        return view('admin.leave-applications.show', compact('leaveApplication', 'title'));
    }

    /**
     * Update the status of the leave application
     */
    public function updateStatus(Request $request, LeaveApplication $leaveApplication)
    {
        $validator = Validator::make($request->all(), [
            'status' => 'required|in:pending,approved,rejected'
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', 'Invalid status provided.');
        }

        $leaveApplication->update([
            'status' => $request->status
        ]);

        return redirect()->back()->with('success', 'Application status updated successfully.');
    }

    /**
     * Remove the specified leave application from storage
     */
    public function destroy(LeaveApplication $leaveApplication)
    {
        try {
            $applicationId = str_pad($leaveApplication->id, 6, '0', STR_PAD_LEFT);
            $leaveApplication->delete();

            return redirect()->route('admin.leave-applications.index')
                ->with('success', "Leave application #{$applicationId} has been deleted successfully.");

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'There was an error deleting the application. Please try again.');
        }
    }
}
