#!/bin/bash
# ============================================================
# SaaS Accounting — Settings Enhancement Deploy Script
# Features:
#   - Inventory Tab (new)
#   - Accounting Tab updates
#   - AR & AP Tab (new)
#   - All guards/toggles as requested
#
# Run: bash deploy_settings.sh
# From: ~/public_html/saas-accounting/
# ============================================================
set -e
cd ~/public_html/saas-accounting

echo ""
echo "=============================================="
echo "  SaaS 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',

            // Accounting
            'allow_prior_period_posting'   => '0',
            'prior_period_warning'         => '1',
            'voucher_approval_required'    => '0',
            'allow_negative_cash_bank'     => '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',
        ]);

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

        $settingKeys = ['timezone','date_format','currency_code','currency_symbol',
                        'amount_decimals','qty_decimals','rate_decimals',
                        'thousand_separator','amount_in_words_language'];
        $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',
            'voucher_approval_required'  => 'in:0,1',
            'allow_negative_cash_bank'   => 'in:0,1',
        ]);

        // Checkboxes — absent means unchecked = 0
        $validated['voucher_approval_required'] = $request->boolean('voucher_approval_required') ? '1' : '0';
        $validated['allow_negative_cash_bank']  = $request->boolean('allow_negative_cash_bank')  ? '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';
        }

        // Sync stock_valuation_method with use_fifo_valuation
        $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.');
    }

    // ── System / 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. Update Settings Tabs Partial ──────────────────────────────────────────
echo "Step 3: Updating settings tabs..."
cat > resources/views/settings/_tabs.blade.php << 'BLADEEOF'
<div class="card mb-4">
    <div class="card-body py-2 px-3">
        <ul class="nav nav-pills gap-1" style="flex-wrap:nowrap;overflow-x:auto">
            <li class="nav-item">
                <a href="{{ route('settings.general') }}"
                   class="nav-link {{ ($active??'')==='general'?'active':'' }}" style="font-size:13px;white-space:nowrap">
                    <i class="bi bi-building me-1"></i>General
                </a>
            </li>
            <li class="nav-item">
                <a href="{{ route('settings.accounting') }}"
                   class="nav-link {{ ($active??'')==='accounting'?'active':'' }}" style="font-size:13px;white-space:nowrap">
                    <i class="bi bi-calculator me-1"></i>Accounting
                </a>
            </li>
            <li class="nav-item">
                <a href="{{ route('settings.inventory') }}"
                   class="nav-link {{ ($active??'')==='inventory'?'active':'' }}" style="font-size:13px;white-space:nowrap">
                    <i class="bi bi-box-seam me-1"></i>Inventory
                </a>
            </li>
            <li class="nav-item">
                <a href="{{ route('settings.arap') }}"
                   class="nav-link {{ ($active??'')==='arap'?'active':'' }}" style="font-size:13px;white-space:nowrap">
                    <i class="bi bi-arrow-left-right me-1"></i>AR &amp; AP
                </a>
            </li>
            <li class="nav-item">
                <a href="{{ route('settings.security') }}"
                   class="nav-link {{ ($active??'')==='security'?'active':'' }}" style="font-size:13px;white-space:nowrap">
                    <i class="bi bi-shield-lock me-1"></i>System
                </a>
            </li>
        </ul>
    </div>
</div>
BLADEEOF
echo "  Done."

# ── 4. Rewrite Accounting Settings View ──────────────────────────────────────
echo "Step 4: Rewriting Accounting settings view..."
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']==='0'?'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</div>
            <div class="card-body">
                <div class="row g-3">

                    {{-- Allow Negative Cash / Bank --}}
                    <div class="col-12">
                        <div class="p-3 rounded-2 border {{ $settings['allow_negative_cash_bank']==='0'?'border-danger-subtle bg-danger-subtle':'bg-light' }}">
                            <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 → Submitted → Approved → Posted workflow.
                                When <strong>OFF</strong>: vouchers can be posted directly from Draft.
                            </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. Create Inventory Settings View ────────────────────────────────────────
echo "Step 5: Creating Inventory settings view..."
cat > resources/views/settings/inventory.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title', 'Inventory Settings')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active">Inventory Settings</li>
@endsection
@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Inventory Settings</h1>
        <p class="page-subtitle">Configure inventory behaviour, tracking and modules</p>
    </div>
</div>

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

@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.inventory.update') }}" id="invForm">
@csrf @method('PUT')

