<?php
class SettingsController extends Controller
{
    public function index():void{Auth::requireRole(['owner','admin']);$settings=[];foreach(Database::connection()->query('SELECT setting_key,setting_value FROM system_settings')->fetchAll() as$r)$settings[$r['setting_key']]=$r['setting_value'];$this->view('settings/index',compact('settings'));}
    public function logo():void{Auth::requireLogin();$relative=setting('company_logo','');$path=$relative?base_path($relative):'';if(!$path||!is_file($path)){http_response_code(404);exit;}header('Content-Type: '.(mime_content_type($path)?:'image/png'));header('Content-Length: '.filesize($path));readfile($path);exit;}
    public function update():void{Auth::requireRole(['owner','admin']);Csrf::verify();$allowed=['company_name','company_address','company_phone','company_email','company_mc','company_dot','invoice_payment_instructions','invoice_terms','currency_symbol','tracking_interval_seconds','seo_title','seo_description'];$s=Database::connection()->prepare('INSERT INTO system_settings (setting_key,setting_value,updated_by) VALUES (?,?,?) ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value),updated_by=VALUES(updated_by)');foreach($allowed as$key)$s->execute([$key,trim((string)($_POST[$key]??'')),Auth::user()['id']]);if(!empty($_FILES['company_logo']['tmp_name'])&&($_FILES['company_logo']['error']??UPLOAD_ERR_NO_FILE)===UPLOAD_ERR_OK){$f=$_FILES['company_logo'];$ext=strtolower(pathinfo($f['name'],PATHINFO_EXTENSION));if(in_array($ext,['png','jpg','jpeg','webp'],true)){$folder=storage_path('uploads/branding');if(!is_dir($folder))mkdir($folder,0755,true);$name='logo.'.$ext;$target=$folder.DIRECTORY_SEPARATOR.$name;move_uploaded_file($f['tmp_name'],$target);$s->execute(['company_logo',str_replace(base_path().DIRECTORY_SEPARATOR,'',$target),Auth::user()['id']]);}}$this->flash('success','Company and document settings updated.');$this->redirect('/settings');}
}
