<?php
if (!hasRole('superadmin')) {
    header("Location: " . url('dashboard', ['error' => 'unauthorized']));
    exit;
}
?>

<div class="card animate-fade-in" style="margin-bottom: 2rem;">
    <div class="card-header" style="border-bottom: 1px solid var(--border); padding-bottom: 1.5rem; margin-bottom: 1.5rem;">
        <h2 class="card-title" style="font-size: 1.5rem; font-weight: 700; color: var(--text-main); display: flex; align-items: center; gap: 0.75rem;">
            <i class="fas fa-envelope" style="color: var(--primary);"></i>
            Email / SMTP
        </h2>
        <p class="card-subtitle" style="color: var(--text-muted); font-size: 0.875rem;">Configure global SMTP settings for system outgoing mail</p>
    </div>
    
    <div class="card-body">
        <form id="smtp-settings-form" onsubmit="saveSmtpSettings(event)">
            <input type="hidden" id="smtp-id" name="id">
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 1.5rem;">
                <div class="form-group">
                    <label class="form-label" style="text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; font-weight: 700;">SMTP Host <span class="required-mark">*</span></label>
                    <input type="text" id="smtp-host" name="smtp_host" class="form-control" placeholder="mail.nexovaitsolutions.com" required>
                </div>
                <div class="form-group">
                    <label class="form-label" style="text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; font-weight: 700;">SMTP Port <span class="required-mark">*</span></label>
                    <input type="number" id="smtp-port" name="smtp_port" class="form-control" placeholder="465" required>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 1.5rem;">
                <div class="form-group">
                    <label class="form-label" style="text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; font-weight: 700;">SMTP Username <span class="required-mark">*</span></label>
                    <input type="text" id="smtp-username" name="smtp_username" class="form-control" placeholder="nexserve@nexovaitsolutions.com" required>
                </div>
                <div class="form-group">
                    <label class="form-label" style="text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; font-weight: 700;">SMTP Password <span class="required-mark">*</span></label>
                    <input type="password" id="smtp-password" name="smtp_password" class="form-control" placeholder="••••••••••••" required>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; margin-bottom: 1.5rem;">
                <div class="form-group">
                    <label class="form-label" style="text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; font-weight: 700;">From Email</label>
                    <input type="email" id="smtp-from-email" name="from_email" class="form-control" placeholder="defaults to company profile email">
                </div>
                <div class="form-group">
                    <label class="form-label" style="text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; font-weight: 700;">From Name</label>
                    <input type="text" id="smtp-from-name" name="from_name" class="form-control" placeholder="NexServe">
                </div>
            </div>

            <div style="display: flex; justify-content: flex-end; gap: 1rem; border-top: 1px solid var(--border); padding-top: 1.5rem;">
                <button type="button" onclick="testSmtpConnection()" id="btn-test-smtp" class="btn" style="background: var(--bg-dark); color: var(--text-main);">
                    <i class="fas fa-plug"></i> Test Connection
                </button>
                <button type="submit" id="btn-save-smtp" class="btn btn-primary">
                    <i class="fas fa-save"></i> Save Settings
                </button>
            </div>
        </form>
    </div>
</div>

<div class="card animate-fade-in">
    <div class="card-header" style="border-bottom: 1px solid var(--border); padding-bottom: 1.5rem; margin-bottom: 1.5rem;">
        <h2 class="card-title" style="font-size: 1.5rem; font-weight: 700; color: var(--text-main);">System Settings</h2>
        <p class="card-subtitle" style="color: var(--text-muted); font-size: 0.875rem;">Manage global system configurations and maintenance</p>
    </div>
    
    <div class="card-body">
        <div class="settings-section">
            <h3 style="color: var(--danger); margin-bottom: 1.25rem; display: flex; align-items: center; gap: 0.75rem; font-size: 1.1rem; font-weight: 600;">
                <i class="fas fa-biohazard"></i>
                Danger Zone
            </h3>
            
            <div style="background: rgba(239, 68, 68, 0.03); border: 1px solid rgba(239, 68, 68, 0.15); padding: 1.5rem; border-radius: 16px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 1.5rem;">
                <div style="flex: 1; min-width: 300px;">
                    <h4 style="color: var(--danger); margin-bottom: 0.5rem; font-weight: 600;">Truncate Database</h4>
                    <p style="color: var(--text-muted); font-size: 0.9rem; line-height: 1.5;">
                        This will permanently delete all data from all tables (including Users, Companies, and Orders), reset auto-incrementing IDs, and clear all indexes. 
                        <strong style="color: var(--danger);">This action is irreversible and cannot be undone.</strong>
                    </p>
                </div>
                <button onclick="confirmTruncate()" class="btn btn-danger-action">
                    <i class="fas fa-trash-can"></i> Truncate Database
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', loadSmtpSettings);

