<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\AttendanceSetting;
use App\Models\AuditLog;
use App\Models\BrandingSetting;
use App\Models\CommunicationSetting;
use App\Models\DocumentType;
use App\Models\HrSetting;
use App\Models\OperationalSetting;
use App\Models\PayrollSetting;
use App\Models\RenewalSetting;
use App\Models\TenantProfile;
use Illuminate\Http\Request;

class TenantSettingsHubController extends Controller
{
    public function overview()
    {
        return view('tenant.settings.index');
    }

    public function companyProfile()
    {
        $tenant = auth()->user()->tenant;
        $profile = TenantProfile::firstOrCreate(['tenant_id' => $tenant->id]);

        return view('tenant.settings.company.profile', compact('tenant', 'profile'));
    }

    public function updateCompanyProfile(Request $request)
    {
        $tenant = auth()->user()->tenant;
        $profile = TenantProfile::firstOrCreate(['tenant_id' => $tenant->id]);

        $tenant->update($request->only(['company_name', 'legal_name', 'email', 'mobile', 'emirate', 'trn', 'trade_license_number']));
        $profile->update($request->only([
            'trade_name', 'business_type', 'licensing_authority', 'license_activity', 'establishment_number',
            'immigration_establishment_number', 'mohre_establishment_number', 'icp_reference', 'gdrfa_reference',
            'landline', 'whatsapp_number', 'website', 'city', 'area', 'building_name', 'office_number', 'street', 'po_box', 'makani_number',
        ]));

        AuditLog::record('settings', 'company_profile.updated', $tenant);

        return back()->with('status', 'Company Profile and Legal details updated successfully.');
    }

    public function documentTypes()
    {
        $tenantId = auth()->user()->tenant_id;
        $documentTypes = DocumentType::where('tenant_id', $tenantId)->get();

        return view('tenant.settings.documents.index', compact('documentTypes'));
    }

    public function renewals()
    {
        $tenantId = auth()->user()->tenant_id;
        $renewalSetting = RenewalSetting::firstOrCreate(['tenant_id' => $tenantId]);

        return view('tenant.settings.renewals.index', compact('renewalSetting'));
    }

    public function communication()
    {
        $tenantId = auth()->user()->tenant_id;
        $commSetting = CommunicationSetting::firstOrCreate(['tenant_id' => $tenantId]);

        return view('tenant.settings.communication.index', compact('commSetting'));
    }

    public function updateCommunication(Request $request)
    {
        $tenantId = auth()->user()->tenant_id;
        $commSetting = CommunicationSetting::firstOrCreate(['tenant_id' => $tenantId]);

        $commSetting->update([
            'whatsapp_number' => $request->whatsapp_number,
            'whatsapp_provider' => $request->whatsapp_provider,
            'email_from_name' => $request->email_from_name,
            'email_from_address' => $request->email_from_address,
            'smtp_host' => $request->smtp_host,
            'smtp_port' => $request->smtp_port ?? 587,
            'smtp_username' => $request->smtp_username,
        ]);

        return back()->with('status', 'Communication SMTP and WhatsApp settings updated.');
    }

    public function branding()
    {
        $tenant = auth()->user()->tenant;
        $branding = BrandingSetting::firstOrCreate(['tenant_id' => $tenant->id]);
        $hasWhiteLabel = true; // Entitlement check

        return view('tenant.settings.branding.index', compact('tenant', 'branding', 'hasWhiteLabel'));
    }

    public function operations()
    {
        $tenantId = auth()->user()->tenant_id;
        $ops = OperationalSetting::firstOrCreate(['tenant_id' => $tenantId]);

        return view('tenant.settings.operations.index', compact('ops'));
    }

    public function hr()
    {
        $tenantId = auth()->user()->tenant_id;
        $hr = HrSetting::firstOrCreate(['tenant_id' => $tenantId], ['settings' => []]);
        $attendance = AttendanceSetting::firstOrCreate(['tenant_id' => $tenantId], ['settings' => []]);
        $payroll = PayrollSetting::firstOrCreate(['tenant_id' => $tenantId], ['settings' => []]);

        return view('tenant.settings.hr.index', compact('hr', 'attendance', 'payroll'));
    }

    public function updateHr(Request $request)
    {
        $data = $request->validate([
            'probation_days' => ['required', 'integer', 'min:0', 'max:365'],
            'document_alert_days' => ['required', 'integer', 'min:1', 'max:365'],
            'week_starts_on' => ['required', 'in:monday,sunday'],
            'allow_web_punch' => ['nullable', 'boolean'],
            'correction_requires_approval' => ['nullable', 'boolean'],
            'minimum_overtime_minutes' => ['required', 'integer', 'min:0', 'max:240'],
            'currency' => ['required', 'in:AED'],
            'salary_payment_day' => ['required', 'integer', 'min:1', 'max:31'],
            'payroll_day_basis' => ['required', 'in:calendar_days,working_days,fixed_30'],
        ]);
        $tenantId = $request->user()->tenant_id;
        $hr = HrSetting::updateOrCreate(['tenant_id' => $tenantId], ['settings' => [
            'probation_days' => $data['probation_days'],
            'document_alert_days' => $data['document_alert_days'],
        ]]);
        AttendanceSetting::updateOrCreate(['tenant_id' => $tenantId], ['settings' => [
            'week_starts_on' => $data['week_starts_on'],
            'allow_web_punch' => $request->boolean('allow_web_punch'),
            'correction_requires_approval' => $request->boolean('correction_requires_approval'),
            'minimum_overtime_minutes' => $data['minimum_overtime_minutes'],
        ]]);
        PayrollSetting::updateOrCreate(['tenant_id' => $tenantId], ['settings' => [
            'currency' => $data['currency'],
            'salary_payment_day' => $data['salary_payment_day'],
            'payroll_day_basis' => $data['payroll_day_basis'],
        ]]);
        AuditLog::record('settings', 'hr_settings.updated', $hr, null, ['groups' => ['hr', 'attendance', 'payroll']], $request->user());

        return back()->with('status', 'HR, attendance and payroll settings updated.');
    }

    public function searchSettings(Request $request)
    {
        $query = strtolower($request->query('q', ''));

        return redirect()->route('app.settings.company.profile')->with('status', 'Settings Search results for: '.$query);
    }
}
