#!/bin/bash
# ============================================================
# SaaS Accounting — General & Accounting Settings Enhancement
# Features:
#   General Tab:
#     + Beep Sound on Save
#     + Voucher Signatory (5 fields)
#     + SMTP Setup
#   Accounting Tab:
#     + Use Multi-Currency
#
# Run: bash deploy_general_settings.sh
# From: ~/public_html/saas-accounting/
# ============================================================
set -e
cd ~/public_html/saas-accounting

echo ""
echo "=============================================="
echo "  General & Accounting Settings Enhancement"
echo "=============================================="
echo ""

# ── 1. Update Setting Model defaults ─────────────────────────────────────────
echo "Step 1: Updating Setting Model defaults..."
cat > app/Models/Setting.php << 'PHPEOF'
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Setting extends Model
{
    protected $fillable = ['company_id','key','value'];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public static function get(int $companyId, string $key, $default = null)
    {
        $cacheKey = "settings_{$companyId}_{$key}";
        $sentinel = '__NOT_FOUND__';
        $cached = Cache::remember($cacheKey, 3600, function () use ($companyId, $key, $sentinel) {
            $value = static::where('company_id', $companyId)->where('key', $key)->value('value');
            return $value ?? $sentinel;
        });
        return ($cached === $sentinel) ? $default : $cached;
    }

    public static function set(int $companyId, string $key, $value): void
    {
        static::updateOrCreate(
            ['company_id' => $companyId, 'key' => $key],
            ['value' => $value]
        );
        Cache::forget("settings_{$companyId}_{$key}");
    }

    public static function forgetAll(int $companyId): void
    {
        foreach (array_keys(static::defaults()) as $key) {
            Cache::forget("settings_{$companyId}_{$key}");
        }
    }

    public static function defaults(): array
    {
        return [
            // ── General ───────────────────────────────────────────────────────
            'fiscal_year_start_month'    => '1',
            'timezone'                   => 'UTC',
            'date_format'                => 'DD/MM/YYYY',
            'currency_code'              => 'USD',
            'currency_symbol'            => '$',
            'amount_decimals'            => '2',
            'qty_decimals'               => '2',
            'rate_decimals'              => '4',
            'thousand_separator'         => ',',
            'amount_in_words_language'   => 'en',
            'max_attachment_size_kb'     => '10240',
            'autosave_interval_seconds'  => '120',

            // Beep sound
            'beep_on_save'               => '1',

            // Voucher Signatory
            'signatory_prepared_by'      => 'Prepared By',
            'signatory_checked_by'       => 'Checked By',
            'signatory_custom1'          => '',
            'signatory_custom2'          => '',
            'signatory_approved_by'      => 'Approved By',

            // SMTP
            'smtp_host'                  => '',
            'smtp_port'                  => '587',
            'smtp_username'              => '',
            'smtp_password'              => '',
            'smtp_from_name'             => '',
            'smtp_from_email'            => '',
            'smtp_encryption'            => 'tls',

            // ── Accounting ────────────────────────────────────────────────────
            'allow_prior_period_posting'   => '0',
            'prior_period_warning'         => '1',
            'voucher_approval_required'    => '0',
            'allow_negative_cash_bank'     => '0',
            'use_multi_currency'           => '0',

            // ── Inventory ─────────────────────────────────────────────────────
            'allow_negative_inventory'   => '0',
            'use_multi_warehouse'        => '0',
            'use_manufacturing'          => '0',
            'use_serial_number'          => '0',
            'use_lot_number'             => '0',
            'use_fifo_valuation'         => '0',
            'stock_valuation_method'     => 'weighted_average',

            // ── AR & AP ───────────────────────────────────────────────────────
            'price_level_enabled'        => '0',
            'customer_aging_basis'       => 'invoice_date',
            'vendor_aging_basis'         => 'bill_date',
        ];
    }
}
PHPEOF
echo "  Done."

# ── 2. Update CompanySettingsController ───────────────────────────────────────
echo "Step 2: Updating CompanySettingsController..."
cat > app/Http/Controllers/Company/Settings/CompanySettingsController.php << 'PHPEOF'
<?php

namespace App\Http\Controllers\Company\Settings;

use App\Http\Controllers\Controller;
use App\Models\{AuditLog, Currency, Setting};
use Illuminate\Http\Request;

