<?php

namespace App\Controllers;

use App\Models\OrganizationPrivacySettingModel;

class PrivacySettings extends BaseController
{
    public function index()
    {
        if ($redirect = $this->requireOrganizationContext()) {
            return $redirect;
        }

        $organizationId = (int) $this->currentOrganizationId();
        $model = new OrganizationPrivacySettingModel();

        return view('privacy_settings/index', [
            'title' => lang('Backoffice.menuPrivacySettings'),
            'active' => 'privacy_settings',
            'canManage' => $this->canManageOrganization(),
            'settings' => $model->forOrganization($organizationId),
        ]);
    }

    public function update()
    {
        if ($redirect = $this->requireOrganizationContext()) {
            return $redirect;
        }

        if (! $this->canManageOrganization()) {
            return redirect()->to(site_url('privacy-settings'))->with('error', lang('Backoffice.privacySettingsForbidden'));
        }

        $organizationId = (int) $this->currentOrganizationId();
        $model = new OrganizationPrivacySettingModel();
        $current = $model->forOrganization($organizationId);

        $payload = [
            'organization_id' => $organizationId,
            'visibility_mode' => (string) $this->request->getPost('visibility_mode'),
            'show_public_reference' => $this->request->getPost('show_public_reference') ? 1 : 0,
            'show_organization_name' => $this->request->getPost('show_organization_name') ? 1 : 0,
            'show_facility_name' => $this->request->getPost('show_facility_name') ? 1 : 0,
            'show_energy' => $this->request->getPost('show_energy') ? 1 : 0,
            'show_period' => $this->request->getPost('show_period') ? 1 : 0,
            'show_blockchain' => $this->request->getPost('show_blockchain') ? 1 : 0,
            'show_hashes' => $this->request->getPost('show_hashes') ? 1 : 0,
            'show_rule_name' => $this->request->getPost('show_rule_name') ? 1 : 0,
        ];

        if (! in_array($payload['visibility_mode'], ['private', 'standard', 'transparent'], true)) {
            return redirect()->back()->withInput()->with('error', lang('Backoffice.privacySettingsModeInvalid'));
        }

        if ($current['visibility_mode'] === 'private') {
            $payload['show_public_reference'] = 0;
            $payload['show_organization_name'] = 0;
            $payload['show_facility_name'] = 0;
            $payload['show_energy'] = 0;
            $payload['show_period'] = 0;
            $payload['show_blockchain'] = 0;
            $payload['show_rule_name'] = 0;
        }

        $existingId = $current['id'] ?? null;
        if ($existingId) {
            $model->update($existingId, $payload);
        } else {
            $model->insert($payload);
        }

        return redirect()->to(site_url('privacy-settings'))->with('success', lang('Backoffice.privacySettingsSaved'));
    }
}
