--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\BusinessDirectorySettingController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Modules\BusinessDirectory\Settings\BusinessDirectorySettings;

class BusinessDirectorySettingController extends Controller
{
    public function __construct()
    {
        // Add any necessary middleware, e.g., for admin authentication
        // $this->middleware('auth:admin'); // Example
    }

    /**
     * Show the form for editing the settings.
     *
     * @param BusinessDirectorySettings $settings
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(BusinessDirectorySettings $settings)
    {
        $this->authorize('manage_settings', BusinessDirectorySettings::class); // Assuming a policy or gate
        return view('businessdirectory::admin.settings.edit', compact('settings'));
    }

    /**
     * Update the settings in storage.
     *
     * @param Request $request
     * @param BusinessDirectorySettings $settings
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, BusinessDirectorySettings $settings)
    {
        $this->authorize('manage_settings', BusinessDirectorySettings::class);

        $validatedData = $request->validate([
            'site_name' => 'required|string|max:255',
            'site_tagline' => 'nullable|string|max:255',
            'contact_email' => 'nullable|email|max:255',
            'pagination_count' => 'required|integer|min:1',
            'auto_approve_companies' => 'nullable|boolean',
            'currency_symbol' => 'nullable|string|max:5',
            'currency_code' => 'nullable|string|max:3',

            'social_facebook_url' => 'nullable|url|max:255',
            'social_twitter_url' => 'nullable|url|max:255',
            'social_linkedin_url' => 'nullable|url|max:255',
            'social_instagram_url' => 'nullable|url|max:255',

            'homepage_hero_title' => 'nullable|string|max:255',
            'homepage_hero_subtitle' => 'nullable|string|max:500',
            'homepage_hero_search_placeholder' => 'nullable|string|max:100',

            'hero_slide_1_title' => 'nullable|string|max:255',
            'hero_slide_1_subtitle' => 'nullable|string|max:500',
            'hero_slide_1_button_text' => 'nullable|string|max:100',
            'hero_slide_1_button_link' => 'nullable|string|max:255',
            'hero_slide_1_image' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',

            'hero_slide_2_title' => 'nullable|string|max:255',
            'hero_slide_2_subtitle' => 'nullable|string|max:500',
            'hero_slide_2_button_text' => 'nullable|string|max:100',
            'hero_slide_2_button_link' => 'nullable|string|max:255',
            'hero_slide_2_image' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',

            'homepage_featured_companies_count' => 'nullable|integer|min:0',
            'homepage_featured_products_count' => 'nullable|integer|min:0',
            'homepage_latest_tenders_count' => 'nullable|integer|min:0',
            'homepage_latest_jobs_count' => 'nullable|integer|min:0',
        ]);

        // Update all validated string/numeric settings directly
        foreach ($validatedData as $key => $value) {
            if ($request->hasFile($key)) { // Skip file fields for now
                continue;
            }
            // For boolean fields not explicitly validated as boolean but present in form (checkboxes)
            if (array_key_exists($key, $settings->getAttributes()) && is_bool($settings->getAttributes()[$key]) && !$request->has($key)) {
                $settings->$key = false;
            } elseif (is_string($value) || is_numeric($value) || is_null($value) || is_bool($value)) {
                 $settings->$key = $value;
            }
        }

        $settings->auto_approve_companies = $request->boolean('auto_approve_companies');

        // Handle file uploads for slider images
        foreach (['hero_slide_1_image', 'hero_slide_2_image'] as $imageField) {
            if ($request->hasFile($imageField)) {
                if ($settings->$imageField && Storage::disk('public')->exists($settings->$imageField)) {
                    Storage::disk('public')->delete($settings->$imageField);
                }
                $path = $request->file($imageField)->store('settings/hero_slider', 'public');
                $settings->$imageField = $path;
            } elseif ($request->has("remove_{$imageField}")) {
                if ($settings->$imageField && Storage::disk('public')->exists($settings->$imageField)) {
                    Storage::disk('public')->delete($settings->$imageField);
                }
                $settings->$imageField = null;
            }
        }

        $settings->save();

        return redirect()->route('admin.businessdirectory.settings.edit')
                         ->with('success', 'Settings updated successfully.');
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\CategoryController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\BusinessDirectory\Entities\Category;
use Modules\BusinessDirectory\Http\Requests\Admin\StoreCategoryRequest;
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateCategoryRequest;
use Illuminate\Support\Facades\Storage;

class CategoryController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Category::class, 'category');
    }

    public function index(Request $request)
    {
        $query = Category::with('parent')->withCount(['companies', 'products', 'tenders', 'jobs'])->latest();
        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }
        $categories = $query->paginate(15);
        return view('businessdirectory::admin.categories.index', compact('categories'));
    }

    public function create()
    {
        $parentCategories = Category::whereNull('parent_id')->orderBy('name')->pluck('name', 'id');
        return view('businessdirectory::admin.categories.create', compact('parentCategories'));
    }

    public function store(StoreCategoryRequest $request)
    {
        $validatedData = $request->validated();
        if ($request->hasFile('image_path')) {
            $validatedData['image_path'] = $request->file('image_path')->store('category_images', 'public');
        }
        Category::create($validatedData);
        return redirect()->route('admin.businessdirectory.categories.index')->with('success', 'Category created successfully.');
    }

    public function edit(Category $category)
    {
        $parentCategories = Category::whereNull('parent_id')->where('id', '!=', $category->id)->orderBy('name')->pluck('name', 'id');
        return view('businessdirectory::admin.categories.edit', compact('category', 'parentCategories'));
    }

    public function update(UpdateCategoryRequest $request, Category $category)
    {
        $validatedData = $request->validated();
        if ($request->hasFile('image_path')) {
            if ($category->image_path) {
                Storage::disk('public')->delete($category->image_path);
            }
            $validatedData['image_path'] = $request->file('image_path')->store('category_images', 'public');
        } elseif ($request->boolean('remove_image_path')) {
             if ($category->image_path) {
                Storage::disk('public')->delete($category->image_path);
            }
            $validatedData['image_path'] = null;
        }

        $category->update($validatedData);
        return redirect()->route('admin.businessdirectory.categories.index')->with('success', 'Category updated successfully.');
    }

    public function destroy(Category $category)
    {
        // Add check for associated items before deletion if necessary
        if ($category->children()->count() > 0 || $category->companies()->count() > 0 /* || etc. */) {
             return redirect()->route('admin.businessdirectory.categories.index')->with('error', 'Cannot delete category. It has child categories or associated items.');
        }
        if ($category->image_path) {
            Storage::disk('public')->delete($category->image_path);
        }
        $category->delete();
        return redirect()->route('admin.businessdirectory.categories.index')->with('success', 'Category deleted successfully.');
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\CompanyController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// Adjust namespace if your Entities are in Entities
use Modules\BusinessDirectory\Entities\Company;
use Modules\BusinessDirectory\Entities\CompanyType;
use App\Models\User; // Standardized User model path
use Illuminate\Support\Facades\Storage;
use Modules\BusinessDirectory\Http\Requests\Admin\StoreCompanyRequest as AdminStoreCompanyRequest;
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateCompanyRequest as AdminUpdateCompanyRequest;