class CompanySettingsController extends Controller
{
    private function companyId(): int
    {
        return auth()->user()->company_id;
    }

    private function allSettings(): array
    {
        $id   = $this->companyId();
        $rows = Setting::where('company_id', $id)->get()->pluck('value', 'key')->toArray();
        return array_merge(Setting::defaults(), $rows);
    }

    private function saveSettings(array $data): void
    {
        $id = $this->companyId();
        foreach ($data as $key => $value) {
            Setting::set($id, $key, $value);
        }
    }

    // ── General ───────────────────────────────────────────────────────────────
    public function general()
    {
        $company    = auth()->user()->company;
        $currencies = Currency::where('is_active', true)->orderBy('code')->get();
        $settings   = $this->allSettings();
        $timezones  = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
        $symbolMap  = $currencies->mapWithKeys(fn($c) => [$c->code => $c->symbol])->toArray();
        return view('settings.general', compact('company', 'currencies', 'settings', 'timezones', 'symbolMap'));
    }

    public function updateGeneral(Request $request)
    {
        $validated = $request->validate([
            'timezone'                 => 'required|timezone',
            'date_format'              => 'required|in:DD/MM/YYYY,MM/DD/YYYY,YYYY-MM-DD,DD-MM-YYYY,DD.MM.YYYY',
            'currency_code'            => 'required|string|size:3',
            'currency_symbol'          => 'required|string|max:5',
            'amount_decimals'          => 'required|integer|min:0|max:4',
            'qty_decimals'             => 'required|integer|min:0|max:4',
            'rate_decimals'            => 'required|integer|min:0|max:6',
            'thousand_separator'       => 'required|in:comma,period,space',
            'amount_in_words_language' => 'required|in:en,bn',
            'company_name'             => 'required|string|max:150',
            'company_email'            => 'nullable|email|max:150',
            'company_phone'            => 'nullable|string|max:30',
            'company_address'          => 'nullable|string|max:500',
            'company_tax_id'           => 'nullable|string|max:50',
            'company_website'          => 'nullable|url|max:200',
            'logo'                     => 'nullable|image|mimes:png,jpg,jpeg,svg+xml|max:2048',
            // Beep
            'beep_on_save'             => 'nullable|in:0,1',
            // Signatory
            'signatory_prepared_by'    => 'nullable|string|max:50',
            'signatory_checked_by'     => 'nullable|string|max:50',
            'signatory_custom1'        => 'nullable|string|max:50',
            'signatory_custom2'        => 'nullable|string|max:50',
            'signatory_approved_by'    => 'nullable|string|max:50',
            // SMTP
            'smtp_host'                => 'nullable|string|max:150',
            'smtp_port'                => 'nullable|integer|min:1|max:65535',
            'smtp_username'            => 'nullable|string|max:150',
            'smtp_password'            => 'nullable|string|max:200',
            'smtp_from_name'           => 'nullable|string|max:100',
            'smtp_from_email'          => 'nullable|email|max:150',
            'smtp_encryption'          => 'nullable|in:tls,ssl,none',
        ]);

        $separatorMap = ['comma' => ',', 'period' => '.', 'space' => ' '];
        $validated['thousand_separator'] = $separatorMap[$validated['thousand_separator']];

        // Checkbox
        $validated['beep_on_save'] = $request->boolean('beep_on_save') ? '1' : '0';

        $settingKeys = [
            'timezone','date_format','currency_code','currency_symbol',
            'amount_decimals','qty_decimals','rate_decimals',
            'thousand_separator','amount_in_words_language',
            'beep_on_save',
            'signatory_prepared_by','signatory_checked_by',
            'signatory_custom1','signatory_custom2','signatory_approved_by',
            'smtp_host','smtp_port','smtp_username','smtp_password',
            'smtp_from_name','smtp_from_email','smtp_encryption',
        ];
        $this->saveSettings(array_intersect_key($validated, array_flip($settingKeys)));

        $company = auth()->user()->company;
        $old     = $company->only(['name','email','phone','address','tax_id','website']);

        $company->update([
            'name'    => $validated['company_name'],
            'email'   => $validated['company_email'] ?? null,
            'phone'   => $validated['company_phone'] ?? null,
            'address' => $validated['company_address'] ?? null,
            'tax_id'  => $validated['company_tax_id'] ?? null,
            'website' => $validated['company_website'] ?? null,
        ]);

        if ($request->hasFile('logo') && $request->file('logo')->isValid()) {
            $path = $request->file('logo')->store("logos/{$this->companyId()}", 'public');
            $company->update(['logo' => $path]);
        }

        AuditLog::record('update', 'settings', null, $old,
            $company->only(['name','email','phone']), 'General settings updated');

        return back()->with('success', 'General settings saved successfully.');
    }

