<?php
namespace App\Http\Controllers;
use App\Models as M;
use Illuminate\Http\Request;
class SettingsController extends Controller {
    public function company() {
        $this->need('settings.view');
        return view('settings.company', ['c' => M\Company::current()]);
    }
    public function companyUpdate(Request $r) {
        $this->need('settings.edit');
        $d = $r->validate(['name' => 'required|max:150', 'tagline' => 'nullable|max:150', 'address' => 'nullable|max:255', 'city' => 'nullable|max:80',
            'region' => 'nullable|max:80', 'country' => 'nullable|max:80', 'phone' => 'nullable|max:40', 'phone2' => 'nullable|max:40',
            'email' => 'nullable|email', 'website' => 'nullable|max:120', 'tin' => 'nullable|max:40', 'currency_code' => 'nullable|max:10',
            'currency_symbol' => 'nullable|max:10', 'invoice_terms' => 'nullable|max:2000', 'bank_details' => 'nullable|max:2000', 'logo' => 'nullable|file|max:2048']);
        $c = M\Company::current();
        if ($r->hasFile('logo')) $d['logo_path'] = $r->file('logo')->store('uploads', 'public');
        unset($d['logo']);
        $c->update($d);
        return back()->with('success', 'Company profile saved.');
    }
    public function prefs() {
        $this->need('settings.view');
        return view('settings.prefs', ['bands' => json_encode(M\Setting::get('payroll.paye_bands', null) ?? \App\Services\PayrollService::bands(), JSON_PRETTY_PRINT)]);
    }
    public function prefsUpdate(Request $r) {
        $this->need('settings.edit');
        $d = $r->validate(['payroll_ssnit_employee' => 'required|numeric|min:0', 'payroll_ssnit_employer' => 'required|numeric|min:0',
            'payroll_paye_bands' => 'required|json', 'sales_default_terms' => 'nullable|integer|min:0']);
        M\Setting::put('payroll.ssnit_employee', $d['payroll_ssnit_employee'], 'payroll', 'number', 'SSNIT employee %');
        M\Setting::put('payroll.ssnit_employer', $d['payroll_ssnit_employer'], 'payroll', 'number', 'SSNIT employer %');
        M\Setting::put('payroll.paye_bands', json_decode($d['payroll_paye_bands'], true), 'payroll', 'json', 'PAYE bands (monthly)');
        if (isset($d['sales_default_terms'])) M\Setting::put('sales.default_terms_days', $d['sales_default_terms'], 'sales', 'number', 'Default payment terms (days)');
        return back()->with('success', 'Preferences saved.');
    }
    public function backup() {
        $this->need('settings.view');
        $bin = trim((string) shell_exec('command -v mysqldump || command -v mariadb-dump'));
        abort_if($bin === '', 500, 'mysqldump not found on server.');
        $c = config('database.connections.mysql');
        $fn = 'nowills_sqc_erp_'.date('Ymd_His').'.sql';
        return response()->streamDownload(function () use ($bin, $c) {
            $cmd = sprintf('%s --host=%s --port=%s --user=%s --password=%s %s 2>/dev/null', escapeshellarg($bin), escapeshellarg($c['host']),
                escapeshellarg($c['port']), escapeshellarg($c['username']), escapeshellarg($c['password']), escapeshellarg($c['database']));
            $h = popen($cmd, 'r');
            while (!feof($h)) echo fread($h, 8192);
            pclose($h);
        }, $fn, ['Content-Type' => 'application/sql']);
    }
}
