<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Traits\DeleteModelTrait;
use App\Traits\FlashMessageTrait;
use App\Models\RentalAgreement;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminRentalAgreementController extends Controller
{
    use DeleteModelTrait, FlashMessageTrait;

    /**
     * Display a listing of rental agreements
     */
    public function index(Request $request)
    {
        try {
            $perPage = 5;
            $query = RentalAgreement::with(['property', 'tenant', 'landlord', 'booking']);
            
            // Apply filters
            if ($request->has('is_active')) {
                $query->where('is_active', $request->is_active);
            }
            
            $agreements = $query->orderBy('created_at', 'desc')->paginate($perPage);
            
            // Calculate serial numbers and format data
            $agreements->getCollection()->transform(function ($agreement, $index) use ($agreements) {
                $agreement->sn = ($agreements->currentPage() - 1) * $agreements->perPage() + $index + 1;
                $agreement->property_title = $agreement->property->title ?? 'N/A';
                $agreement->tenant_name = $agreement->tenant->name ?? 'N/A';
                $agreement->landlord_name = $agreement->landlord->name ?? 'N/A';
                return $agreement;
            });

            return Inertia::render('Admin/RentalAgreements/RentalAgreement', [
                'agreements' => $agreements->items(),
                'pagination' => [
                    'current_page' => $agreements->currentPage(),
                    'last_page' => $agreements->lastPage(),
                    'per_page' => $agreements->perPage(),
                    'total' => $agreements->total(),
                    'from' => $agreements->firstItem(),
                    'to' => $agreements->lastItem(),
                    'links' => $agreements->linkCollection()->toArray(),
                ],
                'filters' => $request->only(['is_active'])
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load rental agreements: ' . $e->getMessage());
        }
    }

    /**
     * Show rental agreement details
     */
    public function show($id)
    {
        try {
            $agreement = RentalAgreement::with(['property', 'tenant', 'landlord', 'booking'])->find($id);
            
            if (!$agreement) {
                return response()->json(['error' => 'Rental agreement not found'], 404);
            }

            return response()->json($agreement);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Toggle agreement status
     */
    public function toggleStatus($id)
    {
        try {
            $agreement = RentalAgreement::findOrFail($id);
            $agreement->update(['is_active' => !$agreement->is_active]);
            
            $status = $agreement->is_active ? 'activated' : 'deactivated';
            return $this->success("Rental agreement {$status} successfully");
        } catch (\Exception $e) {
            return $this->error('Failed to update agreement status: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified rental agreement
     */
    public function destroy($id)
    {
        try {
            $agreement = RentalAgreement::find($id);

            if (!$agreement) {
                return $this->error('Rental agreement not found');
            }

            return $this->deleteModel($id, new RentalAgreement());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
