<?php
//////////////////////////////////
// 	admin_notices ARRAY ORDER	//
// 	[0]=reports					//
// 	[1]=schedules				//
// 	[2]=defects					//
//	[3]=user creation			//
// 	[4]=system log				//
// 	[5]=						//
//////////////////////////////////

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `system` WHERE `id`='1' ") or die(mysqli_error($GLOBALS['con']));
$stmt->execute();
$r = $stmt->get_result();
$stmt->close();
$i = mysqli_fetch_array($r);
$sd = explode(',', $i['admin_notices']);
?>

<?php /// DATABASE 
?>
<!--
<table class="table table-bordered">
    <thead class="thead-dark">
        <tr>
            <th colspan="5">Database <small class="text-danger">(Altering this data incorrectly can prevent your system from loading)</small></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Username</th>
            <th>Password</th>
            <th>Master Database</th>
            <th>Company Database</th>
        </tr>
        <tr>
            <td><input id="db_username" class="form-control" type="text" name="db_username" value="<?= $i['db_username'] ?>" required></td>
            <td><input id="db_password" class="form-control" type="password" name="db_password" value="<?= $i['db_password'] ?>" required></td>
            <td><input id="db_master" class="form-control" type="text" name="db_master" value="<?= $i['db_master'] ?>" required></td>
            <td><input id="db_tables" class="form-control" type="text" name="db_tables" value="<?= $i['db_tables'] ?>" required></td>
        </tr>
        <tr>
            <td colspan="4" class="text-center"><a href="javascript:void(0)" class="btn btn-success" onclick="saveDbPrefs()"><i class="fa fa-save"></i> Save</a></td>
        </tr>
    </tbody>

