<?php
class SettingController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $cid = Auth::user()['company_id'];
        $company = $this->db->fetch("SELECT * FROM companies WHERE id=?", [$cid]);
        $settings = [];
        $rows = $this->db->fetchAll("SELECT setting_key, setting_value FROM settings WHERE company_id=?", [$cid]);
        foreach ($rows as $r) $settings[$r['setting_key']] = $r['setting_value'];
        require 'app/views/settings/index.php';
    }

    public function update() {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        // Update company info
        $this->db->update('companies', [
            'name' => $_POST['company_name'] ?? '', 'email' => $_POST['company_email'] ?? '',
            'phone' => $_POST['company_phone'] ?? '', 'address' => $_POST['company_address'] ?? '',
            'city' => $_POST['company_city'] ?? '', 'state' => $_POST['company_state'] ?? '',
            'zip' => $_POST['company_zip'] ?? '', 'website' => $_POST['company_website'] ?? '',
        ], 'id = ?', [$cid]);
        // Update settings
        $keys = ['late_fee_amount','late_fee_days','late_fee_type','default_lease_term','maintenance_auto_assign',
                 'email_notifications','sms_notifications','payment_gateway','stripe_key','stripe_secret',
                 'plaid_client_id','plaid_secret','timezone','date_format','currency'];
        foreach ($keys as $k) {
            if (isset($_POST[$k])) setSetting($k, $_POST[$k]);
        }
        flash('success', 'Settings updated.'); redirect('?page=settings');
    }
}
