<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class CompanyController extends Controller
{
    use ApiResponse;

    private function formatCompanyData($company)
    {
        $formatted = [
            'id' => $company->id,
            'name' => $company->name,
            'source' => $company->source,
            'industry' => $company->industry,
            'sub_industry' => $company->sub_industry,
            'state' => $company->state,
            'city' => $company->city,
            'address' => $company->address,
            'zipcode' => $company->zipcode,
            'website' => $company->website,
            'logo' => $company->logo ? Storage::disk('public')->url($company->logo) : null,
            'creator' => $company->creator ? [
                'id' => $company->creator->id,
                'name' => $company->creator->name,
                'image_path' => $company->creator->image_path ? Storage::disk('public')->url($company->creator->image_path) : null,
            ] : null,
            'status' => $company->status,
            'created_at' => $company->created_at,
            'updated_at' => $company->updated_at,
        ];

        return (object) $formatted;
    }

    public function create_company(Request $request)
    {
        $user = $request->user();

        $hasCreate = $user->can('lead_management.company.create');
        $hasOverride = $user->can('lead_management.company.override');

        if (!$hasCreate && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'source' => ['nullable', 'string', 'max:255'],
            'industry' => ['nullable', 'string', 'max:255'],
            'sub_industry' => ['nullable', 'string', 'max:255'],
            'state' => ['nullable', 'string', 'max:255'],
            'city' => ['nullable', 'string', 'max:255'],
            'address' => ['nullable', 'string', 'max:255'],
            'zipcode' => ['nullable', 'string', 'max:255'],
            'website' => ['nullable', 'string', 'max:255'],
            'logo' => ['nullable', 'file', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
        ]);

        $disk = 'public';
        $path = null;
        $fileName = null;

        if ($request->hasFile('logo')) {
            $file = $request->file('logo');
            $fileName = 'company_' . time() . '_' . Str::random(6) . '.' . $file->getClientOriginalExtension();
            $path = "companies_logo/{$fileName}";

            Storage::disk($disk)->putFileAs('companies_logo', $file, $fileName);
        }

        // 2. Create the company in a single database hit
        $company = Company::create([
            'name' => $request->name,
            'source' => $request->source,
            'industry' => $request->industry,
            'sub_industry' => $request->sub_industry,
            'state' => $request->state,
            'city' => $request->city,
            'address' => $request->address,
            'zipcode' => $request->zipcode,
            'website' => $request->website,
            'logo' => $path,
            'created_by' => $user->id,
            'created_at' => now()->toDateTimeString(),
        ]);

        // Load creator relationship
        $company->load('creator');

        // Fixed the logger to target the company, not the user integer.
        activity('company_management')
            ->performedOn($company)
            ->causedBy($user)
            ->withProperties([
                'file_name' => $fileName,
                'disk' => $disk,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ])
            ->log("User {$user->name} created company: {$company->name}");

        return $this->success('Company created successfully', $this->formatCompanyData($company));
    }

    public function update_company(Request $request)
    {
        $user = $request->user();

        $hasUpdate = $user->can('lead_management.company.update');
        $hasOverride = $user->can('lead_management.company.override');

        if (!$hasUpdate && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        $company = Company::find($request->id);

        if (!$company) {
            return $this->error('Company not found.', 404);
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'source' => ['nullable', 'string', 'max:255'],
            'industry' => ['nullable', 'string', 'max:255'],
            'sub_industry' => ['nullable', 'string', 'max:255'],
            'state' => ['nullable', 'string', 'max:255'],
            'city' => ['nullable', 'string', 'max:255'],
            'address' => ['nullable', 'string', 'max:255'],
            'zipcode' => ['nullable', 'string', 'max:255'],
            'website' => ['nullable', 'string', 'max:255'],
            'logo' => ['nullable', 'file', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
        ]);

        $disk = 'public';
        $path = $company->getRawOriginal('logo');
        $fileName = null;

        // Handle File logic
        if ($request->hasFile('logo')) {
            if ($path && Storage::disk($disk)->exists($path)) {
                Storage::disk($disk)->delete($path);
            }

            $file = $request->file('logo');
            $fileName = 'company_' . time() . '_' . Str::random(6) . '.' . $file->getClientOriginalExtension();
            $path = "companies_logo/{$fileName}";

            Storage::disk($disk)->putFileAs('companies_logo', $file, $fileName);
        }

        // Capture old data for the log before filling the model
        $oldData = $company->only(['name', 'source', 'industry', 'sub_industry', 'state', 'city', 'address', 'zipcode', 'website', 'logo']);

        $company->fill([
            'name' => $request->name,
            'source' => $request->source,
            'industry' => $request->industry,
            'sub_industry' => $request->sub_industry,
            'state' => $request->state,
            'city' => $request->city,
            'address' => $request->address,
            'zipcode' => $request->zipcode,
            'website' => $request->website,
            'logo' => $path,
        ]);

        if ($company->isDirty()) {
            $company->save();

            // Log Update Activity only if changes were actually made
            activity('company_management')
                ->performedOn($company)
                ->causedBy($user)
                ->withProperties([
                    'old' => $oldData,
                    'new' => $company->only(['name', 'source', 'industry', 'sub_industry', 'state', 'city', 'address', 'zipcode', 'website', 'logo']),
                    'file_name' => $fileName,
                    'ip' => $request->ip()
                ])
                ->log("User {$user->name} updated company: {$company->name}");
        }

        return $this->success('Company updated successfully', $this->formatCompanyData($company));
    }

    public function fetch_active_companies(Request $request)
    {
        $user = $request->user();

        // 🔐 Permission Check
        $hasRead = $user->can('lead_management.company.read');
        $hasOverride = $user->can('lead_management.company.override');

        if (!$hasRead && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        // ✅ PAGINATED QUERY WITH REQUIRED FIELDS ONLY
        $paginatedCompanies = Company::with('creator')->select([
            'id',
            'name',
            'source',
            'website',
            'industry',
            'sub_industry',
            'state',
            'city',
            'address',
            'zipcode',
            'logo',
            'created_by',
            'status',
            'created_at',
            'updated_at'
        ])->where('is_deleted', 0)->where('status', 1)->latest()->paginate(15);

        // ✅ TRANSFORM DATA (ADD logo_url)
        $companies = $paginatedCompanies->getCollection()->map(function ($company) {
            return $this->formatCompanyData($company);
        });

        // ✅ FINAL RESPONSE (YOUR FORMAT)
        return $this->success('Companies fetched successfully.', [
            'data' => $companies,
            'current_page' => $paginatedCompanies->currentPage(),
            'next_page' => $paginatedCompanies->hasMorePages()
                ? $paginatedCompanies->currentPage() + 1
                : null,
            'last_page' => $paginatedCompanies->lastPage(),
            'total_items' => $paginatedCompanies->total(),
            'per_page' => $paginatedCompanies->perPage(),
        ]);
    }

    public function fetch_inactive_companies(Request $request)
    {
        $user = $request->user();

        // 🔐 Permission Check
        $hasRead = $user->can('lead_management.company.read');
        $hasOverride = $user->can('lead_management.company.override');

        if (!$hasRead && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        // ✅ PAGINATED QUERY WITH REQUIRED FIELDS ONLY
        $paginatedCompanies = Company::with('creator')->select([
            'id',
            'name',
            'source',
            'website',
            'industry',
            'sub_industry',
            'state',
            'city',
            'address',
            'zipcode',
            'logo',
            'created_by',
            'status',
            'created_at',
            'updated_at'
        ])->where('is_deleted', 0)->where('status', 0)->latest()->paginate(15);

        // ✅ TRANSFORM DATA (ADD logo_url)
        $companies = $paginatedCompanies->getCollection()->map(function ($company) {
            return $this->formatCompanyData($company);
        });

        // ✅ FINAL RESPONSE (YOUR FORMAT)
        return $this->success('Companies fetched successfully.', [
            'data' => $companies,
            'current_page' => $paginatedCompanies->currentPage(),
            'next_page' => $paginatedCompanies->hasMorePages()
                ? $paginatedCompanies->currentPage() + 1
                : null,
            'last_page' => $paginatedCompanies->lastPage(),
            'total_items' => $paginatedCompanies->total(),
            'per_page' => $paginatedCompanies->perPage(),
        ]);
    }

    public function update_company_status(Request $request)
    {
        $user = $request->user();

        // 🔐 Permission Check
        $hasUpdate = $user->can('lead_management.company.update');
        $hasOverride = $user->can('lead_management.company.override');

        if (!$hasUpdate && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        // ✅ Validation
        $request->validate([
            'company_id' => ['required', 'exists:companies,id'],
            'status' => ['required', 'in:0,1'],
        ]);

        $company = Company::with('creator')->where('id', $request->company_id)
            ->where('is_deleted', 0)->first();

        if (!$company) {
            return $this->error('Company not found.', 404);
        }

        $company->update(['status' => $request->status]);

        return $this->success('Status updated', $this->formatCompanyData($company));
    }

    public function delete_company(Request $request)
    {
        $user = $request->user();

        // 🔐 Permission Check
        $hasDelete = $user->can('lead_management.company.delete');
        $hasOverride = $user->can('lead_management.company.override');

        if (!$hasDelete && !$hasOverride) {
            return $this->error('Forbidden', 403);
        }

        // ✅ Validation
        $request->validate([
            'company_id' => ['required', 'exists:companies,id']
        ]);

        // 🔍 Find Company
        $updated = Company::where('id', $request->company_id)
            ->where('is_deleted', 0)
            ->update([
                'is_deleted' => 1,
                'deleted_at' => now()->toDateTimeString(),
                'updated_at' => now()->toDateTimeString(),
            ]);

        if (!$updated) {
            return $this->error('Company not found or already deleted.', 404);
        }

        return $this->success('Company deleted successfully.');
    }

    public function search_companies(Request $request)
    {
        $request->validate([
            'search' => ['required', 'string','min:3' , 'max:255'],
        ]);

        $companies = Company::with('creator')->where('is_deleted', 0)->where('status', 1)
            ->where(function ($q) use ($request) {
                $q->where('name', 'LIKE', "%{$request->search}%")
                    ->orWhere('industry', 'LIKE', "%{$request->search}%")
                    ->orWhere('city', 'LIKE', "%{$request->search}%");
            })->limit(20)->get();

        return $this->success('Company list', $companies->map(function ($company) {
            return $this->formatCompanyData($company);
        }));
    }
}