</table>
-->
<div class="row">
    <div class="col-12 col-md-6">
        <!-- FULL SITE PATH -->
        <table class="table table-bordered">
            <thead class="table-dark">
                <tr>
                    <th>FULL SITE PATH <small>(No trailing /)</small></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><input id="site_path" class="form-control" type="text" name="site_path"
                            placeholder="https://yourdomain.com" value="<?= $i['site_path'] ?>" required></td>
                </tr>
                <tr>
                    <td class="text-center">
                        <a href="javascript:void(0)" class="btn btn-success waves-effect" onclick="saveSitePath()">
                            <i class="fad fa-save"></i> Save
                        </a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="col-12 col-md-6">
        <!-- Schedule Mode -->
        <table class="table table-bordered">
            <thead class="table-dark">
                <tr>
                    <th>Schedule mode</small></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <div class="form-switch">
                            <input type="checkbox" class="form-check-input" id="schedule_mode_switch"
                                name="scheduleMode" value="1" <?= $i['smode'] == '1' ? 'checked' : '' ?>>
                            <label class="form-check-label" for="schedule_mode_switch">
                                <span id="schedule_label"><?= $i['smode'] == '1' ? 'Light' : 'Default' ?></span>
                            </label>
                        </div>

                        <script>
                        // Toggle label based on switch state
                        document.getElementById('schedule_mode_switch').addEventListener('change', function() {
                            var label = document.getElementById('schedule_label');
                            label.textContent = this.checked ? 'Light' : 'Default';
                            this.value = this.checked ? '1' : '0';
                        });
                        </script>
                    </td>
                </tr>
                <tr>
                    <td class="text-center">
                        <a href="javascript:void(0)" class="btn btn-success waves-effect" onclick="saveSMode()">
                            <i class="fad fa-save"></i> Save
                        </a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="col-12">
        <!-- MAILER -->
        <table class="table table-bordered">
            <thead class="table-dark">
                <tr>
                    <th colspan="5">Email Server <small>(Required for Email sending)</small>
                        <div class="float-end">
                            <span id="verified" class="badge bg-secondary"></span>
                        </div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th>Mail server</th>
                    <th>Mail Username</th>
                    <th>Mail Password</th>
                    <th>Mail "From" Address</th>
                    <th>Mail "From" Name</th>
                </tr>
                <tr>
                    <td><input id="mail_host" class="form-control" type="text" name="mail_host"
                            placeholder="mail.yourdomain.com" value="<?= $i['mail_host'] ?>" required></td>
                    <td><input id="mail_username" class="form-control" type="text" name="mail_username"
                            placeholder="full username" value="<?= $i['mail_username'] ?>" required></td>
                    <td><input id="mail_password" class="form-control" type="text" name="mail_password"
                            value="<?= $i['mail_password'] ?>" required></td>
                    <td><input id="mail_from" class="form-control" type="text" name="mail_from"
                            placeholder="noreply@yourdomain.com" value="<?= $i['mail_from'] ?>" required></td>
                    <td><input id="mail_from_name" class="form-control" type="text" name="mail_from_name"
                            placeholder="Your Business Name" value="<?= $i['mail_from_name'] ?>" required></td>
                </tr>
                <tr>
                    <th>Test Email Address</th>
                    <th>Test Email Name</th>
                    <th colspan="3"></th>
                </tr>
                <tr>
                    <td><input id="mail_test_address" class="form-control" type="text" name="mail_test_address"
                            placeholder="your email address" value="<?= $i['mail_test_address'] ?>" required></td>
                    <td><input id="mail_test_name" class="form-control" type="text" name="mail_test_name"
                            placeholder="Your Name" value="<?= $i['mail_test_name'] ?>" required></td>
                    <td colspan="3" class="text-center">
                        <a href="javascript:void(0)" class="btn btn-success waves-effect" onclick="saveMailPrefs()"><i
                                class="fad fa-save"></i> Save</a>
                        <a href="javascript:void(0)" class="btn btn-info waves-effect" onclick="testMailPrefs()"><i
                                class="fad fa-envelope-open-text"></i> Test</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="col-12 col-md-4">
        <!-- Default Email Address -->
        <table class="table table-bordered">
            <thead class="table-dark">
                <tr>
                    <th colspan="2">Default Email address</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th colspan="2">
                        <blockquote>This is used as the auto-reply for all outgoing emails by default. It also can be
                            used to auto-receive copies of emails.<br>
                            <span class="text-danger"><small>If <strong>not enabled</strong>, no copies will be sent and
                                    all emails will be sent out as "no-reply@yourdomain.co.uk"</small></span>
                        </blockquote>
                    </th>
                </tr>
                <tr>
                    <td style="width:150px">Enabled
                        <input class="form-check-input" type="checkbox" id="default_email_status"
                            <?= $sd['0'] == 1 ? 'checked' : '' ?>
                            onChange="checkEmail();updateSetting('default_email_status','toggle')">
                    </td>
                    <td>
                        <div class="input-group">
                            <input class="form-control" type="email" id="default_email"
                                placeholder="email address for all responses" value="<?= $i['default_email'] ?>"
                                onKeyUp="valEml()">
                            <button class="btn btn-success m-0 px-3 py-2 waves-effect" type="button"
                                onClick="updateSetting('default_email','string')">
                                <i class="fad fa-save"></i>
                            </button>
                        </div>
                        <br><span id="default_email_save" class="text-success" style="display:none">Saved</span>
                        <p id="default_email_error" class="text-danger"></p>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="col-12 col-md-4">
        <!-- Admin Copy -->
        <table class="table table-bordered">
            <thead class="table-dark">
                <tr>
                    <th colspan="2">Admin copy</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="form-check">
                        <input class="form-check-input" type="checkbox" id="opt_report"
                            <?= $sd['1'] == 1 ? 'checked' : '' ?> onChange="updateSetting('opt_report','toggle')">
                        <label class="form-check-label" for="opt_report"></label>
                    </td>
                    <td>Reports <span class="text-success float-end" id="opt_report_save"
                            style="display:none">Saved</span></td>
                </tr>
                <!-- Similar rows for schedules, defects, user creation, system log -->
            </tbody>
        </table>
    </div>
    <div class="col-12 col-md-4">
        <!-- Default reporting email subject -->
        <table class="table table-bordered">
            <thead class="table-dark">
                <tr>
                    <th colspan="2">Default reporting email subject</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="2">
                        <div class="input-group">
                            <input class="form-control" type="text" id="default_email_report_subject"
                                value="Your <?= strtoupper($_SESSION['company']) ?> inspection reports"
                                value="<?= $i['default_email_report_subject'] ?>">
                            <button class="btn btn-success m-0 px-3 py-2 waves-effect" type="button"
                                onClick="updateSetting('default_email_report_subject','string')">
                                <i class="fad fa-save"></i>
                            </button>
                        </div>
                        <span id="default_email_report_subject_save" class="text-success"
                            style="display:none">Saved</span>
                        <p id="default_email_error" class="text-danger"></p>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <!-- Default reporting email message -->
    <table class="table table-bordered">
        <thead class="table-dark">
            <tr>
                <th colspan="2">Default reporting email message</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td colspan="2">
                    <div class="input-group">
                        <input class="form-control" type="text" id="default_email_report_message"
                            value="<?= $i['default_email_report_message'] ?>">
                        <button class="btn btn-success m-0 px-3 py-2 waves-effect" type="button"
                            onClick="updateSetting('default_email_report_message','string')">
                            <i class="fad fa-save"></i>
                        </button>
                    </div>
                    <span id="default_email_report_message_save" class="text-success" style="display:none">Saved</span>
                    <p id="default_email_error" class="text-danger"></p>
                </td>
            </tr>
        </tbody>
    </table>

