<?php

namespace App\Http\Controllers;

use App\Models\MaintenanceRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MaintenanceRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     */
   
    public function index(Request $request)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }

        $query = MaintenanceRequest::with([
                'unit.property', 
                'technician', 
                'creator', 
                'customer'
            ])
            ->whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->orderBy('created_at', 'desc');

        // Filter by block_id if provided
        if ($request->has('block_id')) {
            $query->where('block_id', $request->block_id);
        }

        $maintenanceRequests = $query->paginate(15);

        return view('maintenance-requests.index', compact('maintenanceRequests'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Get properties and units for the dropdowns, filtered by company
        $properties = \App\Models\Property::where('CompanyID', $companyId)
            ->with(['blocks', 'units'])
            ->get();
            
        $customers = \App\Models\Customer::whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->get();
            
        return view('maintenance-requests.create', compact('properties', 'customers'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        $validated = $request->validate([
            'property_id' => 'required|exists:property,PropID',
            'block_id' => 'nullable|exists:blocks,BlockID',
            'unit_id' => 'required|exists:prounits,UnitID',
            'customer_id' => 'required|exists:customer,CustomerID',
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'priority' => 'required|in:Low,Medium,High,Urgent',
            'requested_date' => 'required|date',
            'images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);
        
        // Verify the unit belongs to the user's company
        $unit = \App\Models\ProUnit::with('property')
            ->where('UnitID', $validated['unit_id'])
            ->whereHas('property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->firstOrFail();
            
        // Verify the customer is associated with the unit
        $customer = \App\Models\Customer::where('CustomerID', $validated['customer_id'])
            ->where('UnitID', $validated['unit_id'])
            ->firstOrFail();
        
        try {
            DB::beginTransaction();
            
            // Create the maintenance request
            $maintenanceRequest = new MaintenanceRequest([
                'property_id' => $validated['property_id'],
                'block_id' => $validated['block_id'],
                'unit_id' => $validated['unit_id'],
                'customer_id' => $validated['customer_id'],
                'title' => $validated['title'],
                'description' => $validated['description'],
                'priority' => $validated['priority'],
                'requested_date' => $validated['requested_date'],
                'status' => 'Pending',
                'created_by' => $this->user()->id,
                'company_id' => $companyId,
            ]);
            
            $maintenanceRequest->save();
            
            // Handle file uploads if any
            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $image) {
                    $path = $image->store('maintenance-requests/' . $maintenanceRequest->id, 'public');
                    
                    $maintenanceRequest->images()->create([
                        'file_path' => $path,
                        'file_name' => $image->getClientOriginalName(),
                        'file_type' => $image->getClientMimeType(),
                        'file_size' => $image->getSize(),
                    ]);
                }
            }
            
            DB::commit();
            
            return redirect()->route('maintenance-requests.show', $maintenanceRequest->id)
                ->with('success', 'Maintenance request created successfully.');
                
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error creating maintenance request: ' . $e->getMessage());
            
            return redirect()->back()
                ->withInput()
                ->with('error', 'Failed to create maintenance request. Please try again.');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }

        // Load the maintenance request with relationships and verify company access
        $maintenanceRequest = MaintenanceRequest::with([
                'company',
                'property',
                'block',
                'unit.property',
                'customer',
                'technician',
                'creator',
                'updater'
            ])
            ->whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->findOrFail($id);

        // Get upcoming rent dues for the unit, scoped to the company
        $upcomingRentDues = \App\Models\RentServiceBill::with(['unit.property'])
            ->where('UnitID', $maintenanceRequest->unit_id)
            ->whereIn('BillStatus', ['Unpaid', 'Partially Paid'])
            ->where('BillingDate', '>=', now()->subDays(30)) // Show bills from the last 30 days and future
            ->whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->orderBy('BillingDate', 'asc')
            ->limit(3) // Show only the next 3 upcoming dues
            ->get()
            ->map(function ($bill) {
                $dueDate = \Carbon\Carbon::parse($bill->BillingDate);
                $now = now();
                $diffInDays = $now->diffInDays($dueDate, false);
                
                // Determine status and badge class
                if ($diffInDays < 0) {
                    $status = 'Overdue';
                    $badgeClass = 'bg-danger';
                    $dueText = 'Due ' . abs($diffInDays) . ' days ago';
                } elseif ($diffInDays <= 2) {
                    $status = 'Due Soon';
                    $badgeClass = 'bg-warning';
                    $dueText = $diffInDays == 0 ? 'Due today' : "Due in $diffInDays days";
                } else {
                    $status = 'Upcoming';
                    $badgeClass = 'bg-info';
                    $dueText = "Due in $diffInDays days";
                }

                return (object)[
                    'unit' => $bill->unit ? $bill->unit->UnitIdentity : 'N/A',
                    'dueDate' => $dueDate->format('Y-m-d'),
                    'dueText' => $dueText,
                    'amount' => number_format($bill->TotalPayable, 2),
                    'status' => $status,
                    'badgeClass' => $badgeClass,
                    'billId' => $bill->BillID
                ];
            });

        return view('maintenance-requests.show', compact('maintenanceRequest', 'upcomingRentDues'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        $maintenanceRequest = MaintenanceRequest::with(['unit.property'])
            ->whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->findOrFail($id);
            
        return view('maintenance-requests.edit', compact('maintenanceRequest'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Find the maintenance request and verify company access
        $maintenanceRequest = MaintenanceRequest::with(['unit.property'])
            ->whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->findOrFail($id);
            
        $validated = $request->validate([
            'status' => 'required|in:Pending,In Progress,Completed,Cancelled',
            'technician_notes' => 'nullable|string',
            'completion_date' => 'nullable|date',
        ]);
        
        $maintenanceRequest->update([
            'status' => $validated['status'],
            'technician_notes' => $validated['technician_notes'] ?? null,
            'completion_date' => $validated['completion_date'] ?? null,
            'updated_by' => $this->user()->id,
        ]);
        
        return redirect()->route('maintenance-requests.show', $maintenanceRequest->id)
            ->with('success', 'Maintenance request updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        // Get the authenticated user's CompanyID
        $companyId = $this->user()->CompanyID;;
        
        if (!$companyId) {
            return redirect()->back()->with('error', 'No company associated with this account.');
        }
        
        // Find the maintenance request and verify company access
        $maintenanceRequest = MaintenanceRequest::with(['unit.property'])
            ->whereHas('unit.property', function($q) use ($companyId) {
                $q->where('CompanyID', $companyId);
            })
            ->findOrFail($id);
            
        $maintenanceRequest->delete();
        
        return redirect()->route('maintenance-requests.index')
            ->with('success', 'Maintenance request deleted successfully.');
    }
}
