<?php

namespace App\Modules\Admin;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;
use App\Http\Controllers\BaseController;
use App\Modules\Admin\Contract;
use App\Modules\Clients\Client;

class ContractsController extends BaseController
{
    /**
     * Display a listing of the resource.
     */
    public function index(): View
    {
        $contracts = Contract::with('client')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('admin::settings.contracts.index', compact('contracts'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        $clients = Client::select('id', 'name')->get();
        return view('admin::settings.contracts.create', compact('clients'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [
            'client_id' => 'required|exists:clients,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after:start_date',
            'value' => 'nullable|numeric|min:0',
            'status' => 'required|in:active,inactive,expired',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $validator->validated();
        
        $contract = Contract::create($data);

        return redirect()->route('admin.settings.contracts.index')
            ->with('message', 'Contract created successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(int $id): JsonResponse
    {
        $contract = Contract::with('client')->find($id);

        if (!$contract) {
            return response()->json(['error' => 'Contract not found'], 404);
        }

        return response()->json($contract);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(int $id): View
    {
        $contract = Contract::with('client')->find($id);

        if (!$contract) {
            abort(404, 'Contract not found');
        }

        $clients = Client::select('id', 'name')->get();
        return view('admin::settings.contracts.edit', compact('contract', 'clients'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, int $id): RedirectResponse
    {
        $contract = Contract::find($id);

        if (!$contract) {
            abort(404, 'Contract not found');
        }

        $validator = Validator::make($request->all(), [
            'client_id' => 'required|exists:clients,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date|after:start_date',
            'value' => 'nullable|numeric|min:0',
            'status' => 'required|in:active,inactive,expired',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $validator->validated();
        $contract->update($data);

        return redirect()->route('admin.settings.contracts.index')
            ->with('message', 'Contract updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $id): JsonResponse
    {
        $contract = Contract::find($id);

        if (!$contract) {
            return response()->json(['error' => 'Contract not found'], 404);
        }

        // Check if any clients are using this contract
        $clientsUsingContract = $contract->clients()->count();

        if ($clientsUsingContract > 0) {
            return response()->json([
                'error' => 'Cannot delete contract. It is currently assigned to ' . $clientsUsingContract . ' client(s).'
            ], 422);
        }

        $contract->delete();

        return response()->json([
            'success' => true, 
            'message' => 'Contract deleted successfully'
        ]);
    }
}