async function loadSmtpSettings() {
    try {
        const res = await fetch(window.APP_CONFIG.BASE_PATH + 'api/superadmin.php?action=list&table=smtp_settings');
        const json = await res.json();
        if (json.success && json.data && json.data.length > 0) {
            const settings = json.data[0];
            document.getElementById('smtp-id').value = settings.id;
            document.getElementById('smtp-host').value = settings.smtp_host;
            document.getElementById('smtp-port').value = settings.smtp_port;
            document.getElementById('smtp-username').value = settings.smtp_username;
            document.getElementById('smtp-password').value = settings.smtp_password;
            document.getElementById('smtp-from-email').value = settings.from_email || '';
            document.getElementById('smtp-from-name').value = settings.from_name || '';
        }
    } catch (e) {
        console.error("Failed to load SMTP settings:", e);
    }
}

async function saveSmtpSettings(e) {
    e.preventDefault();
    const btn = document.getElementById('btn-save-smtp');
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.classList.add('btn-loading');

    const data = {
        id: document.getElementById('smtp-id').value || null,
        smtp_host: document.getElementById('smtp-host').value.trim(),
        smtp_port: parseInt(document.getElementById('smtp-port').value),
        smtp_username: document.getElementById('smtp-username').value.trim(),
        smtp_password: document.getElementById('smtp-password').value,
        from_email: document.getElementById('smtp-from-email').value.trim(),
        from_name: document.getElementById('smtp-from-name').value.trim()
    };

    try {
        const res = await fetch(window.APP_CONFIG.BASE_PATH + 'api/superadmin.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'save',
                table: 'smtp_settings',
                data: data
            })
        });
        const json = await res.json();
        if (json.success) {
            alert("SMTP Settings saved successfully.");
            loadSmtpSettings();
        } else {
            alert("Error: " + json.message);
        }
    } catch (err) {
        console.error(err);
        alert("An unexpected error occurred while saving.");
    } finally {
        btn.disabled = false;
        btn.classList.remove('btn-loading');
        btn.innerHTML = originalHTML;
    }
}

async function testSmtpConnection() {
    const btn = document.getElementById('btn-test-smtp');
    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.classList.add('btn-loading');

    const data = {
        smtp_host: document.getElementById('smtp-host').value.trim(),
        smtp_port: parseInt(document.getElementById('smtp-port').value),
        smtp_username: document.getElementById('smtp-username').value.trim(),
        smtp_password: document.getElementById('smtp-password').value,
        from_email: document.getElementById('smtp-from-email').value.trim(),
        from_name: document.getElementById('smtp-from-name').value.trim()
    };

    try {
        const res = await fetch(window.APP_CONFIG.BASE_PATH + 'api/superadmin.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'test_smtp',
                smtp_host: data.smtp_host,
                smtp_port: data.smtp_port,
                smtp_username: data.smtp_username,
                smtp_password: data.smtp_password,
                from_email: data.from_email,
                from_name: data.from_name
            })
        });
        const json = await res.json();
        if (json.success) {
            alert("Connection successful! Test email has been sent.");
        } else {
            alert("Connection failed: " + json.message);
        }
    } catch (err) {
        console.error(err);
        alert("An unexpected error occurred while testing connection.");
    } finally {
        btn.disabled = false;
        btn.classList.remove('btn-loading');
        btn.innerHTML = originalHTML;
    }
}

function confirmTruncate() {
    if (confirm("CRITICAL WARNING: Are you absolutely sure you want to TRUNCATE the entire database? This will delete EVERYTHING. This action is IRREVERSIBLE.")) {
        if (confirm("FINAL CONFIRMATION: Are you REALLY sure? All data will be wiped. Click OK to proceed.")) {
            truncateDatabase();
        }
    }
}

async function truncateDatabase() {
    const btn = document.querySelector('.btn-danger-action');
    const originalContent = btn.innerHTML;
    
    try {
        btn.disabled = true;
        btn.classList.add('btn-loading');
        
        const response = await fetch(window.APP_CONFIG.BASE_PATH + 'api/superadmin.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'truncate_database'
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert("Database truncated successfully. All data has been cleared. You will be logged out now.");
            window.location.href = window.APP_CONFIG.BASE_PATH + 'logout.php';
        } else {
            alert("Error: " + result.message);
            btn.disabled = false;
            btn.classList.remove('btn-loading');
            btn.innerHTML = originalContent;
        }
    } catch (error) {
        console.error('Error:', error);
        alert("An error occurred while truncating the database.");
        btn.disabled = false;
        btn.classList.remove('btn-loading');
        btn.innerHTML = originalContent;
    }
}
</script>

<style>
.btn-danger-action {
    background: var(--danger);
    color: white !important;
    padding: 0.75rem 1.5rem;
    border-radius: 12px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: var(--transition);
    display: flex;
    align-items: center;
    gap: 0.5rem;
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
}

.btn-danger-action:hover {
    background: #dc2626;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(239, 68, 68, 0.3);
}

.btn-danger-action:active {
    transform: translateY(0);
}

.btn-danger-action:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
}

/* Reusing the btn-loading animation from style.css */
.btn-loading::after {
    border-top-color: white !important;
}
</style>