</div>
<script>
<?php if ($i['mail_check'] == 1) { ?>
$('#verified').html('<span style="color:green">Verified</span>')
<?php } else { ?>$('#verified').html('<span style="color:red">Not Verified</span>')
<?php } ?>

// Save database preferences
function saveDbPrefs() {
    const u = document.getElementById('db_username').value;
    const p = document.getElementById('db_password').value;
    const t = document.getElementById('db_tables').value;
    const m = document.getElementById('db_master').value;

    if (!u || !p || !t) {
        showResponse('danger', 'You must complete all fields');
    } else {
        const params = new URLSearchParams({
            FCN: 'updateDB',
            db_username: u,
            db_password: p,
            db_tables: t,
            db_master: m
        });

        fetch(ROOT_URL + '/includes/master/system_functions.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.text())
            .then(res => {
                if (res.trim() === "success") {
                    showResponse('success', 'The database settings have been saved');
                } else {
                    console.log(res);
                }
            });
    }
}

// Save site path preferences
function saveSitePath() {
    const s = document.getElementById('site_path').value;

    if (!s) {
        showResponse('danger', 'You must complete all fields');
    } else {
        const params = new URLSearchParams({
            FCN: 'updateSitePath',
            site_path: s,
            tenant: TENANT_URL
        });

        fetch(ROOT_URL + '/includes/master/system_functions.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.text())
            .then(res => {
                if (res.trim() === "success") {
                    showResponse('success', 'The site path settings have been saved');
                } else {
                    console.log(res);
                }
            });
    }
}

// Save mail preferences
function saveMailPrefs() {
    const h = document.getElementById('mail_host').value;
    const u = document.getElementById('mail_username').value;
    const p = document.getElementById('mail_password').value;
    const f = document.getElementById('mail_from').value;
    const fn = document.getElementById('mail_from_name').value;
    const t = document.getElementById('mail_test_address').value;
    const tn = document.getElementById('mail_test_name').value;

    if (!h || !u || !p || !f || !fn || !t || !tn) {
        showResponse('danger', 'You must complete all fields');
    } else {
        const params = new URLSearchParams({
            FCN: 'updateMailer',
            mail_host: h,
            mail_username: u,
            mail_password: p,
            mail_from: f,
            mail_from_name: fn,
            mail_test_address: t,
            mail_test_name: tn,
            tenant: TENANT_URL
        });

        fetch(ROOT_URL + '/includes/master/system_functions.php', {
                method: 'POST',
                body: params,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.text())
            .then(res => {
                if (res.trim() === "success") {
                    showResponse('success', 'The mail settings have been saved');
                } else {
                    console.log(res);
                }
            });
    }
}

// Test mail preferences
function testMailPrefs() {
    const h = document.getElementById('mail_host').value;
    const u = document.getElementById('mail_username').value;
    const p = document.getElementById('mail_password').value;
    const f = document.getElementById('mail_from').value;
    const fn = document.getElementById('mail_from_name').value;
    const t = document.getElementById('mail_test_address').value;
    const tn = document.getElementById('mail_test_name').value;

    if (!h || !u || !p || !f || !fn || !t || !tn) {
        showResponse('danger', 'You must complete all fields');
        return;
    }

    const params = new URLSearchParams({
        FCN: 'testMailer',
        mail_host: h,
        mail_username: u,
        mail_password: p,
        mail_from: f,
        mail_from_name: fn,
        mail_test_address: t,
        mail_test_name: tn,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(res => {
            if (res.trim() === "success") {
                showResponse('success', 'The mail settings have been accepted');
                document.getElementById('verified').innerHTML = '<span style="color:green">Verified</span>';
                saveMailPrefs();
            } else {
                document.getElementById('verified').innerHTML =
                    `<span style="color:red">Not Verified: ${res}</span>`;
            }
        });
}

// Email validation check
function checkEmail() {
    const emailStatus = document.getElementById('default_email_status');
    const emailField = document.getElementById('default_email');
    const emailError = document.getElementById('default_email_error');
    const emailButton = document.getElementById('default_email_button');

    if (emailStatus.checked) {
        if (!emailField.value) {
            emailField.style.borderColor = '#f00';
            emailError.textContent = 'You must add a valid email address to enable this feature';
            emailButton.classList.add('disabled');
        } else {
            valEml();
        }
    } else {
        emailField.style.borderColor = '';
        emailField.value = '';
        emailError.textContent = '';
        emailButton.classList.add('disabled');
        updateSetting('default_email', 'string');
    }
}

// Validate email format
function valEml() {
    const sEmail = document.getElementById('default_email').value;
    const emailError = document.getElementById('default_email_error');
    const emailField = document.getElementById('default_email');
    const emailButton = document.getElementById('default_email_button');

    if (validatedEmail(sEmail)) {
        emailError.textContent = 'Email address accepted';
        emailError.style.color = 'green';
        emailField.style.borderColor = 'green';
        emailButton.classList.remove('disabled');
    } else {
        emailError.textContent = 'You must add a valid email address to enable this feature';
        emailField.style.borderColor = '#f00';
        emailError.style.color = '#f00';
        emailButton.classList.add('disabled');
    }
}

// Update settings
function updateSetting(i, t) {
    let state;
    if (t === "toggle") {
        state = [
            document.getElementById('default_email_status').checked ? '1' : '0',
            document.getElementById('opt_report').checked ? '1' : '0',
            document.getElementById('opt_schedule').checked ? '1' : '0',
            document.getElementById('opt_defect').checked ? '1' : '0',
            document.getElementById('opt_user').checked ? '1' : '0',
            document.getElementById('opt_system').checked ? '1' : '0'
        ].join(',');
        i = 'admin_notices';
    } else if (t === "string") {
        state = document.getElementById(i).value;
    }

    const params = new URLSearchParams({
        FCN: 'update',
        col: i,
        val: state,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(() => {
            document.getElementById(`${i}_save`).style.display = 'inline';
            setTimeout(() => {
                document.getElementById(`${i}_save`).style.display = 'none';
            }, 1000);
        });
}

// Save schedule mode
function saveSMode() {
    const m = document.querySelector('input[name="sheduleMode"]:checked').value;

    const params = new URLSearchParams({
        FCN: 'saveSMode',
        mode: m,
        tenant: TENANT_URL
    });

    fetch(ROOT_URL + '/includes/master/system_functions.php', {
            method: 'POST',
            body: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.text())
        .then(res => {
            if (res.trim() === "success") {
                showResponse('success', 'The schedule settings have been saved');
            } else {
                console.log(res);
            }
        });
}

// Update navigation box content
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">System Setup</li>';
</script>