<?php

namespace App\Controllers\Owner;

use App\Controllers\BaseController;
use App\Models\CompanySettingModel;
use App\Models\SystemSettingModel;
use App\Services\MonthlyPoScheduler;

class Setting extends BaseController
{
    protected $company;
    protected $system;

    public function __construct()
    {
        helper(['form','url']);
        if(class_exists(\App\Models\CompanySettingModel::class)){
            $this->company = new CompanySettingModel();
        }
        if(class_exists(\App\Models\SystemSettingModel::class)){
            $this->system = new SystemSettingModel();
        }
    }

    public function index()
    {
        $company = [];
        if($this->company){
            $company = $this->company->first();
        }
        $system = [];
        if($this->system){
            $system = $this->system->findAll();
        }
        return view('owner/setting/index', [
            'title'   => 'Pengaturan',
            'company' => $company,
            'system'  => $system
        ]);
    }

    public function update()
    {
        if(!$this->company){
            return redirect()->back()->with('error','CompanySettingModel tidak ditemukan.');
        }

        // Ambil data yang ada
        $setting = $this->company->first();

        if (! $this->validate(['company_name' => 'required|max_length[150]', 'email' => 'permit_empty|valid_email', 'monthly_po_limit' => 'required|integer|greater_than_equal_to[0]'])) {
            return redirect()->back()->withInput()->with('error', implode(' ', $this->validator->getErrors()));
        }
        $data = [
            'company_name' => trim((string) $this->request->getPost('company_name')), 'owner_name' => $this->request->getPost('owner_name'),
            'email' => $this->request->getPost('email'), 'phone' => $this->request->getPost('phone'), 'address' => $this->request->getPost('address'),
            'npwp' => $this->request->getPost('npwp'), 'rekening_bank' => $this->request->getPost('rekening_bank'),
            'monthly_po_limit' => (int) $this->request->getPost('monthly_po_limit'),
        ];

        foreach (['logo_url' => 'logo', 'favicon_url' => 'favicon'] as $field => $input) {
            $file = $this->request->getFile($input);
            if (! $file || $file->getError() === UPLOAD_ERR_NO_FILE) {
                continue;
            }

            if (! $file->isValid() || $file->hasMoved()) {
                return redirect()->back()->withInput()->with('error', 'File ' . $input . ' tidak dapat diproses.');
            }

            $extension = strtolower($file->getExtension());
            if ($file->getSize() > 2 * 1024 * 1024 || ! in_array($extension, ['png', 'jpg', 'jpeg', 'webp', 'ico'], true)) {
                return redirect()->back()->withInput()->with('error', 'Logo/favikon harus berupa PNG, JPG, WEBP, atau ICO dengan ukuran maksimal 2 MB.');
            }

            $directory = FCPATH . 'uploads/company';
            if (! is_dir($directory) && ! mkdir($directory, 0775, true) && ! is_dir($directory)) {
                return redirect()->back()->withInput()->with('error', 'Folder penyimpanan identitas visual tidak dapat dibuat.');
            }

            try {
                $name = $input . '-' . $file->getRandomName();
                $file->move($directory, $name);
                $data[$field] = 'uploads/company/' . $name;
            } catch (\Throwable $e) {
                return redirect()->back()->withInput()->with('error', 'File ' . $input . ' gagal diunggah.');
            }
        }

        // Perubahan limit dan pemadatan ulang batch harus menjadi satu
        // transaksi agar jadwal tidak tertinggal dengan nilai limit baru.
        $db = \Config\Database::connect();
        $db->transBegin();
        try {
            $saved = $setting
                ? $this->company->update($setting['id_setting'], $data)
                : $this->company->insert($data) !== false;

            if (! $saved) {
                $errors = implode(' ', $this->company->errors());
                throw new \RuntimeException($errors ?: 'Pengaturan gagal disimpan.');
            }

            (new MonthlyPoScheduler($db))->rebalance((int) $data['monthly_po_limit']);

            if ($db->transStatus() === false) {
                throw new \RuntimeException('Penyesuaian jadwal PO gagal disimpan.');
            }
            $db->transCommit();
        } catch (\Throwable $e) {
            $db->transRollback();

            return redirect()->back()->withInput()->with('error', $e->getMessage());
        }

        return redirect()
            ->to('/owner/setting')
            ->with('success', 'Pengaturan berhasil disimpan dan jadwal PO telah disesuaikan.');
    }

    /*
    |--------------------------------------------------------------------------
    | Target Profit
    |--------------------------------------------------------------------------
    */

    public function targetProfit()
    {
        return view(

            'owner/setting/target_profit',

            [

                'title'=>'Target Profit'

            ]

        );
    }

    /*
    |--------------------------------------------------------------------------
    | Backup Database
    |--------------------------------------------------------------------------
    */

    public function backup()
    {
        return redirect()

            ->back()

            ->with(

                'success',

                'Fitur backup akan ditambahkan.'

            );
    }

    /*
    |--------------------------------------------------------------------------
    | Restore Database
    |--------------------------------------------------------------------------
    */

    public function restore()
    {
        return redirect()

            ->back()

            ->with(

                'success',

                'Fitur restore akan ditambahkan.'

            );
    }

    /*
    |--------------------------------------------------------------------------
    | Activity Log
    |--------------------------------------------------------------------------
    */

    public function logs()
    {
        return view(

            'owner/setting/logs',

            [

                'title'=>'Activity Log'

            ]

        );
    }
}