class CompanyController extends Controller
{
    public function __construct()
    {
        // Assuming admin routes are already protected by an admin auth middleware
        // Policy authorization will be done per method.
        // $this->authorizeResource(Company::class, 'company'); // Alternative for full resource controller
        // $this->middleware('can:manage-companies'); // Example permission
    }

    public function index(Request $request)
    {
        $query = Company::with('user', 'companyType')->latest();

        // Admin can view all, so typically no specific viewAny policy check here for index listing
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('email', 'like', "%{$searchTerm}%")
                  ->orWhereHas('user', function ($userQuery) use ($searchTerm) {
                      $userQuery->where('name', 'like', "%{$searchTerm}%")
                                ->orWhere('email', 'like', "%{$searchTerm}%");
                  });
            });
        }

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

        if ($request->filled('company_type_id')) {
            $query->where('company_type_id', $request->company_type_id);
        }

        $companies = $query->paginate(15);
        $companyTypes = CompanyType::orderBy('name')->pluck('name', 'id');
        $statuses = Company::getStatuses(); // Using the static method from Company model

        return view('businessdirectory::admin.companies.index', compact('companies', 'companyTypes', 'statuses'));
    }

    public function create()
    {
        $this->authorize('create', Company::class); // Authorize creation
        $companyTypes = CompanyType::orderBy('name')->pluck('name', 'id');
        $users = User::orderBy('name')->pluck('name', 'id'); // For assigning a user if admin creates
        $statuses = Company::getStatuses();
        return view('businessdirectory::admin.companies.create', compact('companyTypes', 'users', 'statuses'));
    }

    public function store(AdminStoreCompanyRequest $request)
    {
        $this->authorize('create', Company::class); // Authorize creation
        $validatedData = $request->validated();

        $companyData = $validatedData;
        // Slug is handled by HasSlug trait in the model on saving

        if ($request->hasFile('logo')) {
            $companyData['logo'] = $request->file('logo')->store('company_logos', 'public');
        }
        if ($request->hasFile('banner')) {
            $companyData['banner'] = $request->file('banner')->store('company_banners', 'public');
        }

        // Handle status-specific timestamps
        if ($request->input('status') === 'approved') {
            $companyData['approved_at'] = now();
        }

        // Consolidate social links
        $companyData['social_links'] = [
            'facebook' => $request->input('social_links.facebook'),
            'twitter' => $request->input('social_links.twitter'),
            'linkedin' => $request->input('social_links.linkedin'),
            'instagram' => $request->input('social_links.instagram'),
        ];
        $companyData['social_links'] = array_filter($companyData['social_links']); // Remove empty values

        // Boolean fields are handled by the FormRequest's prepareForValidation or directly from validated data if set up correctly
        $companyData['is_featured'] = $request->boolean('is_featured');
        $companyData['is_verified'] = $request->boolean('is_verified');
        $companyData['is_ecommerce'] = $request->boolean('is_ecommerce');

        Company::create($companyData);

        return redirect()->route('admin.businessdirectory.companies.index')
                         ->with('success', 'Company created successfully.');
    }

    public function show(Company $company)
    {
        $this->authorize('view', $company); // Authorize viewing this specific company
        $company->load('user', 'companyType', 'products', 'tenders'); // Eager load relations
        return view('businessdirectory::admin.companies.show', compact('company'));
    }

    public function edit(Company $company)
    {
        $this->authorize('update', $company); // Authorize updating this specific company
        $companyTypes = CompanyType::orderBy('name')->pluck('name', 'id');
        $users = User::orderBy('name')->pluck('name', 'id');
        $statuses = Company::getStatuses();
        return view('businessdirectory::admin.companies.edit', compact('company', 'companyTypes', 'users', 'statuses'));
    }

    public function update(AdminUpdateCompanyRequest $request, Company $company)
    {
        $this->authorize('update', $company); // Authorize updating this specific company
        $validatedData = $request->validated();

        $companyData = $validatedData;
        // The HasSlug trait in the Company model handles slug updates automatically if 'name' changes.

        if ($request->hasFile('logo')) {
            if ($company->logo) Storage::disk('public')->delete($company->logo);
            $companyData['logo'] = $request->file('logo')->store('company_logos', 'public');
        }
        // Ensure the form field name for banner is 'banner'
        if ($request->hasFile('banner')) {
            if ($company->banner) Storage::disk('public')->delete($company->banner);
            $companyData['banner'] = $request->file('banner')->store('company_banners', 'public');
        }

        // Handle status changes and timestamps
        if ($company->status !== $request->input('status')) {
            $companyData['approved_at'] = ($request->input('status') === 'approved') ? now() : null;
            $companyData['rejected_at'] = ($request->input('status') === 'rejected') ? now() : null;
            $companyData['rejection_reason'] = ($request->input('status') === 'rejected') ? $request->input('rejection_reason', $company->rejection_reason) : null;
            $companyData['suspended_at'] = ($request->input('status') === 'suspended') ? now() : null;
            $companyData['suspension_reason'] = ($request->input('status') === 'suspended') ? $request->input('suspension_reason', $company->suspension_reason) : null;
        } else {
            // If status hasn't changed, but reasons might have been submitted (e.g. editing a rejected company)
            $companyData['rejection_reason'] = ($request->input('status') === 'rejected') ? $request->input('rejection_reason', $company->rejection_reason) : null;
            $companyData['suspension_reason'] = ($request->input('status') === 'suspended') ? $request->input('suspension_reason', $company->suspension_reason) : null;
        }

        // Ensure boolean fields are correctly set
        $companyData['is_featured'] = $request->boolean('is_featured');
        $companyData['is_verified'] = $request->boolean('is_verified');
        $companyData['is_ecommerce'] = $request->boolean('is_ecommerce');

        // Consolidate social links
        $companyData['social_links'] = [
            'facebook' => $request->input('social_links.facebook'),
            'twitter' => $request->input('social_links.twitter'),
            'linkedin' => $request->input('social_links.linkedin'),
            'instagram' => $request->input('social_links.instagram'),
        ];
        $companyData['social_links'] = array_filter($companyData['social_links']);

        $company->update($companyData);


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

    public function destroy(Company $company)
    {
        $this->authorize('delete', $company); // Authorize deleting this specific company
        if ($company->logo) Storage::disk('public')->delete($company->logo);
        if ($company->banner) Storage::disk('public')->delete($company->banner);
        // Consider soft delete implications or related data (products, tenders)
        $company->delete(); // This will soft delete if SoftDeletes trait is used

        return redirect()->route('admin.businessdirectory.companies.index')
                         ->with('success', 'Company deleted successfully.');
    }

    public function approve(Company $company)
    {
        $this->authorize('update', $company); // Or a more specific 'approve' policy method
        $company->update([
            'status' => 'approved',
            'approved_at' => now(),
            'rejected_at' => null,
            'rejection_reason' => null,
            'suspended_at' => null,
            'suspension_reason' => null,
        ]);
        // Optionally, send notification to user
        return redirect()->back()->with('success', 'Company approved successfully.');
    }

    public function reject(Request $request, Company $company)
    {
        $this->authorize('update', $company); // Or a more specific 'reject' policy method
        $request->validate(['rejection_reason' => 'required|string|max:1000']);
        $company->update([
            'status' => 'rejected',
            'rejected_at' => now(),
            'rejection_reason' => $request->rejection_reason,
            'approved_at' => null,
            'suspended_at' => null,
            'suspension_reason' => null,
        ]);
        // Optionally, send notification to user
        return redirect()->back()->with('success', 'Company rejected successfully.');
    }

    public function suspend(Request $request, Company $company)
    {
        $this->authorize('update', $company); // Or a more specific 'suspend' policy method
        $request->validate(['suspension_reason' => 'required|string|max:1000']);
        $company->update([
            'status' => 'suspended',
            'suspended_at' => now(),
            'suspension_reason' => $request->suspension_reason,
            // 'approved_at' => null, // Keep approved_at if it was previously approved
        ]);
        // Optionally, send notification to user
        return redirect()->back()->with('success', 'Company suspended successfully.');
    }

    public function reactivate(Company $company)
    {
        $this->authorize('update', $company); // Or a more specific 'reactivate' policy method
        // Reactivate typically means setting back to 'approved' or 'pending'
        // depending on your workflow. Let's assume 'approved'.
        $company->update([
            'status' => 'approved', // Or 'pending' if it needs re-review
            'approved_at' => $company->approved_at ?? now(), // Keep original or set new
            'rejected_at' => null,
            'rejection_reason' => null,
            'suspended_at' => null,
            'suspension_reason' => null,
        ]);
        return redirect()->back()->with('success', 'Company reactivated successfully.');
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\CompanyProjectController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\BusinessDirectory\Entities\CompanyProject;
use Modules\BusinessDirectory\Entities\Company; // Keep if needed for create/edit forms

class CompanyProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', CompanyProject::class); // Assuming you have a policy

        $query = CompanyProject::with('company')->latest();

        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where('name', 'like', "%{$searchTerm}%")
                  ->orWhereHas('company', function ($q) use ($searchTerm) {
                      $q->where('name', 'like', "%{$searchTerm}%");
                  });
        }

        if ($request->filled('status_filter')) {
            $query->where('status', $request->status_filter);
        }

        $projects = $query->paginate(15)->withQueryString();
        $project_statuses_filter = CompanyProject::getStatuses();

        return view('businessdirectory::admin.projects.index', compact('projects', 'project_statuses_filter'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        $companies = Company::where('status', 'approved')->orderBy('name')->pluck('name', 'id');
        $project_statuses = CompanyProject::getStatuses();
        return view('businessdirectory::admin.projects.create', compact('companies', 'project_statuses'));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        $request->validate([
            'company_id' => 'required|exists:bd_companies,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'budget' => 'nullable|numeric|min:0',
            'currency' => 'nullable|string|max:10',
            'status' => 'required|in:planning,in_progress,completed,on_hold,cancelled,draft',
            'client_company_id' => 'nullable|exists:bd_companies,id',
        ]);

        CompanyProject::create($request->all());

        return redirect()->route('admin.businessdirectory.projects.index')
            ->with('success', 'Project created successfully.');
    }

    /**
     * Show the specified resource (tasks for this project).
     * @param CompanyProject $project
     * @return Renderable
     */
    public function show(CompanyProject $project)
    {
        $project->load('company', 'tasks.assignee'); // Eager load tasks and their assignees
        return view('businessdirectory::admin.projects.show', compact('project'));
    }

    /**
     * Show the form for editing the specified resource.
     * @param CompanyProject $project
     * @return Renderable
     */
    public function edit(CompanyProject $project)
    {
        $companies = Company::where('status', 'approved')->orderBy('name')->pluck('name', 'id');
        $project_statuses = CompanyProject::getStatuses();
        return view('businessdirectory::admin.projects.edit', compact('project', 'companies', 'project_statuses'));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param CompanyProject $project
     * @return Renderable
     */
    public function update(Request $request, CompanyProject $project)
    {
        $request->validate([
            'company_id' => 'required|exists:bd_companies,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
            'budget' => 'nullable|numeric|min:0',
            'currency' => 'nullable|string|max:10',
            'status' => 'required|in:planning,in_progress,completed,on_hold,cancelled,draft',
            'client_company_id' => 'nullable|exists:bd_companies,id',
        ]);

        $project->update($request->all());

        return redirect()->route('admin.businessdirectory.projects.index')
            ->with('success', 'Project updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     * @param CompanyProject $project
     * @return Renderable
     */
    public function destroy(CompanyProject $project)
    {
        try {
            // Consider deleting related tasks or handling them based on business logic
            $project->tasks()->delete(); // Example: delete related tasks
            // Add authorization check for deleting
            $this->authorize('delete', $project);
            $project->delete();
            return redirect()->route('admin.businessdirectory.projects.index')->with('success', 'Project and its tasks deleted successfully.');
        } catch (\Exception $e) {
            return redirect()->route('admin.businessdirectory.projects.index')->with('error', 'Failed to delete project: ' . $e->getMessage());
        }
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\CompanyTaskController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\BusinessDirectory\Entities\CompanyProject;
use Modules\BusinessDirectory\Entities\CompanyTask;
use App\Entities\User; // Assuming global User model

class CompanyTaskController extends Controller
{
    // Note: Admin task management is often done via the project's show page.
    // These methods provide direct CRUD if needed, but might be simplified.

    /**
     * Show the form for creating a new task for a project.
     * @param CompanyProject $project
     * @return Renderable
     */
    public function create(CompanyProject $project)
    {
        $assignees = User::orderBy('name')->pluck('name', 'id'); // Or filter by users related to the company
        $task_statuses = ['todo' => 'To Do', 'in_progress' => 'In Progress', 'review' => 'Review', 'completed' => 'Completed', 'blocked' => 'Blocked'];
        $priorities = ['low' => 'Low', 'medium' => 'Medium', 'high' => 'High', 'urgent' => 'Urgent'];
        return view('businessdirectory::admin.tasks.create', compact('project', 'assignees', 'task_statuses', 'priorities'));
    }

    /**
     * Store a newly created task in storage.
     * @param Request $request
     * @param CompanyProject $project
     * @return Renderable
     */
    public function store(Request $request, CompanyProject $project)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'assignee_user_id' => 'nullable|exists:users,id',
            'due_date' => 'nullable|date',
            'priority' => 'nullable|string|max:50',
            'status' => 'required|in:todo,in_progress,review,completed,blocked',
        ]);

        $taskData = $request->all();
        $taskData['project_id'] = $project->id;
        CompanyTask::create($taskData);

        return redirect()->route('admin.businessdirectory.projects.show', $project->id)
            ->with('success', 'Task created successfully.');
    }

    /**
     * Show the form for editing the specified task.
     * @param CompanyProject $project (passed for context, though task is route model bound)
     * @param CompanyTask $task
     * @return Renderable
     */
    public function edit(CompanyProject $project, CompanyTask $task)
    {
        if ($task->project_id !== $project->id) {
            abort(404); // Task does not belong to this project
        }
        $assignees = User::orderBy('name')->pluck('name', 'id');
        $task_statuses = ['todo' => 'To Do', 'in_progress' => 'In Progress', 'review' => 'Review', 'completed' => 'Completed', 'blocked' => 'Blocked'];
        $priorities = ['low' => 'Low', 'medium' => 'Medium', 'high' => 'High', 'urgent' => 'Urgent'];
        return view('businessdirectory::admin.tasks.edit', compact('project', 'task', 'assignees', 'task_statuses', 'priorities'));
    }

    /**
     * Update the specified task in storage.
     * @param Request $request
     * @param CompanyProject $project
     * @param CompanyTask $task
     * @return Renderable
     */
    public function update(Request $request, CompanyProject $project, CompanyTask $task)
    {
        if ($task->project_id !== $project->id) {
            abort(404);
        }
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'assignee_user_id' => 'nullable|exists:users,id',
            'due_date' => 'nullable|date',
            'priority' => 'nullable|string|max:50',
            'status' => 'required|in:todo,in_progress,review,completed,blocked',
        ]);

        $task->update($request->all());

        return redirect()->route('admin.businessdirectory.projects.show', $project->id)
            ->with('success', 'Task updated successfully.');
    }

    /**
     * Remove the specified task from storage.
     * @param CompanyProject $project
     * @param CompanyTask $task
     * @return Renderable
     */
    public function destroy(CompanyProject $project, CompanyTask $task)
    {
        if ($task->project_id !== $project->id) {
            return response()->json(['error' => 'Task does not belong to this project.'], 403);
        }
        try {
            $task->delete();
            // If request is AJAX, return JSON, otherwise redirect
            if (request()->ajax()) {
                return response()->json(['success' => 'Task deleted successfully.']);
            }
            return redirect()->route('admin.businessdirectory.projects.show', $project->id)
                             ->with('success', 'Task deleted successfully.');
        } catch (\Exception $e) {
            if (request()->ajax()) {
                return response()->json(['error' => 'Failed to delete task.'], 500);
            }
            return redirect()->route('admin.businessdirectory.projects.show', $project->id)
                             ->with('error', 'Failed to delete task.');
        }
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\CompanyTypeController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\BusinessDirectory\Entities\CompanyType;
use Modules\BusinessDirectory\Http\Requests\Admin\StoreCompanyTypeRequest;
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateCompanyTypeRequest;
use Illuminate\Support\Facades\Storage;

class CompanyTypeController extends Controller
{
    public function __construct()
    {
        // Assuming admin routes are protected. Policy authorization per method.
    }

    public function index(Request $request)
    {
        $this->authorize('viewAny', CompanyType::class);
        $query = CompanyType::query()->latest();

        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%");
        }

        $companyTypes = $query->paginate(15);
        return view('businessdirectory::admin.company_types.index', compact('companyTypes'));
    }

    public function create()
    {
        $this->authorize('create', CompanyType::class);
        return view('businessdirectory::admin.company_types.create');
    }

    public function store(StoreCompanyTypeRequest $request)
    {
        $this->authorize('create', CompanyType::class);
        $validatedData = $request->validated();

        if ($request->hasFile('icon')) {
            $validatedData['icon'] = $request->file('icon')->store('company_type_icons', 'public');
        }

        CompanyType::create($validatedData);

        return redirect()->route('admin.businessdirectory.company-types.index')
                         ->with('success', 'Company Type created successfully.');
    }

    public function edit(CompanyType $companyType)
    {
        $this->authorize('update', $companyType);
        return view('businessdirectory::admin.company_types.edit', compact('companyType'));
    }

    public function update(UpdateCompanyTypeRequest $request, CompanyType $companyType)
    {
        $this->authorize('update', $companyType);
        $validatedData = $request->validated();

        if ($request->hasFile('icon')) {
            if ($companyType->icon) {
                Storage::disk('public')->delete($companyType->icon);
            }
            $validatedData['icon'] = $request->file('icon')->store('company_type_icons', 'public');
        }

        $companyType->update($validatedData);

        return redirect()->route('admin.businessdirectory.company-types.index')
                         ->with('success', 'Company Type updated successfully.');
    }

    public function destroy(CompanyType $companyType)
    {
        $this->authorize('delete', $companyType);

        if ($companyType->companies()->count() > 0) {
            return redirect()->route('admin.businessdirectory.company-types.index')
                             ->with('error', 'Cannot delete company type. It is associated with existing companies.');
        }

        if ($companyType->icon) {
            Storage::disk('public')->delete($companyType->icon);
        }
        $companyType->delete();

        return redirect()->route('admin.businessdirectory.company-types.index')
                         ->with('success', 'Company Type deleted successfully.');
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\DashboardController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\BusinessDirectory\Entities\Company;
use Modules\BusinessDirectory\Entities\Tender;
use Modules\BusinessDirectory\Entities\Product;

class DashboardController extends Controller
{
    /**
     * Display the admin dashboard for the BusinessDirectory module.
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        $companyCount = Company::count();
        $activeTenderCount = Tender::where('status', 'open')->count(); // Example: only open tenders
        $productCount = Product::count();

        return view('businessdirectory::admin.dashboard', compact(
            'companyCount',
            'activeTenderCount',
            'productCount'
        ));
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\JobController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\BusinessDirectory\Entities\Job;
use Modules\BusinessDirectory\Entities\Company;
use Modules\BusinessDirectory\Entities\JobApplication;
use Modules\BusinessDirectory\Http\Requests\Admin\StoreJobRequest; // Keep if used
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateJobRequest; // Keep if used

class JobController extends Controller
{
    public function __construct()
    {
        // Policy authorization per method.
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Job::class);

        $query = Job::with('company')->latest();

        if ($request->filled('search_title')) {
            $query->where('title', 'like', '%' . $request->search_title . '%');
        }

        if ($request->filled('job_status_filter')) {
            $query->where('status', $request->job_status_filter);
        }
        // Add other filters like company_id if needed

        $jobs = $query->paginate(15)->withQueryString();
        $job_statuses_filter = Job::getStatuses();
        // $companies_filter = Company::orderBy('name')->pluck('name', 'id'); // If you add company filter

        return view('businessdirectory::admin.jobs.index', compact('jobs', 'job_statuses_filter' /*, 'companies_filter' */));
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        $this->authorize('create', Job::class);
        $companies = Company::where('status', 'approved')->pluck('name', 'id');
        $job_statuses = Job::getStatuses();
        $job_types = Job::getJobTypes();
        $categories = \Modules\BusinessDirectory\Entities\Category::orderBy('name')->pluck('name', 'id'); // Assuming you have categories for jobs
        return view('businessdirectory::admin.jobs.create', compact('companies', 'job_statuses', 'job_types', 'categories'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreJobRequest $request)
    {
        $this->authorize('create', Job::class);
        $validatedData = $request->validated();
        // Slug is handled by HasSlug trait in the model

        // Admin can assign user_id, otherwise default to company owner or logged-in admin
        if (empty($validatedData['user_id']) && !empty($validatedData['company_id'])) {
            $company = Company::find($validatedData['company_id']);
            $validatedData['user_id'] = $company->user_id ?? auth()->id();
        } elseif (empty($validatedData['user_id'])) {
            $validatedData['user_id'] = auth()->id();
        }

        Job::create($validatedData);

        return redirect()->route('admin.businessdirectory.jobs.index')
            ->with('success', 'Job created successfully.');
    }

    /**
     * Show the specified resource.
     */
    public function show(Job $job)
    {
        $this->authorize('view', $job);
        $job->load('company', 'jobApplications.user');
        return view('businessdirectory::admin.jobs.show', compact('job'));
    }

    /**
     * Show the form for editing the specified resource.
     * @param Job $job
     */
    public function edit(Job $job)
    {
        $this->authorize('update', $job);
        $companies = Company::where('status', 'approved')->pluck('name', 'id');
        $job_statuses = Job::getStatuses();
        $job_types = Job::getJobTypes();
        $categories = \Modules\BusinessDirectory\Entities\Category::orderBy('name')->pluck('name', 'id');
        return view('businessdirectory::admin.jobs.edit', compact('job', 'companies', 'job_statuses', 'job_types', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateJobRequest $request, Job $job)
    {
        $this->authorize('update', $job);
        $validatedData = $request->validated();
        // Slug is handled by HasSlug trait if title changes

        $job->update($validatedData);

        return redirect()->route('admin.businessdirectory.jobs.index')
            ->with('success', 'Job updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Job $job)
    {
        $this->authorize('delete', $job);
        try {
            // Consider what happens to job applications.
            // If JobApplication model has a foreign key with onDelete('cascade'), they will be deleted.
            // Otherwise, you might want to delete them manually or prevent deletion if applications exist.
            // $job->jobApplications()->delete(); // Example

            $job->delete();
            return redirect()->route('admin.businessdirectory.jobs.index')->with('success', 'Job deleted successfully.');
        } catch (\Exception $e) {
            return redirect()->route('admin.businessdirectory.jobs.index')->with('error', 'Failed to delete job. It might have related data.');
        }
    }

    /**
     * Update the status of a job application.
     */
    public function updateApplicationStatus(Request $request, JobApplication $application)
    {
        $this->authorize('update', $application->job); // Admin can update applications for any job
        $request->validate(['status' => 'required|in:applied,shortlisted,interviewed,rejected,hired,withdrawn']);
        $application->update(['status' => $request->status]);
        return back()->with('success', 'Application status updated.');
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\OrderController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\BusinessDirectory\Entities\Order;
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateOrderRequest; // Keep if used

class OrderController extends Controller
{
    public function __construct()
    {
        // Policy authorization per method.
    }
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Order::class);
        $query = Order::with(['user', 'company'])->latest();

        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where('order_number', 'like', "%{$searchTerm}%")
                  ->orWhereHas('user', fn($q) => $q->where('name', 'like', "%{$searchTerm}%")->orWhere('email', 'like', "%{$searchTerm}%"))
                  ->orWhereHas('company', fn($q) => $q->where('name', 'like', "%{$searchTerm}%"));
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('payment_status')) {
            $query->where('payment_status', $request->payment_status);
        }

        $orders = $query->paginate(15)->withQueryString();

        // Use the static methods from the Order model if they exist, or config values
        $order_statuses = method_exists(Order::class, 'getStatuses') ? Order::getStatuses() : config('businessdirectory.order_statuses', ['pending' => 'Pending', 'processing' => 'Processing', 'shipped' => 'Shipped', 'delivered' => 'Delivered', 'completed' => 'Completed', 'cancelled' => 'Cancelled', 'refunded' => 'Refunded', 'payment_failed' => 'Payment Failed']);
        $payment_statuses = method_exists(Order::class, 'getPaymentStatuses') ? Order::getPaymentStatuses() : config('businessdirectory.payment_statuses', ['pending' => 'Pending', 'paid' => 'Paid', 'failed' => 'Failed', 'refunded' => 'Refunded']);

        return view('businessdirectory::admin.orders.index', compact('orders', 'order_statuses', 'payment_statuses'));
    }

    /**
     * Show the specified resource.
     * @param Order $order
     * @return Renderable
     */
    public function show(Order $order)
    {
        $this->authorize('view', $order);
        $order->load(['user', 'company', 'items.product']);
        return view('businessdirectory::admin.orders.show', compact('order'));
    }

    public function edit(Order $order)
    {
        $this->authorize('update', $order);
        // Load necessary data for the edit form (e.g., statuses)
        $order_statuses = Order::getStatuses();
        $payment_statuses = Order::getPaymentStatuses();
        return view('businessdirectory::admin.orders.edit', compact('order', 'order_statuses', 'payment_statuses'));
    }

    /**
     * Update the specified resource in storage. (e.g., order status, payment status)
     * @param Request $request
     * @param Order $order
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UpdateOrderRequest $request, Order $order)
    {
        $this->authorize('update', $order);
        $validatedData = $request->validated();

        $order->update($validatedData);

        // Notify user about order status change
        // OrderStatusUpdatedNotification::dispatch($order->user, $order);
        // if ($order->wasChanged('status') || $order->wasChanged('payment_status')) {
            // Send notification
        // }

        return back()->with('success', 'Order updated successfully.');
    }

    // No destroy method for orders usually, they are marked as cancelled/refunded.
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\ProductController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\BusinessDirectory\Entities\Company;
use Modules\BusinessDirectory\Entities\Product;
use Modules\BusinessDirectory\Http\Requests\Admin\StoreProductRequest;
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateProductRequest;
use Illuminate\Support\Facades\Storage;
// Assuming you might have Product Categories
// use Modules\BusinessDirectory\Entities\ProductCategory;

class ProductController extends Controller
{
    public function __construct()
    {
        // Policy authorization per method.
    }

    public function index(Request $request, Company $company)
    {
        $this->authorize('viewAny', [Product::class, $company]);
        $query = $company->products()->latest();

        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%")
                  ->orWhere('sku', 'like', "%{$request->search}%");
        }

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

        $products = $query->paginate(15);
        $statuses = Product::getStatuses(); // Assuming Product model has getStatuses()

        return view('businessdirectory::admin.products.index', compact('company', 'products', 'statuses'));
    }

    public function create(Company $company)
    {
        $this->authorize('create', [Product::class, $company]);
        $statuses = Product::getStatuses();
        // $categories = ProductCategory::orderBy('name')->pluck('name', 'id'); // If you have categories
        return view('businessdirectory::admin.products.create', compact('company', 'statuses' /*, 'categories'*/));
    }

    public function store(StoreProductRequest $request, Company $company)
    {
        $this->authorize('create', [Product::class, $company]);
        $validatedData = $request->validated();

        $validatedData['company_id'] = $company->id;
        // Admin might set the user_id or it defaults to company owner
        $validatedData['user_id'] = $validatedData['user_id'] ?? $company->user_id;

        if ($request->hasFile('featured_image')) {
            $validatedData['featured_image'] = $request->file('featured_image')->store('product_images', 'public');
        }

        // Handle gallery images if your form supports multiple uploads
        if ($request->hasFile('gallery_images')) {
            $galleryPaths = [];
            foreach ($request->file('gallery_images') as $file) {
                $galleryPaths[] = $file->store('product_gallery', 'public');
            }
            $validatedData['gallery_images'] = $galleryPaths; // Assuming 'gallery_images' is a JSON column
        }

        Product::create($validatedData);

        return redirect()->route('admin.businessdirectory.companies.products.index', $company->id)
                         ->with('success', 'Product created successfully.');
    }

    public function edit(Company $company, Product $product)
    {
        $this->authorize('update', $product);
        $statuses = Product::getStatuses();
        // $categories = ProductCategory::orderBy('name')->pluck('name', 'id');
        return view('businessdirectory::admin.products.edit', compact('company', 'product', 'statuses' /*, 'categories'*/));
    }

    public function update(UpdateProductRequest $request, Company $company, Product $product)
    {
        $this->authorize('update', $product);
        $validatedData = $request->validated();

        if ($request->hasFile('featured_image')) {
            if ($product->featured_image) {
                Storage::disk('public')->delete($product->featured_image);
            }
            $validatedData['featured_image'] = $request->file('featured_image')->store('product_images', 'public');
        }

        // Handle gallery image updates (more complex: add new, remove old)
        // For simplicity, this example just replaces if new ones are uploaded.
        // A more robust solution would handle individual image additions/deletions.
        if ($request->hasFile('gallery_images')) {
            // Delete old gallery images if necessary
            if (is_array($product->gallery_images)) {
                foreach ($product->gallery_images as $oldImage) {
                    Storage::disk('public')->delete($oldImage);
                }
            }
            $galleryPaths = [];
            foreach ($request->file('gallery_images') as $file) {
                $galleryPaths[] = $file->store('product_gallery', 'public');
            }
            $validatedData['gallery_images'] = $galleryPaths;
        } elseif ($request->boolean('remove_gallery_images')) { // Example: a checkbox to clear gallery
             if (is_array($product->gallery_images)) {
                foreach ($product->gallery_images as $oldImage) {
                    Storage::disk('public')->delete($oldImage);
                }
            }
            $validatedData['gallery_images'] = null;
        }


        $product->update($validatedData);

        return redirect()->route('admin.businessdirectory.companies.products.index', $company->id)
                         ->with('success', 'Product updated successfully.');
    }

    public function destroy(Company $company, Product $product)
    {
        $this->authorize('delete', $product);

        if ($product->featured_image) {
            Storage::disk('public')->delete($product->featured_image);
        }
        if (is_array($product->gallery_images)) {
            foreach ($product->gallery_images as $galleryImage) {
                Storage::disk('public')->delete($galleryImage);
            }
        }
        // Consider if orders are associated with this product before deleting.
        $product->delete();

        return redirect()->route('admin.businessdirectory.companies.products.index', $company->id)
                         ->with('success', 'Product deleted successfully.');
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\ReviewController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\BusinessDirectory\Entities\Review;

class ReviewController extends Controller
{
    public function __construct()
    {
        // Policy authorization per method.
    }
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', Review::class);
        $query = Review::with(['company', 'user'])->latest();

        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where('title', 'like', "%{$searchTerm}%")
                  ->orWhere('comment', 'like', "%{$searchTerm}%")
                  ->orWhereHas('company', fn($q) => $q->where('name', 'like', "%{$searchTerm}%"))
                  ->orWhereHas('user', fn($q) => $q->where('name', 'like', "%{$searchTerm}%"));
        }

        if ($request->filled('status_filter')) {
            $query->where('is_approved', $request->status_filter === '1'); // '1' for approved, '0' for pending
        }

        $reviews = $query->paginate(15)->withQueryString();
        // $statuses_filter = ['1' => 'Approved', '0' => 'Pending']; // For the filter dropdown

        return view('businessdirectory::admin.reviews.index', compact('reviews' /*, 'statuses_filter'*/));
    }

    /**
     * Show the specified resource.
     * @param Review $review
     * @return Renderable
     */
    public function show(Review $review)
    {
        $this->authorize('view', $review);
        $review->load(['company', 'user']);
        return view('businessdirectory::admin.reviews.show', compact('review'));
    }

    /**
     * Update the specified resource's approval status in storage.
     * @param Request $request
     * @param Review $review
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updateStatus(Request $request, Review $review)
    {
        $this->authorize('updateStatus', $review); // Or 'update' if admin role handles this via before()
        $request->validate([
            'is_approved' => 'required|boolean',
        ]);

        $review->is_approved = $request->is_approved;
        $review->save();

        // Notify user if needed
        // ReviewStatusChangedNotification::dispatch($review->user, $review);

        return redirect()->back()->with('success', 'Review status updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     * @param Review $review
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Review $review)
    {
        $this->authorize('delete', $review);
        try {
            $review->delete();
            return redirect()->route('admin.businessdirectory.reviews.index')->with('success', 'Review deleted successfully.');
        } catch (\Exception $e) {
            return redirect()->route('admin.businessdirectory.reviews.index')->with('error', 'Failed to delete review.');
        }
    }
}


--- File: D:\projects\digitalvocano\Modules\BusinessDirectory\Http\Controllers\Admin\TenderController.php ---
<?php

namespace Modules\BusinessDirectory\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\BusinessDirectory\Entities\Company;
use Modules\BusinessDirectory\Entities\Tender;
use Modules\BusinessDirectory\Entities\Bid; // Import Bid model
use Modules\BusinessDirectory\Http\Requests\Admin\StoreTenderRequest;
use Modules\BusinessDirectory\Http\Requests\Admin\UpdateTenderRequest;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
// use Modules\BusinessDirectory\Entities\CompanyType; // Not directly used in this controller
// use Modules\BusinessDirectory\Entities\Product; // Not directly used in this controller

class TenderController extends Controller
{
    public function __construct()
    {
        // Policy authorization per method.
    }

    public function index(Request $request)
    {
        $this->authorize('viewAny', Tender::class);
        $query = Tender::with('company')->withCount('bids')->orderBy('created_at', 'desc');

        if ($request->filled('search')) {
            $searchTerm = $request->input('search');
            $query->where(function ($q) use ($searchTerm) {
                $q->where('title', 'like', "%{$searchTerm}%")
                  ->orWhere('description', 'like', "%{$searchTerm}%")
                  ->orWhereHas('company', function ($companyQuery) use ($searchTerm) {
                      $companyQuery->where('name', 'like', "%{$searchTerm}%");
                  });
            });
        }

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }
        
        if ($request->filled('company_id')) {
            $query->where('company_id', $request->company_id);
        }

        $tenders = $query->paginate(15)->withQueryString(); // Added withQueryString
        $statuses = Tender::getStatuses(); // Assuming Tender model has getStatuses()
        $companies = Company::orderBy('name')->pluck('name', 'id'); // For the filter dropdown

        return view('businessdirectory::admin.tenders.index', compact('tenders', 'statuses', 'companies'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $this->authorize('create', Tender::class);
        $tender = new Tender(); // For form model binding
        $companies = Company::orderBy('name')->pluck('name', 'id');
        $statuses = Tender::getStatuses();
        return view('businessdirectory::admin.tenders.create', compact('tender', 'companies', 'statuses'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreTenderRequest $request)
    {
        $this->authorize('create', Tender::class);
        $validatedData = $request->validated();
        // Slug is handled by HasSlug trait in the model

        Tender::create($validatedData);
        return redirect()->route('admin.businessdirectory.tenders.index')
                         ->with('success', 'Tender created successfully.');
    }

    public function show(Tender $tender)
    {
        $this->authorize('view', $tender);
        // Typically, for admin, edit is more common than show.
        // You might want to load bids here or redirect to edit.
        // For now, redirecting to edit or showing a simple view.
        // Let's assume we want to show bids on the show page for admin
        return $this->showBids($tender);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Tender $tender)
    {
        $this->authorize('update', $tender);
        $companies = Company::orderBy('name')->pluck('name', 'id');
        $statuses = Tender::getStatuses();
        return view('businessdirectory::admin.tenders.edit', compact('tender', 'companies', 'statuses'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateTenderRequest $request, Tender $tender)
    {
        $this->authorize('update', $tender);
        $validatedData = $request->validated();
        // Slug is handled by HasSlug trait if title changes

        $tender->update($validatedData);
        return redirect()->route('admin.businessdirectory.tenders.index')
                         ->with('success', 'Tender updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Tender $tender)
    {
        $this->authorize('delete', $tender);
        // Consider what happens to bids associated with this tender.
        // By default, if bids have a foreign key with onDelete('cascade'), they will be deleted.
        $tender->delete();
        return redirect()->route('admin.businessdirectory.tenders.index')
                         ->with('success', 'Tender deleted successfully.');
    }

    /**
     * Display the bids for a specific tender.
     */
    public function showBids(Tender $tender)
    {
        $this->authorize('view', $tender); // Or a specific 'viewBids' permission
        $tender->load('company'); // Ensure company is loaded
        $bids = $tender->bids()
                       ->with(['bidderCompany.owner', 'bidderUser']) // Eager load bidderCompany, its owner, and bidderUser
                       ->orderBy('created_at', 'desc')
                       ->paginate(10);

        return view('businessdirectory::admin.tenders.show_bids', compact('tender', 'bids'));
    }

    /**
     * Toggle the flagged status of a bid.
     */
    public function toggleBidFlag(Bid $bid)
    {
        $this->authorize('update', $bid->tender); // Admin can update bids related to a tender
        $bid->update(['is_flagged' => !$bid->is_flagged]);

        $message = $bid->is_flagged ? 'Bid has been flagged for review.' : 'Bid has been unflagged.';

        return redirect()->back()->with('success', $message);
    }
}


