#!/bin/bash
# ============================================================
# SaaS Accounting — SMTP Test Mail Feature
# Adds:
#   - Test Mail Recipient field in SMTP section
#   - Send Test Mail button with AJAX
#   - Success / Failure message display
#   - Backend route + controller method
#
# Run: bash deploy_smtp_test.sh
# From: ~/public_html/saas-accounting/
# ============================================================
set -e
cd ~/public_html/saas-accounting

echo ""
echo "=============================================="
echo "  SMTP Test Mail Feature"
echo "=============================================="
echo ""

# ── 1. Add testSmtp method to CompanySettingsController ──────────────────────
echo "Step 1: Adding testSmtp method to controller..."
python3 << 'PYEOF'
content = open('app/Http/Controllers/Company/Settings/CompanySettingsController.php').read()

# Add use Mail and use Exception at top
if 'use Illuminate\\Support\\Facades\\Mail;' not in content:
    content = content.replace(
        'use Illuminate\\Http\\Request;',
        'use Illuminate\\Http\\Request;\nuse Illuminate\\Support\\Facades\\Mail;\nuse Exception;'
    )

# Add testSmtp method before the last closing brace
test_method = '''
    // ── SMTP Test ─────────────────────────────────────────────────────────────
    public function testSmtp(Request $request)
    {
        $request->validate([
            'smtp_host'        => 'required|string',
            'smtp_port'        => 'required|integer',
            'smtp_username'    => 'required|string',
            'smtp_password'    => 'required|string',
            'smtp_from_name'   => 'required|string',
            'smtp_from_email'  => 'required|email',
            'smtp_encryption'  => 'required|in:tls,ssl,none',
            'test_recipient'   => 'required|email',
        ]);

        // Override mail config dynamically
        config([
            'mail.default'                       => 'smtp',
            'mail.mailers.smtp.host'             => $request->smtp_host,
            'mail.mailers.smtp.port'             => (int) $request->smtp_port,
            'mail.mailers.smtp.username'         => $request->smtp_username,
            'mail.mailers.smtp.password'         => $request->smtp_password,
            'mail.mailers.smtp.encryption'       => $request->smtp_encryption === 'none' ? null : $request->smtp_encryption,
            'mail.mailers.smtp.timeout'          => 15,
            'mail.from.address'                  => $request->smtp_from_email,
            'mail.from.name'                     => $request->smtp_from_name,
        ]);

        try {
            $company   = auth()->user()->company;
            $recipient = $request->test_recipient;
            $fromName  = $request->smtp_from_name;
            $fromEmail = $request->smtp_from_email;

            Mail::raw(
                "This is a test email from {$company->name}.\\n\\n" .
                "Your SMTP configuration is working correctly.\\n\\n" .
                "Sent from: SaaS Accounting System\\n" .
                "Company: {$company->name}",
                function ($message) use ($recipient, $fromName, $fromEmail, $company) {
                    $message->to($recipient)
                            ->from($fromEmail, $fromName)
                            ->subject("Test Email from {$company->name} — SMTP Working");
                }
            );

            return response()->json([
                'success' => true,
                'message' => "Test email sent successfully to {$recipient}. Please check your inbox.",
            ]);

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to send test email: ' . $e->getMessage(),
            ], 422);
        }
    }
'''

# Insert before the last closing brace of the class
last_brace = content.rfind('}')
content = content[:last_brace] + test_method + '\n}'

open('app/Http/Controllers/Company/Settings/CompanySettingsController.php', 'w').write(content)
print("  Controller updated.")
PYEOF

# ── 2. Add test SMTP route ────────────────────────────────────────────────────
echo "Step 2: Adding test SMTP route..."
python3 << 'PYEOF'
content = open('routes/web.php').read()

old = "        Route::get('/security',   [CompanySettingsController::class, 'security'])->name('security');"
new = "        Route::post('/test-smtp', [CompanySettingsController::class, 'testSmtp'])->name('test-smtp');\n        Route::get('/security',   [CompanySettingsController::class, 'security'])->name('security');"

if 'test-smtp' not in content:
    content = content.replace(old, new)
    open('routes/web.php', 'w').write(content)
    print("  Route added.")
else:
    print("  Route already exists.")
PYEOF

# ── 3. Update the SMTP section in general.blade.php ───────────────────────────
echo "Step 3: Updating SMTP section in general settings view..."
python3 << 'PYEOF'
content = open('resources/views/settings/general.blade.php').read()

# Replace the old SMTP test button section
old_btn = """                <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>"""

