<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\PricingPlan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class CompaniesController extends Controller
{
    public function index(Request $request)
    {
        $query = Company::with('user')->withTrashed(false);

        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($q) use ($search) {
                      $q->where('name',  'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%")
                        ->orWhere('phone', 'like', "%{$search}%");
                  });
            });
        }

        if ($status = $request->get('status')) {
            $query->whereHas('user', fn($q) => $q->where('plan_status', $status));
        }

        $query->latest();
        $companies = $query->paginate(15)->withQueryString();

        // Stats strip
        $total   = Company::count();
        $active  = Company::whereHas('user', fn($q) => $q->where('plan_status', 'active'))->count();
        $trial   = Company::whereHas('user', fn($q) => $q->where('plan_status', 'trial'))->count();
        $expired = Company::whereHas('user', fn($q) => $q->where('plan_status', 'expired'))->count();

        // Dormant: owner hasn't logged in for 6+ months (or never)
        $dormantCompanies = Company::with('user')
            ->whereHas('user', function ($q) {
                $q->where(function ($q2) {
                    $q2->whereNull('last_login_at')
                       ->orWhere('last_login_at', '<', now()->subMonths(6));
                });
            })
            ->latest()
            ->get();

        // Pricing plans for name lookup in the table
        $plans = PricingPlan::orderBy('name')->get()->keyBy('id');

        return view('companies', compact('companies', 'total', 'active', 'trial', 'expired', 'dormantCompanies', 'plans'))
            ->with('authUser', Auth::user());
    }

    public function store(Request $request)
    {
        $request->validate([
            'company_name'        => ['required', 'string', 'max:255'],
            'company_address'     => ['nullable', 'string', 'max:500'],
            'currency'            => ['nullable', 'string', 'max:10'],
            'company_description' => ['nullable', 'string', 'max:1000'],
            'name'                => ['required', 'string', 'max:255'],
            'email'               => ['required', 'email', 'max:255', 'unique:users,email'],
            'password'            => ['required', 'string', 'min:8'],
            'phone'               => ['nullable', 'string', 'max:20'],
            'whatsapp_num'        => ['nullable', 'string', 'max:20'],
            'plan_status'         => ['nullable', 'string', 'in:trial,active,expired'],
        ]);

        DB::transaction(function () use ($request) {
            $user = User::create([
                'name'          => $request->name,
                'email'         => $request->email,
                'password'      => $request->password,
                'phone'         => $request->phone,
                'whatsapp_num'  => $request->whatsapp_num,
                'business_name' => $request->company_name,
                'plan_status'   => $request->plan_status ?? 'trial',
                'role'          => 'user',
                'api_token'     => $token = strtoupper(Str::random(20)),
                'verify_token'  => $token,
            ]);

            $company = Company::create([
                'name'        => $request->company_name,
                'address'     => $request->company_address,
                'currency'    => $request->currency ?: 'USD',
                'description' => $request->company_description,
                'user_id'     => $user->id,
            ]);

            $user->update(['company_id' => $company->id]);
        });

        return redirect()->route('companies')->with('success', 'Company and owner account created successfully.');
    }

    public function update(Request $request, Company $company)
    {
        $owner = $company->user;

        $request->validate([
            'company_name'        => ['required', 'string', 'max:255'],
            'company_address'     => ['nullable', 'string', 'max:500'],
            'currency'            => ['nullable', 'string', 'max:10'],
            'company_description' => ['nullable', 'string', 'max:1000'],
            'owner_name'          => ['required', 'string', 'max:255'],
            'owner_email'         => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($owner?->id)],
            'owner_phone'         => ['nullable', 'string', 'max:20'],
            'owner_whatsapp'      => ['nullable', 'string', 'max:20'],
            'plan_status'         => ['nullable', 'string', 'in:trial,active,expired'],
            'owner_password'      => ['nullable', 'string', 'min:8'],
        ]);

        $company->update([
            'name'        => $request->company_name,
            'address'     => $request->company_address,
            'currency'    => $request->currency ?: 'USD',
            'description' => $request->company_description,
        ]);

        if ($owner) {
            $ownerData = [
                'name'          => $request->owner_name,
                'email'         => $request->owner_email,
                'phone'         => $request->owner_phone,
                'whatsapp_num'  => $request->owner_whatsapp,
                'business_name' => $request->company_name,
                'plan_status'   => $request->plan_status ?? $owner->plan_status,
            ];
            if ($request->filled('owner_password')) {
                $ownerData['password'] = $request->owner_password;
            }
            $owner->update($ownerData);
        }

        return redirect()->route('companies')->with('success', 'Company updated successfully.');
    }

    public function destroy(Company $company)
    {
        $company->delete();
        return back()->with('success', 'Company deleted.');
    }
}