    // ── Accounting ────────────────────────────────────────────────────────────
    public function accounting()
    {
        $settings = $this->allSettings();
        return view('settings.accounting', compact('settings'));
    }

    public function updateAccounting(Request $request)
    {
        $validated = $request->validate([
            'fiscal_year_start_month'    => 'required|integer|min:1|max:12',
            'allow_prior_period_posting' => 'required|in:0,1',
            'prior_period_warning'       => 'required|in:0,1',
        ]);

        $validated['voucher_approval_required'] = $request->boolean('voucher_approval_required') ? '1' : '0';
        $validated['allow_negative_cash_bank']  = $request->boolean('allow_negative_cash_bank')  ? '1' : '0';
        $validated['use_multi_currency']        = $request->boolean('use_multi_currency')         ? '1' : '0';

        $this->saveSettings($validated);

        AuditLog::record('update', 'settings', null, null, $validated, 'Accounting settings updated');
        return back()->with('success', 'Accounting settings saved.');
    }

    // ── Inventory ─────────────────────────────────────────────────────────────
    public function inventory()
    {
        $settings = $this->allSettings();
        return view('settings.inventory', compact('settings'));
    }

    public function updateInventory(Request $request)
    {
        $boolKeys = [
            'allow_negative_inventory','use_multi_warehouse',
            'use_manufacturing','use_serial_number',
            'use_lot_number','use_fifo_valuation',
        ];
        $data = [];
        foreach ($boolKeys as $key) {
            $data[$key] = $request->boolean($key) ? '1' : '0';
        }
        $data['stock_valuation_method'] = $data['use_fifo_valuation'] === '1' ? 'fifo' : 'weighted_average';
        $this->saveSettings($data);

        AuditLog::record('update', 'settings', null, null, $data, 'Inventory settings updated');
        return back()->with('success', 'Inventory settings saved.');
    }

    // ── AR & AP ───────────────────────────────────────────────────────────────
    public function arap()
    {
        $settings = $this->allSettings();
        return view('settings.arap', compact('settings'));
    }

    public function updateArap(Request $request)
    {
        $validated = $request->validate([
            'customer_aging_basis' => 'required|in:invoice_date,due_date',
            'vendor_aging_basis'   => 'required|in:bill_date,due_date',
        ]);
        $validated['price_level_enabled'] = $request->boolean('price_level_enabled') ? '1' : '0';
        $this->saveSettings($validated);

        AuditLog::record('update', 'settings', null, null, $validated, 'AR/AP settings updated');
        return back()->with('success', 'AR & AP settings saved.');
    }

    // ── Security ──────────────────────────────────────────────────────────────
    public function security()
    {
        $settings     = $this->allSettings();
        $subscription = auth()->user()->company->subscription;
        return view('settings.security', compact('settings', 'subscription'));
    }

    public function updateSecurity(Request $request)
    {
        $validated = $request->validate([
            'autosave_interval_seconds' => 'required|integer|min:30|max:600',
            'max_attachment_size_kb'    => 'required|integer|min:256|max:51200',
        ]);
        $this->saveSettings($validated);

        AuditLog::record('update', 'settings', null, null, $validated, 'System settings updated');
        return back()->with('success', 'Settings saved successfully.');
    }
}
PHPEOF
echo "  Done."

# ── 3. Rewrite General Settings View ─────────────────────────────────────────
echo "Step 3: Rewriting General settings view..."
cat > resources/views/settings/general.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title', 'General Settings')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active">General Settings</li>
@endsection
@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Company Settings</h1>
        <p class="page-subtitle">Configure your company profile and display preferences</p>
    </div>
</div>

@include('settings._tabs', ['active' => 'general'])

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-4">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif

<form method="POST" action="{{ route('settings.general.update') }}" enctype="multipart/form-data" id="settingsForm">
@csrf @method('PUT')

