<?php

namespace App\Http\Controllers;

use App\Models\UnitAssignment;
use App\Models\Customer;
use App\Models\ProUnit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class UnitAssignmentController extends Controller
{
    /**
     * Display a listing of unit assignments for a specific unit.
     */
    public function index($propertyId, $unitId)
    {
        $unit = ProUnit::where('UnitID', $unitId)
            ->where('PropID', $propertyId)
            ->with(['currentAssignments.customer'])
            ->firstOrFail();

        return view('units.assignments.index', [
            'unit' => $unit,
            'propertyId' => $propertyId,
            'assignments' => $unit->currentAssignments,
        ]);
    }

    /**
     * Show the form for creating a new assignment.
     */
    public function create($propertyId, $unitId)
    {
        $unit = ProUnit::where('UnitID', $unitId)
            ->where('PropID', $propertyId)
            ->firstOrFail();

        // Get only customers who don't have any unit assigned (UnitID is null or empty)
        $customers = Customer::whereNull('UnitID')
            ->orWhere('UnitID', '')
            ->orderBy('CustomerName')
            ->get();

        return view('units.assignments.create', [
            'unit' => $unit,
            'propertyId' => $propertyId,
            'customers' => $customers,
        ]);
    }

    /**
     * Store a newly created assignment in storage.
     */
    public function store(Request $request, $propertyId, $unitId)
    {
        // Check if the unit already has an active assignment
        $existingAssignment = UnitAssignment::where('unit_id', $unitId)
            ->where('status', 'active')
            ->exists();
            
        if ($existingAssignment) {
            return back()
                ->withInput()
                ->with('error', 'This unit is already assigned to a customer. Please terminate the current assignment first.');
        }

        $validated = $request->validate([
            'customer_id' => [
                'required',
                'exists:CUSTOMER,CustomerID',
            ],
            'start_date' => 'required|date',
            'notes' => 'nullable|string|max:500',
        ]);

        try {
            DB::beginTransaction();

            // End any existing active assignment for this customer
            UnitAssignment::where('customer_id', $validated['customer_id'])
                ->where('status', 'active')
                ->update([
                    'status' => 'transferred',
                    'end_date' => now(),
                    'notes' => 'Transferred to another unit',
                ]);

            // Create new assignment
            $assignment = new UnitAssignment([
                'customer_id' => $validated['customer_id'],
                'unit_id' => $unitId,
                'start_date' => $validated['start_date'],
                'status' => 'active',
                'notes' => $validated['notes'] ?? null,
            ]);

            $assignment->save();

             // Update Occupation status
            ProUnit::where('UnitID', $unitId)
                ->update(['OccupationStatus'=>'Active']);

            // Update customer's unit_id
            Customer::where('CustomerID', $validated['customer_id'])
                ->update(['UnitID' => $unitId, 'AccountStatus'=>'A']);

            DB::commit();

            return redirect()
                ->route('properties.units.assignments.index', [$propertyId, $unitId])
                ->with('success', 'Customer assigned to unit successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error assigning customer to unit: ' . $e->getMessage());
            
            return back()
                ->withInput()
                ->with('error', 'Failed to assign customer to unit. Please try again.');
        }
    }

    /**
     * Terminate an active assignment.
     */
    public function terminate(Request $request, $propertyId, $unitId, $assignmentId)
    {
        $validated = $request->validate([
            'end_date' => 'required|date|after_or_equal:today',
            'notes' => 'nullable|string|max:500',
        ]);

        try {
            $assignment = UnitAssignment::where('id', $assignmentId)
                ->where('unit_id', $unitId)
                ->where('status', 'active')
                ->firstOrFail();

            DB::beginTransaction();

            // Update the assignment
            $assignment->update([
                'status' => 'terminated',
                'end_date' => $validated['end_date'],
                'notes' => $validated['notes'] ?? 'Assignment terminated',
            ]);

            // Clear customer's unit_id
            Customer::where('CustomerID', $assignment->customer_id)
                ->update(['UnitID' => null]);

            DB::commit();

            return redirect()
                ->route('properties.units.assignments.index', [$propertyId, $unitId])
                ->with('success', 'Assignment terminated successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error terminating assignment: ' . $e->getMessage());
            
            return back()
                ->with('error', 'Failed to terminate assignment. Please try again.');
        }
    }

    /**
     * Show the form for terminating an assignment.
     */
    public function showTerminateForm($propertyId, $unitId, $assignmentId)
    {
        $assignment = UnitAssignment::with(['customer', 'unit'])
            ->where('id', $assignmentId)
            ->where('unit_id', $unitId)
            ->firstOrFail();

        return view('units.assignments.terminate', [
            'assignment' => $assignment,
            'propertyId' => $propertyId,
            'unitId' => $unitId,
        ]);
    }
}