new_btn = """                {{-- Test Recipient + Send Test --}}
                <div class="row g-3 mt-1">
                    <div class="col-12 col-sm-6 col-md-5">
                        <label class="form-label fw-semibold">Test Mail Recipient</label>
                        <input type="email" id="smtpTestRecipient" class="form-control"
                               placeholder="e.g. you@example.com"
                               value="{{ auth()->user()->email ?? '' }}">
                        <div class="form-text" style="font-size:11.5px">Enter an email address to receive the test mail</div>
                    </div>
                    <div class="col-12 col-sm-6 col-md-4 d-flex align-items-end pb-1">
                        <button type="button" class="btn btn-outline-primary" id="testSmtpBtn">
                            <i class="bi bi-send me-1"></i>Send Test Mail
                        </button>
                    </div>
                </div>

                {{-- Result message --}}
                <div id="smtpTestResult" class="mt-3" style="display:none"></div>"""

if 'smtpTestRecipient' not in content:
    content = content.replace(old_btn, new_btn)
    print("  SMTP section updated.")
else:
    print("  SMTP section already has test recipient.")

# Replace the old JS testSmtp handler
old_js = """// 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.';
});"""

new_js = """// SMTP Test Mail
document.getElementById('testSmtpBtn').addEventListener('click', function() {
    const btn       = this;
    const resultEl  = document.getElementById('smtpTestResult');
    const recipient = document.getElementById('smtpTestRecipient').value.trim();

    if (!recipient) {
        resultEl.style.display = '';
        resultEl.innerHTML = '<div class="alert alert-warning py-2 d-flex gap-2 align-items-center" style="font-size:13px"><i class="bi bi-exclamation-triangle flex-shrink-0"></i><div>Please enter a test mail recipient email address.</div></div>';
        return;
    }

    const host       = document.querySelector('[name="smtp_host"]').value.trim();
    const port       = document.querySelector('[name="smtp_port"]').value.trim();
    const username   = document.querySelector('[name="smtp_username"]').value.trim();
    const password   = document.getElementById('smtpPass').value.trim();
    const fromName   = document.querySelector('[name="smtp_from_name"]').value.trim();
    const fromEmail  = document.querySelector('[name="smtp_from_email"]').value.trim();
    const encryption = document.querySelector('[name="smtp_encryption"]').value;

    if (!host || !port || !username || !password || !fromEmail || !fromName) {
        resultEl.style.display = '';
        resultEl.innerHTML = '<div class="alert alert-warning py-2 d-flex gap-2 align-items-center" style="font-size:13px"><i class="bi bi-exclamation-triangle flex-shrink-0"></i><div>Please fill in all SMTP fields (Host, Port, Username, Password, From Name, From Email) before testing.</div></div>';
        return;
    }

    // Loading state
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
    btn.disabled  = true;
    resultEl.style.display = 'none';

    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    fetch('{{ route("settings.test-smtp") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': csrfToken,
            'Accept': 'application/json',
        },
        body: JSON.stringify({
            smtp_host:      host,
            smtp_port:      port,
            smtp_username:  username,
            smtp_password:  password,
            smtp_from_name: fromName,
            smtp_from_email:fromEmail,
            smtp_encryption:encryption,
            test_recipient: recipient,
        })
    })
    .then(r => r.json())
    .then(data => {
        resultEl.style.display = '';
        if (data.success) {
            resultEl.innerHTML = '<div class="alert alert-success py-2 d-flex gap-2 align-items-center" style="font-size:13px"><i class="bi bi-check-circle-fill flex-shrink-0 text-success"></i><div><strong>Success!</strong> ' + data.message + '</div></div>';
        } else {
            resultEl.innerHTML = '<div class="alert alert-danger py-2 d-flex gap-2 align-items-start" style="font-size:13px"><i class="bi bi-x-circle-fill flex-shrink-0 text-danger mt-1"></i><div><strong>Failed!</strong> ' + data.message + '</div></div>';
        }
    })
    .catch(err => {
        resultEl.style.display = '';
        resultEl.innerHTML = '<div class="alert alert-danger py-2 d-flex gap-2 align-items-center" style="font-size:13px"><i class="bi bi-x-circle-fill flex-shrink-0"></i><div><strong>Error!</strong> Could not reach the server. Please try again.</div></div>';
    })
    .finally(() => {
        btn.innerHTML = '<i class="bi bi-send me-1"></i>Send Test Mail';
        btn.disabled  = false;
    });
});"""

if 'fetch(' not in content:
    content = content.replace(old_js, new_js)
    print("  JS updated.")
else:
    print("  JS already updated.")

open('resources/views/settings/general.blade.php', 'w').write(content)
PYEOF

# ── 4. Clear cache ────────────────────────────────────────────────────────────
echo "Step 4: Clearing cache..."
php artisan view:clear
php artisan route:clear
php artisan optimize

echo ""
echo "=============================================="
echo "  DEPLOY COMPLETE!"
echo "=============================================="
echo ""
echo "  SMTP Test Mail feature added:"
echo "  ✅ Test Mail Recipient field"
echo "  ✅ Send Test Mail button (AJAX)"
echo "  ✅ Success message with green alert"
echo "  ✅ Failure message with red alert + error"
echo "  ✅ Validation: recipient + all SMTP fields"
echo "  ✅ Loading spinner during send"
echo "=============================================="
