<?php

namespace App\Http\Controllers;

use App\Models\Trade;
use App\Models\SubcontractorCompany;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TradeController extends Controller
{
    /**
     * Display a listing of trades.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $trades = Trade::where('del', '0');
        
        // Add search functionality if search parameter is provided
        if ($request->filled('search')) {
            $search = $request->input('search');
            $trades->where('title', 'like', '%' . $search . '%');
        }
        
        $trades->orderBy('title', 'asc');
        
        return $this->withCount($trades, "Trades retrieved successfully.");
    }

    /**
     * Store a newly created trade in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
        ], [
            'title.required' => 'Trade title is required',
            'title.string' => 'Trade title must be a string',
            'title.max' => 'Trade title must not exceed 255 characters',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        // Check if trade with same title already exists
        $existingTrade = Trade::where('title', $request->title)
            ->where('del', '0')
            ->first();
            
        if ($existingTrade) {
            return $this->error('Trade with this title already exists', 422);
        }

        $trade = Trade::create([
            'title' => $request->title,
            'del' => '0',
        ]);

        return $this->success($trade, 'Trade created successfully', 201);
    }

    /**
     * Display the specified trade.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $trade = Trade::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$trade) {
            return $this->notFound('Trade not found', 404);
        }

        return $this->success($trade, 'Trade retrieved successfully');
    }

    /**
     * Update the specified trade in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer|exists:trades,id',
            'title' => 'required|string|max:255',
        ], [
            'id.required' => 'Trade ID is required',
            'id.integer' => 'Trade ID must be an integer',
            'id.exists' => 'Trade not found',
            'title.required' => 'Trade title is required',
            'title.string' => 'Trade title must be a string',
            'title.max' => 'Trade title must not exceed 255 characters',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $id = $request->input('id');
        $trade = Trade::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$trade) {
            return $this->notFound('Trade not found', 404);
        }

        // Check if another trade with same title already exists (excluding current one)
        $existingTrade = Trade::where('title', $request->title)
            ->where('id', '!=', $id)
            ->where('del', '0')
            ->first();
            
        if ($existingTrade) {
            return $this->error('Trade with this title already exists', 422);
        }

        $trade->update([
            'title' => $request->title,
        ]);

        return $this->success($trade->fresh(), 'Trade updated successfully');
    }

    /**
     * Remove the specified trade from storage (soft delete).
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $trade = Trade::where('id', $id)
            ->where('del', '0')
            ->first();

        if (!$trade) {
            return $this->notFound('Trade not found', 404);
        }

        // Check if trade is being used by any subcontractor companies
        $usageCount = SubcontractorCompany::where('trade_id', $id)
            ->where('del', '0')
            ->count();

        if ($usageCount > 0) {
            return $this->error('Cannot delete trade. It is being used by ' . $usageCount . ' subcontractor company(ies).', 422);
        }

        // Soft delete by setting del to '1'
        $trade->update(['del' => '1']);

        return $this->message('Trade deleted successfully', 200);
    }

    /**
     * Get all trades (for customers and subcontractors - read only).
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function getTrades(Request $request)
    {
        try {
            $trades = Trade::where('del', '0')
                ->orderBy('title', 'asc')
                ->select('id', 'title')
                ->get();

            return $this->success($trades, 'Trades retrieved successfully', 200);
        } catch (\Exception $e) {
            return $this->message('Error retrieving trades: ' . $e->getMessage(), 500);
        }
    }
}

