<?php
namespace App\Controllers\Settings;

use App\Controllers\BaseController;
use Config\Database;

class VatController extends BaseController
{
    public function index()
    {
        $db = Database::connect();
        $settings = [];
        try {
            $settings = $db->table('settings_vat')->orderBy('id', 'DESC')->get()->getRowArray();
        } catch (\Throwable $e) { $settings = []; }

        return view('settings/vat', [
            'title' => lang('App.vat_settings'),
            'settings' => $settings,
        ]);
    }

    public function store()
    {
        $db = Database::connect();
        $req = $this->request;

        $schoolName = trim((string) ($req->getPost('school_name') ?? ''));
        $vatNumber = trim((string) ($req->getPost('vat_number') ?? ''));
        $vatRatePercent = (float) ($req->getPost('vat_rate') ?? 15);
        $now = date('Y-m-d H:i:s');

        $data = [
            'school_name' => $schoolName,
            'vat_number' => $vatNumber,
            'vat_rate' => $vatRatePercent, // stored as percent (e.g., 15)
            'updated_at' => $now,
        ];

        // Handle logo upload if provided
        $logoFile = $req->getFile('logo');
        if ($logoFile && $logoFile->isValid() && ! $logoFile->hasMoved()) {
            $targetDir = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . 'logos';
            if (! is_dir($targetDir)) { @mkdir($targetDir, 0777, true); }
            $newName = 'school_logo_' . time() . '.' . $logoFile->getExtension();
            try {
                $logoFile->move($targetDir, $newName);
                $data['logo_path'] = 'uploads/logos/' . $newName; // relative to WRITEPATH
            } catch (\Throwable $e) {
                // keep going without blocking save
            }
        }

        try {
            $existing = $db->table('settings_vat')->orderBy('id', 'DESC')->get()->getRowArray();
            if ($existing) {
                $db->table('settings_vat')->where('id', (int) $existing['id'])->update($data);
            } else {
                $data['created_at'] = $now;
                $db->table('settings_vat')->insert($data);
            }
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'Could not save settings. Please try again.').withInput();
        }

        return redirect()->to('/settings/vat')->with('success', 'Settings saved successfully. VAT and QR will apply to new receipts.');
    }
}