<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User;

class VendorController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();
        $query = DB::table('users')
            ->where('role', 'vendor');

        // Scope to society if not super admin
        if ($user->role !== 'super_admin' && $user->society_id) {
            $query->where('society_id', $user->society_id);
        }

        if ($request->has('status')) {
            $query->where('vendor_status', $request->status);
        }

        if ($request->has('type')) {
            $query->where('vendor_type', $request->query('type'));
        }

        if ($request->has('search')) {
            $search = $request->query('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('vendor_company_name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('vendor_type', 'like', "%{$search}%");
            });
        }

        $vendors = $query->select(
            'id',
            'name',
            'email',
            'phone',
            'vendor_company_name',
            'vendor_type',
            'vendor_status',
            'vendor_rating',
            'vendor_completed_projects',
            'vendor_registration_date'
        )->paginate(10);

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

    public function show($id)
    {
        $user = auth()->user();

        $vendor = DB::table('users')
            ->where('id', $id)
            ->where('role', 'vendor')
            ->when($user->role !== 'super_admin' && $user->society_id, function ($q) use ($user) {
                return $q->where('society_id', $user->society_id);
            })
            ->first();

        if (!$vendor) {
            return response()->json(['message' => 'Vendor not found'], 404);
        }

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

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:active,inactive,suspended,blocked',
            'reason' => 'required_if:status,suspended,blocked|string|nullable',
            'suspended_until' => 'nullable|date'
        ]);

        $user = auth()->user();

        // Only admins can update status
        if (!in_array($user->role, ['super_admin', 'society_admin', 'secretary'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $vendor = DB::table('users')
            ->where('id', $id)
            ->where('role', 'vendor')
            ->where('society_id', $user->society_id)
            ->first();

        if (!$vendor) {
            return response()->json(['message' => 'Vendor not found'], 404);
        }

        $updateData = [
            'vendor_status' => $request->status,
            'updated_at' => now()
        ];

        if (in_array($request->status, ['suspended', 'blocked'])) {
            $updateData['blocked_reason'] = $request->reason;
            $updateData['suspended_until'] = $request->suspended_until;
        } else {
            // Clear suspension details if reactivating
            $updateData['blocked_reason'] = null;
            $updateData['suspended_until'] = null;
        }

        DB::table('users')->where('id', $id)->update($updateData);

        return response()->json(['message' => 'Vendor status updated successfully', 'status' => $request->status]);
    }

    public function getPerformance($id)
    {
        $user = auth()->user();

        $vendor = DB::table('users')
            ->where('id', $id)
            ->where('role', 'vendor')
            ->where('society_id', $user->society_id)
            ->first();

        if (!$vendor) {
            return response()->json(['message' => 'Vendor not found'], 404);
        }

        // Calculate performance metrics
        $totalBids = DB::table('tender_bids')->where('vendor_id', $id)->count();
        $wonBids = DB::table('tender_bids')
            ->where('vendor_id', $id)
            ->where('status', 'accepted')
            ->count();

        $activeProjects = DB::table('tenders')
            ->where('awarded_vendor_id', $id)
            ->where('status', '!=', 'closed')
            ->count();

        $winRate = $totalBids > 0 ? round(($wonBids / $totalBids) * 100, 1) : 0;

        return response()->json([
            'total_bids' => $totalBids,
            'won_bids' => $wonBids,
            'win_rate' => $winRate . '%',
            'active_projects' => $activeProjects,
            'completed_projects' => $vendor->vendor_completed_projects,
            'rating' => $vendor->vendor_rating
        ]);
    }
}