<div class="row g-4">

    {{-- ── Company Profile ──────────────────────────────────────────────── --}}
    <div class="col-12 col-xl-6">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-building me-2 text-primary"></i>Company Profile</div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label fw-semibold">Company Logo</label>
                        <div class="d-flex align-items-center gap-3 mb-2">
                            @if($company->logo)
                                <img src="{{ asset('storage/'.$company->logo) }}"
                                     style="height:60px;max-width:160px;object-fit:contain;border:1px solid #dee2e6;border-radius:6px;padding:4px;background:#fff" alt="Logo">
                            @else
                                <div style="width:60px;height:60px;background:var(--accent);border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--primary);font-weight:700;font-size:22px">
                                    {{ strtoupper(substr($company->name,0,1)) }}
                                </div>
                            @endif
                            <div>
                                <input type="file" name="logo" id="logoInput" accept="image/png,image/jpeg,image/svg+xml" class="form-control form-control-sm">
                                <div class="form-text">PNG/JPG/SVG, max 2MB. Recommended: 200×60px</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Company Name <span class="text-danger">*</span></label>
                        <input type="text" name="company_name" class="form-control @error('company_name') is-invalid @enderror"
                               value="{{ old('company_name', $company->name) }}" required>
                        @error('company_name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Email</label>
                        <input type="email" name="company_email" class="form-control"
                               value="{{ old('company_email', $company->email) }}" placeholder="info@company.com">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Phone</label>
                        <input type="text" name="company_phone" class="form-control"
                               value="{{ old('company_phone', $company->phone) }}">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Tax / VAT ID</label>
                        <input type="text" name="company_tax_id" class="form-control"
                               value="{{ old('company_tax_id', $company->tax_id) }}" placeholder="VAT number">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Website</label>
                        <input type="url" name="company_website" class="form-control"
                               value="{{ old('company_website', $company->website) }}" placeholder="https://...">
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Address</label>
                        <textarea name="company_address" class="form-control" rows="2">{{ old('company_address', $company->address) }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- ── Display Preferences ──────────────────────────────────────────── --}}
    <div class="col-12 col-xl-6">
        <div class="card mb-4">
            <div class="card-header"><i class="bi bi-display me-2 text-primary"></i>Display Preferences</div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-6">
                        <label class="form-label fw-semibold">Timezone <span class="text-danger">*</span></label>
                        <select name="timezone" class="form-select select2">
                            @foreach($timezones as $tz)
                                <option value="{{ $tz }}" {{ $settings['timezone']===$tz?'selected':'' }}>{{ $tz }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Date Format <span class="text-danger">*</span></label>
                        <select name="date_format" class="form-select">
                            @foreach(['DD/MM/YYYY','MM/DD/YYYY','YYYY-MM-DD','DD-MM-YYYY','DD.MM.YYYY'] as $fmt)
                                <option value="{{ $fmt }}" {{ $settings['date_format']===$fmt?'selected':'' }}>{{ $fmt }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Base Currency Code <span class="text-danger">*</span></label>
                        <select name="currency_code" class="form-select select2" id="currencySelect">
                            @foreach($currencies as $cur)
                                <option value="{{ $cur->code }}" data-symbol="{{ $cur->symbol }}"
                                        {{ $settings['currency_code']===$cur->code?'selected':'' }}>
                                    {{ $cur->code }} — {{ $cur->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Currency Symbol <span class="text-danger">*</span></label>
                        <input type="text" name="currency_symbol" id="currencySymbol" class="form-control"
                               value="{{ old('currency_symbol', $settings['currency_symbol']) }}" maxlength="5" required>
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold">Amount Decimals</label>
                        <select name="amount_decimals" class="form-select">
                            @foreach([0,1,2,3,4] as $d)<option value="{{ $d }}" {{ $settings['amount_decimals']==$d?'selected':'' }}>{{ $d }}</option>@endforeach
                        </select>
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold">Qty Decimals</label>
                        <select name="qty_decimals" class="form-select">
                            @foreach([0,1,2,3,4] as $d)<option value="{{ $d }}" {{ $settings['qty_decimals']==$d?'selected':'' }}>{{ $d }}</option>@endforeach
                        </select>
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold">Rate Decimals</label>
                        <select name="rate_decimals" class="form-select">
                            @foreach([2,3,4,5,6] as $d)<option value="{{ $d }}" {{ $settings['rate_decimals']==$d?'selected':'' }}>{{ $d }}</option>@endforeach
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Thousand Separator</label>
                        <select name="thousand_separator" class="form-select">
                            <option value="comma"  {{ $settings['thousand_separator']===','?'selected':'' }}>Comma (1,000)</option>
                            <option value="period" {{ $settings['thousand_separator']==='.'?'selected':'' }}>Period (1.000)</option>
                            <option value="space"  {{ $settings['thousand_separator']===' '?'selected':'' }}>Space (1 000)</option>
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Amount in Words</label>
                        <select name="amount_in_words_language" class="form-select">
                            <option value="en" {{ $settings['amount_in_words_language']==='en'?'selected':'' }}>English</option>
                            <option value="bn" {{ $settings['amount_in_words_language']==='bn'?'selected':'' }}>Bengali (বাংলা)</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        {{-- Number Format Preview --}}
        <div class="card">
            <div class="card-header"><i class="bi bi-eye me-2 text-primary"></i>Number Format Preview</div>
            <div class="card-body">
                <table class="table table-sm mb-0" style="font-size:13px">
                    <tr><td class="text-muted">Amount</td><td class="fw-semibold" id="previewAmount">$ 1,234,567.89</td></tr>
                    <tr><td class="text-muted">Quantity</td><td class="fw-semibold" id="previewQty">1,234.50</td></tr>
                    <tr><td class="text-muted">Unit Rate</td><td class="fw-semibold" id="previewRate">25.5000</td></tr>
                    <tr><td class="text-muted">Amount in Words</td><td class="fw-semibold text-primary" id="previewWords">One Million Two Hundred...</td></tr>
                </table>
            </div>
        </div>
    </div>

    {{-- ── Transaction Preferences ──────────────────────────────────────── --}}
    <div class="col-12 col-xl-6">
        <div class="card">
            <div class="card-header"><i class="bi bi-sliders me-2 text-primary"></i>Transaction Preferences</div>
            <div class="card-body">
                <div class="p-3 rounded-2 border bg-light">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="beep_on_save"
                               value="1" id="beepOnSave" role="switch"
                               {{ ($settings['beep_on_save'] ?? '1') === '1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="beepOnSave">
                            <i class="bi bi-volume-up me-1 text-primary"></i>Beep Sound When Saving a Transaction
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>ON</strong>: a short beep sound plays each time a transaction
                        is saved successfully — useful for fast data entry.
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- ── Voucher Signatory ────────────────────────────────────────────── --}}
    <div class="col-12 col-xl-6">
        <div class="card">
            <div class="card-header"><i class="bi bi-pen me-2 text-primary"></i>Voucher Signatory</div>
            <div class="card-body">
                <p class="text-muted mb-3" style="font-size:13px">
                    Signature blocks shown on printed vouchers. The first, second and last labels are always shown
                    (defaults: "Prepared By", "Checked By", "Approved By"); customise them as needed.
                    The two middle custom labels appear only if filled in.
                </p>
                <div class="row g-3">
                    <div class="col-12 col-sm-4">
                        <label class="form-label fw-semibold" style="font-size:12.5px">1. Prepared By</label>
                        <input type="text" name="signatory_prepared_by" class="form-control form-control-sm"
                               value="{{ old('signatory_prepared_by', $settings['signatory_prepared_by'] ?? 'Prepared By') }}"
                               placeholder="Prepared By">
                    </div>
                    <div class="col-12 col-sm-4">
                        <label class="form-label fw-semibold" style="font-size:12.5px">2. Checked By</label>
                        <input type="text" name="signatory_checked_by" class="form-control form-control-sm"
                               value="{{ old('signatory_checked_by', $settings['signatory_checked_by'] ?? 'Checked By') }}"
                               placeholder="Checked By">
                    </div>
                    <div class="col-12 col-sm-4">
                        <label class="form-label fw-semibold" style="font-size:12.5px">3. Custom Signatory 1 <span class="text-muted">(optional)</span></label>
                        <input type="text" name="signatory_custom1" class="form-control form-control-sm"
                               value="{{ old('signatory_custom1', $settings['signatory_custom1'] ?? '') }}"
                               placeholder="e.g. Verified By">
                    </div>
                    <div class="col-12 col-sm-4">
                        <label class="form-label fw-semibold" style="font-size:12.5px">4. Custom Signatory 2 <span class="text-muted">(optional)</span></label>
                        <input type="text" name="signatory_custom2" class="form-control form-control-sm"
                               value="{{ old('signatory_custom2', $settings['signatory_custom2'] ?? '') }}"
                               placeholder="e.g. Authorized By">
                    </div>
                    <div class="col-12 col-sm-4">
                        <label class="form-label fw-semibold" style="font-size:12.5px">5. Approved By</label>
                        <input type="text" name="signatory_approved_by" class="form-control form-control-sm"
                               value="{{ old('signatory_approved_by', $settings['signatory_approved_by'] ?? 'Approved By') }}"
                               placeholder="Approved By">
                    </div>
                </div>
                <div class="mt-3 text-muted" style="font-size:12px">
                    <i class="bi bi-info-circle me-1"></i>
                    Leave the custom fields blank to hide them on printed vouchers.
                    Leave the fixed fields blank to use the default labels.
                </div>
            </div>
        </div>
    </div>

    {{-- ── SMTP Setup ───────────────────────────────────────────────────── --}}
    <div class="col-12">
        <div class="card">
            <div class="card-header"><i class="bi bi-envelope-at me-2 text-primary"></i>SMTP Setup
                <span class="badge ms-2" style="background:#EBF3FB;color:#1B4F8A;font-size:11px;font-weight:500">For emailing reports &amp; documents</span>
            </div>
            <div class="card-body">
                <p class="text-muted mb-3" style="font-size:13px">
                    Configure outgoing email settings to allow the system to send reports,
                    invoices and other documents directly from your company email address.
                </p>
                <div class="row g-3">
                    <div class="col-12 col-sm-6 col-md-4">
                        <label class="form-label fw-semibold">SMTP Host</label>
                        <input type="text" name="smtp_host" class="form-control"
                               value="{{ old('smtp_host', $settings['smtp_host'] ?? '') }}"
                               placeholder="e.g. smtp.gmail.com">
                    </div>
                    <div class="col-6 col-sm-3 col-md-2">
                        <label class="form-label fw-semibold">Port</label>
                        <input type="number" name="smtp_port" class="form-control"
                               value="{{ old('smtp_port', $settings['smtp_port'] ?? '587') }}"
                               placeholder="587">
                    </div>
                    <div class="col-6 col-sm-3 col-md-2">
                        <label class="form-label fw-semibold">Encryption</label>
                        <select name="smtp_encryption" class="form-select">
                            <option value="tls"  {{ ($settings['smtp_encryption'] ?? 'tls') === 'tls'  ? 'selected' : '' }}>TLS</option>
                            <option value="ssl"  {{ ($settings['smtp_encryption'] ?? '')    === 'ssl'  ? 'selected' : '' }}>SSL</option>
                            <option value="none" {{ ($settings['smtp_encryption'] ?? '')    === 'none' ? 'selected' : '' }}>None</option>
                        </select>
                    </div>
                    <div class="col-12 col-sm-6 col-md-4">
                        <label class="form-label fw-semibold">SMTP Username</label>
                        <input type="text" name="smtp_username" class="form-control"
                               value="{{ old('smtp_username', $settings['smtp_username'] ?? '') }}"
                               placeholder="your@email.com" autocomplete="off">
                    </div>
                    <div class="col-12 col-sm-6 col-md-4">
                        <label class="form-label fw-semibold">SMTP Password</label>
                        <div class="input-group">
                            <input type="password" name="smtp_password" id="smtpPass" class="form-control"
                                   value="{{ old('smtp_password', $settings['smtp_password'] ?? '') }}"
                                   placeholder="App password or SMTP password" autocomplete="off">
                            <button type="button" class="btn btn-outline-secondary" id="toggleSmtpPass">
                                <i class="bi bi-eye" id="smtpPassIcon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-12 col-sm-6 col-md-4">
                        <label class="form-label fw-semibold">From Name</label>
                        <input type="text" name="smtp_from_name" class="form-control"
                               value="{{ old('smtp_from_name', $settings['smtp_from_name'] ?? '') }}"
                               placeholder="e.g. Demo Company Ltd">
                    </div>
                    <div class="col-12 col-sm-6 col-md-4">
                        <label class="form-label fw-semibold">From Email</label>
                        <input type="email" name="smtp_from_email" class="form-control"
                               value="{{ old('smtp_from_email', $settings['smtp_from_email'] ?? '') }}"
                               placeholder="noreply@company.com">
                    </div>
                </div>
                <div class="mt-3 d-flex align-items-center gap-2">
                    <button type="button" class="btn btn-outline-secondary btn-sm" id="testSmtpBtn">
                        <i class="bi bi-send me-1"></i>Test Connection
                    </button>
                    <span id="smtpTestResult" class="text-muted" style="font-size:12.5px"></span>
                </div>
            </div>
        </div>
    </div>

    {{-- Action Bar --}}
    <div class="col-12">
        <div class="d-flex gap-3 justify-content-end">
            <a href="{{ route('dashboard') }}" class="btn btn-outline-secondary">
                <i class="bi bi-x me-1"></i>Cancel
            </a>
            <button type="submit" class="btn btn-primary px-4" id="saveBtn">
                <i class="bi bi-check-circle me-1"></i>Save General Settings
            </button>
        </div>
    </div>
</div>
</form>
@endsection

@push('scripts')
<script>
const symbolMap = @json($symbolMap);
$('#currencySelect').on('change', function() {
    const code = $(this).val();
    if (code && symbolMap[code]) $('#currencySymbol').val(symbolMap[code]);
});

document.getElementById('settingsForm').addEventListener('submit', function() {
    const btn = document.getElementById('saveBtn');
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
    btn.disabled = true;
});

// Toggle SMTP password visibility
document.getElementById('toggleSmtpPass').addEventListener('click', function() {
    const input = document.getElementById('smtpPass');
    const icon  = document.getElementById('smtpPassIcon');
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'bi bi-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'bi bi-eye';
    }
});

// SMTP test (placeholder — shows instructions)
document.getElementById('testSmtpBtn').addEventListener('click', function() {
    const result = document.getElementById('smtpTestResult');
    result.className = 'text-info';
    result.textContent = 'Save settings first, then use the test email feature from Reports.';
});
</script>
@endpush
BLADEEOF
echo "  Done."

# ── 4. Rewrite Accounting Settings View (add Multi-Currency) ──────────────────
echo "Step 4: Updating Accounting settings view with Multi-Currency..."
cat > resources/views/settings/accounting.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title', 'Accounting Settings')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active">Accounting Settings</li>
@endsection
@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Accounting Settings</h1>
        <p class="page-subtitle">Configure fiscal year and accounting behaviour</p>
    </div>
</div>

@include('settings._tabs', ['active' => 'accounting'])

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-4">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif

<form method="POST" action="{{ route('settings.accounting.update') }}" id="accForm">
@csrf @method('PUT')
<div class="row g-4">

    {{-- Fiscal Year --}}
    <div class="col-12 col-xl-6">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-calendar3 me-2 text-primary"></i>Fiscal Year</div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label fw-semibold">Fiscal Year Start Month <span class="text-danger">*</span></label>
                        <select name="fiscal_year_start_month" class="form-select">
                            @php $months=['January','February','March','April','May','June','July','August','September','October','November','December']; @endphp
                            @foreach($months as $i => $month)
                                <option value="{{ $i+1 }}" {{ $settings['fiscal_year_start_month']==$i+1?'selected':'' }}>{{ $month }}</option>
                            @endforeach
                        </select>
                        <div class="form-text"><i class="bi bi-info-circle me-1 text-primary"></i>Uses virtual closing — no closing journal entries required.</div>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Prior Period Posting</label>
                        <div class="d-flex gap-3 mt-1">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="allow_prior_period_posting" value="1" id="priorYes" {{ $settings['allow_prior_period_posting']==='1'?'checked':'' }}>
                                <label class="form-check-label" for="priorYes">Allow</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="allow_prior_period_posting" value="0" id="priorNo" {{ $settings['allow_prior_period_posting']!=='1'?'checked':'' }}>
                                <label class="form-check-label" for="priorNo">Disallow</label>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Show Warning for Prior Period Posting</label>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="prior_period_warning" value="1" id="priorWarn" role="switch" {{ $settings['prior_period_warning']==='1'?'checked':'' }}>
                            <label class="form-check-label" for="priorWarn">Show warning before posting to a prior period</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Accounting Guards --}}
    <div class="col-12 col-xl-6">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-shield-check me-2 text-primary"></i>Accounting Guards &amp; Modules</div>
            <div class="card-body">
                <div class="row g-3">

                    {{-- Negative Cash/Bank --}}
                    <div class="col-12">
                        <div class="p-3 rounded-2 border {{ $settings['allow_negative_cash_bank']==='0' ? 'border-success-subtle bg-success-subtle' : 'border-warning-subtle bg-warning-subtle' }}">
                            <div class="form-check form-switch mb-1">
                                <input class="form-check-input" type="checkbox" name="allow_negative_cash_bank"
                                       value="1" id="negCashBank" role="switch"
                                       {{ $settings['allow_negative_cash_bank']==='1' ? 'checked' : '' }}>
                                <label class="form-check-label fw-semibold" for="negCashBank">
                                    Allow Negative Cash or Bank Balance
                                </label>
                            </div>
                            <div class="text-muted" style="font-size:12px">
                                When <strong>OFF</strong> (recommended): any transaction that would make a
                                Cash or Bank account balance negative is blocked at save time.
                            </div>
                        </div>
                    </div>

                    {{-- Voucher Approval --}}
                    <div class="col-12">
                        <div class="p-3 rounded-2 border bg-light">
                            <div class="form-check form-switch mb-1">
                                <input class="form-check-input" type="checkbox" name="voucher_approval_required"
                                       value="1" id="approvalReq" role="switch"
                                       {{ $settings['voucher_approval_required']==='1' ? 'checked' : '' }}>
                                <label class="form-check-label fw-semibold" for="approvalReq">
                                    Use Voucher Approval Process
                                </label>
                            </div>
                            <div class="text-muted" style="font-size:12px">
                                When <strong>ON</strong>: vouchers follow Draft &rarr; Submitted &rarr; Approved &rarr; Posted.
                                When <strong>OFF</strong>: vouchers can be posted directly from Draft.
                            </div>
                        </div>
                    </div>

                    {{-- Multi-Currency --}}
                    <div class="col-12">
                        <div class="p-3 rounded-2 border bg-light">
                            <div class="form-check form-switch mb-1">
                                <input class="form-check-input" type="checkbox" name="use_multi_currency"
                                       value="1" id="multiCurrency" role="switch"
                                       {{ ($settings['use_multi_currency'] ?? '0') === '1' ? 'checked' : '' }}>
                                <label class="form-check-label fw-semibold" for="multiCurrency">
                                    Use Multi-Currency
                                </label>
                            </div>
                            <div class="text-muted" style="font-size:12px">
                                When <strong>ON</strong>: foreign currency fields appear on transactions,
                                exchange rate management is enabled, and multi-currency reports
                                (Unrealised Gains/Losses, Currency Revaluation) become available.
                                When <strong>OFF</strong>: all currency-related features are hidden.
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="d-flex gap-3 justify-content-end">
            <a href="{{ route('dashboard') }}" class="btn btn-outline-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary px-4" id="saveBtn">
                <i class="bi bi-check-circle me-1"></i>Save Accounting Settings
            </button>
        </div>
    </div>
</div>
</form>
@endsection
@push('scripts')
<script>
document.getElementById('accForm').addEventListener('submit', function() {
    var btn = document.getElementById('saveBtn');
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
    btn.disabled = true;
});
</script>
@endpush
BLADEEOF
echo "  Done."

# ── 5. Clear cache ────────────────────────────────────────────────────────────
echo "Step 5: Clearing cache and optimising..."
php artisan view:clear
php artisan route:clear
php artisan config:clear
php artisan optimize

echo ""
echo "=============================================="
echo "  DEPLOY COMPLETE!"
echo "=============================================="
echo ""
echo "  General Tab — new sections:"
echo "  ✅ Beep Sound on Save (ON by default)"
echo "  ✅ Voucher Signatory (5 fields)"
echo "     1. Prepared By"
echo "     2. Checked By"
echo "     3. Custom Signatory 1 (optional)"
echo "     4. Custom Signatory 2 (optional)"
echo "     5. Approved By"
echo "  ✅ SMTP Setup"
echo "     Host / Port / Encryption"
echo "     Username / Password (toggle visibility)"
echo "     From Name / From Email"
echo ""
echo "  Accounting Tab — new guard:"
echo "  ✅ Use Multi-Currency (OFF by default)"
echo "     When OFF: currency fields & reports hidden"
echo "=============================================="