@php
function guardCard(string $id, string $label, string $desc, string $settingKey, array $settings, string $badgeText = '', string $badgeColor = 'warning'): void {
    $checked = ($settings[$settingKey] ?? '0') === '1';
    $border  = $checked ? 'border-success-subtle' : 'border-warning-subtle';
    $bg      = $checked ? 'bg-success-subtle' : 'bg-warning-subtle';
    echo <<<HTML
    <div class="p-3 rounded-2 border {$border} {$bg} mb-3">
        <div class="form-check form-switch mb-1">
            <input class="form-check-input inv-toggle" type="checkbox" name="{$settingKey}"
                   value="1" id="{$id}" role="switch" data-setting="{$settingKey}"
                   {$( $checked ? 'checked' : '' )}>
            <label class="form-check-label fw-semibold" for="{$id}">{$label}</label>
        </div>
        <div class="text-muted" style="font-size:12px">{$desc}</div>
    </div>
HTML;
}
@endphp

<div class="row g-4">

    {{-- Inventory Behaviour --}}
    <div class="col-12 col-xl-6">
        <div class="card mb-4">
            <div class="card-header"><i class="bi bi-boxes me-2 text-primary"></i>Inventory Behaviour</div>
            <div class="card-body">

                {{-- Allow Negative Inventory --}}
                <div class="p-3 rounded-2 border mb-3 {{ $settings['allow_negative_inventory']==='1' ? 'border-warning-subtle bg-warning-subtle' : 'border-success-subtle bg-success-subtle' }}">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="allow_negative_inventory"
                               value="1" id="negInv" role="switch"
                               {{ $settings['allow_negative_inventory']==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="negInv">
                            Allow Negative Inventory
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>OFF</strong> (recommended): any transaction that would make an
                        inventory item's stock balance negative is blocked. When <strong>ON</strong>:
                        negative stock is allowed (backorder scenario).
                    </div>
                    @if($settings['allow_negative_inventory']==='0')
                    <div class="mt-2 d-flex align-items-center gap-1" style="font-size:12px;color:#856404">
                        <i class="bi bi-shield-check"></i> Guard is <strong>active</strong> — negative stock is blocked
                    </div>
                    @endif
                </div>

                {{-- Use FIFO Valuation --}}
                <div class="p-3 rounded-2 border mb-3 bg-light">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="use_fifo_valuation"
                               value="1" id="fifoVal" role="switch"
                               {{ $settings['use_fifo_valuation']==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="fifoVal">
                            Use FIFO Valuation Method
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>ON</strong>: uses First In, First Out (FIFO) as the default stock
                        valuation method. When <strong>OFF</strong>: uses Weighted Average Cost (WAC).
                        Can be overridden per item.
                    </div>
                    <div class="mt-2 badge" style="background:#EBF3FB;color:#1B4F8A;font-size:11px">
                        Current method: <strong>{{ $settings['use_fifo_valuation']==='1' ? 'FIFO' : 'Weighted Average' }}</strong>
                    </div>
                </div>

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

    {{-- Optional Modules --}}
    <div class="col-12 col-xl-6">
        <div class="card mb-4">
            <div class="card-header"><i class="bi bi-toggles me-2 text-primary"></i>Optional Modules</div>
            <div class="card-body">

                {{-- Multi-Warehouse --}}
                <div class="p-3 rounded-2 border mb-3 bg-light">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="use_multi_warehouse"
                               value="1" id="multiWh" role="switch"
                               {{ $settings['use_multi_warehouse']==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="multiWh">
                            Use Multi-Warehouse
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>OFF</strong>: warehouse selection is hidden from all transaction forms
                        and reports. Enable when you operate from multiple locations.
                    </div>
                </div>

                {{-- Manufacturing --}}
                <div class="p-3 rounded-2 border mb-3 bg-light">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="use_manufacturing"
                               value="1" id="useMfg" role="switch"
                               {{ $settings['use_manufacturing']==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="useMfg">
                            Use Manufacturing Module
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>OFF</strong>: the Manufacturing menu, Bill of Materials and
                        Production Orders are hidden. Enable for production businesses.
                    </div>
                </div>

                {{-- Serial Number --}}
                <div class="p-3 rounded-2 border mb-3 bg-light">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="use_serial_number"
                               value="1" id="useSerial" role="switch"
                               {{ $settings['use_serial_number']==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="useSerial">
                            Use Serial Number Tracking
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>OFF</strong>: serial number fields and reports are hidden.
                        Enable to track individual units by serial number.
                    </div>
                </div>

                {{-- Lot Number --}}
                <div class="p-3 rounded-2 border mb-0 bg-light">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="use_lot_number"
                               value="1" id="useLot" role="switch"
                               {{ $settings['use_lot_number']==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="useLot">
                            Use Lot / Batch Number Tracking
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>OFF</strong>: lot/batch fields and expiry date tracking are hidden.
                        Enable for food, pharma or any batch-tracked products.
                    </div>
                </div>

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

    {{-- Summary of active settings --}}
    <div class="col-12">
        <div class="card" style="background:#f0f9ff;border:1px solid #bae6fd">
            <div class="card-body py-3">
                <div class="fw-semibold mb-2" style="font-size:13px;color:#0369a1">
                    <i class="bi bi-info-circle me-2"></i>Active Inventory Configuration
                </div>
                <div class="row g-2" style="font-size:13px">
                    @php
                    $guards = [
                        ['allow_negative_inventory', 'Negative Inventory', 'Allowed', 'Blocked (recommended)'],
                        ['use_multi_warehouse',       'Multi-Warehouse',    'Enabled', 'Disabled'],
                        ['use_manufacturing',         'Manufacturing',      'Enabled', 'Disabled'],
                        ['use_serial_number',         'Serial Tracking',    'Enabled', 'Disabled'],
                        ['use_lot_number',            'Lot Tracking',       'Enabled', 'Disabled'],
                        ['use_fifo_valuation',        'FIFO Valuation',     'FIFO',    'Weighted Average'],
                    ];
                    @endphp
                    @foreach($guards as [$key, $label, $on, $off])
                    <div class="col-6 col-md-4">
                        <span class="fw-semibold">{{ $label }}:</span>
                        <span class="{{ $settings[$key]==='1' ? 'text-success' : 'text-secondary' }}">
                            {{ $settings[$key]==='1' ? $on : $off }}
                        </span>
                    </div>
                    @endforeach
                </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 Inventory Settings
            </button>
        </div>
    </div>
</div>
</form>
@endsection
@push('scripts')
<script>
document.getElementById('invForm').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."

# ── 6. Create AR & AP Settings View ──────────────────────────────────────────
echo "Step 6: Creating AR & AP settings view..."
cat > resources/views/settings/arap.blade.php << 'BLADEEOF'
@extends('layouts.app')
@section('title', 'AR & AP Settings')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active">AR & AP Settings</li>
@endsection
@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">AR &amp; AP Settings</h1>
        <p class="page-subtitle">Configure Accounts Receivable and Accounts Payable behaviour</p>
    </div>
</div>

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

@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.arap.update') }}" id="arapForm">
@csrf @method('PUT')

<div class="row g-4">

    {{-- Pricing --}}
    <div class="col-12 col-xl-6">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-tags me-2 text-primary"></i>Pricing</div>
            <div class="card-body">

                {{-- Price Levels --}}
                <div class="p-3 rounded-2 border bg-light mb-0">
                    <div class="form-check form-switch mb-1">
                        <input class="form-check-input" type="checkbox" name="price_level_enabled"
                               value="1" id="priceLevel" role="switch"
                               {{ ($settings['price_level_enabled']??'0')==='1' ? 'checked' : '' }}>
                        <label class="form-check-label fw-semibold" for="priceLevel">
                            Use Price Levels
                        </label>
                    </div>
                    <div class="text-muted" style="font-size:12px">
                        When <strong>ON</strong>: customers can be assigned different price tiers
                        (e.g. Retail, Wholesale, VIP). Price level fields appear on customer profiles
                        and sales documents. When <strong>OFF</strong>: all price level features
                        and reports are hidden.
                    </div>
                </div>

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

    {{-- Aging Calculation --}}
    <div class="col-12 col-xl-6">
        <div class="card h-100">
            <div class="card-header"><i class="bi bi-clock-history me-2 text-primary"></i>Aging Calculation</div>
            <div class="card-body">
                <p class="text-muted mb-3" style="font-size:13px">
                    Choose whether customer and vendor aging is calculated from the
                    Invoice/Bill Date or the Due Date. Aging reports use this setting.
                    If no Due Date is set, the Invoice/Bill Date is used as a fallback.
                </p>
                <div class="row g-3">
                    <div class="col-12 col-sm-6">
                        <label class="form-label fw-semibold">Customer Aging Basis</label>
                        <select name="customer_aging_basis" class="form-select">
                            <option value="invoice_date" {{ ($settings['customer_aging_basis']??'invoice_date')==='invoice_date' ? 'selected' : '' }}>
                                Invoice Date
                            </option>
                            <option value="due_date" {{ ($settings['customer_aging_basis']??'')==='due_date' ? 'selected' : '' }}>
                                Due Date
                            </option>
                        </select>
                    </div>
                    <div class="col-12 col-sm-6">
                        <label class="form-label fw-semibold">Vendor Aging Basis</label>
                        <select name="vendor_aging_basis" class="form-select">
                            <option value="bill_date" {{ ($settings['vendor_aging_basis']??'bill_date')==='bill_date' ? 'selected' : '' }}>
                                Bill Date
                            </option>
                            <option value="due_date" {{ ($settings['vendor_aging_basis']??'')==='due_date' ? 'selected' : '' }}>
                                Due Date
                            </option>
                        </select>
                    </div>
                    <div class="col-12">
                        <div class="alert alert-info py-2 d-flex gap-2 align-items-start" style="font-size:12.5px">
                            <i class="bi bi-info-circle flex-shrink-0 mt-1"></i>
                            <div>
                                If no Due Date is set on a transaction, the Invoice/Bill Date is used as a fallback.
                                This affects Customer Aging, Vendor Aging, and Overdue reports.
                            </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 AR &amp; AP Settings
            </button>
        </div>
    </div>

</div>
</form>
@endsection
@push('scripts')
<script>
document.getElementById('arapForm').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."

# ── 7. Update Routes ──────────────────────────────────────────────────────────
echo "Step 7: Adding new settings routes..."
# Add inventory and arap routes to web.php
python3 << 'PYEOF'
content = open('routes/web.php').read()

old = """    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/general',    [CompanySettingsController::class, 'general'])->name('general');
        Route::put('/general',    [CompanySettingsController::class, 'updateGeneral'])->name('general.update');
        Route::get('/accounting', [CompanySettingsController::class, 'accounting'])->name('accounting');
        Route::put('/accounting', [CompanySettingsController::class, 'updateAccounting'])->name('accounting.update');
        Route::get('/security',   [CompanySettingsController::class, 'security'])->name('security');
        Route::put('/security',   [CompanySettingsController::class, 'updateSecurity'])->name('security.update');
    });"""

new = """    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/general',    [CompanySettingsController::class, 'general'])->name('general');
        Route::put('/general',    [CompanySettingsController::class, 'updateGeneral'])->name('general.update');
        Route::get('/accounting', [CompanySettingsController::class, 'accounting'])->name('accounting');
        Route::put('/accounting', [CompanySettingsController::class, 'updateAccounting'])->name('accounting.update');
        Route::get('/inventory',  [CompanySettingsController::class, 'inventory'])->name('inventory');
        Route::put('/inventory',  [CompanySettingsController::class, 'updateInventory'])->name('inventory.update');
        Route::get('/arap',       [CompanySettingsController::class, 'arap'])->name('arap');
        Route::put('/arap',       [CompanySettingsController::class, 'updateArap'])->name('arap.update');
        Route::get('/security',   [CompanySettingsController::class, 'security'])->name('security');
        Route::put('/security',   [CompanySettingsController::class, 'updateSecurity'])->name('security.update');
    });"""

content = content.replace(old, new)
open('routes/web.php', 'w').write(content)
print("  Routes updated.")
PYEOF

# ── 8. Add settings link to sidebar Admin menu ────────────────────────────────
echo "Step 8: Updating sidebar settings link..."
python3 << 'PYEOF'
content = open('resources/views/layouts/app.blade.php').read()
# Update admin active check to include new settings routes
content = content.replace(
    "$adminActive = request()->routeIs('settings.*','admin.*');",
    "$adminActive = request()->routeIs('settings.*','admin.*','settings.inventory','settings.arap');"
)
open('resources/views/layouts/app.blade.php','w').write(content)
print("  Sidebar updated.")
PYEOF

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

echo ""
echo "=============================================="
echo "  DEPLOY COMPLETE!"
echo "=============================================="
echo ""
echo "  New Settings Tabs:"
echo "  ✅ General      — unchanged"
echo "  ✅ Accounting   — + Negative Cash/Bank guard"
echo "                   + Voucher Approval toggle"
echo "  ✅ Inventory    — NEW TAB with 6 guards:"
echo "     - Allow Negative Inventory"
echo "     - Use Multi-Warehouse"
echo "     - Use Manufacturing"
echo "     - Use Serial Number"
echo "     - Use Lot Number"
echo "     - Use FIFO Valuation"
echo "  ✅ AR & AP      — NEW TAB with:"
echo "     - Use Price Levels"
echo "     - Customer Aging Basis"
echo "     - Vendor Aging Basis"
echo "  ✅ System       — unchanged"
echo ""
echo "  Visit: duiclick.com/settings/inventory"
echo "         duiclick.com/settings/arap"
echo "=============================================="
