<?php
// ============================================================
//  admin/email-account-edit.php — add or edit an email account
// ============================================================
//
//  Two POST actions:
//   - save        → validate, store, redirect to list
//   - test_imap   → run IMAP login test, redisplay with result
//   - test_smtp   → run SMTP login test, redisplay with result
//
//  Passwords use a "keep existing if blank" pattern: edit form
//  shows empty password fields; if you leave them empty on save,
//  the existing encrypted password is preserved.
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/email_crypto.php';
require_once __DIR__ . '/../includes/imap_client.php';
auth_require_super_admin();

$me = auth_admin_user();

$id  = (int)($_GET['id'] ?? 0);
$acct = $id ? db_row('SELECT * FROM email_accounts WHERE id=:id', ['id' => $id]) : null;
if ($id && !$acct) { http_response_code(404); exit('Account not found.'); }

$error    = '';
$test_msg = '';
$test_ok  = null;     // null = haven't tested; true/false after a test

// ── POST handlers ───────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? 'save';

    // Build an in-memory account row from the form (used by test or save)
    $form = [
        'display_name'   => trim((string)($_POST['display_name'] ?? '')),
        'email_address'  => trim((string)($_POST['email_address'] ?? '')),
        'colour'         => trim((string)($_POST['colour'] ?? '#6366f1')),
        'imap_host'      => trim((string)($_POST['imap_host'] ?? '')),
        'imap_port'      => (int)($_POST['imap_port'] ?? 993),
        'imap_encryption'=> (string)($_POST['imap_encryption'] ?? 'ssl'),
        'imap_username'  => trim((string)($_POST['imap_username'] ?? '')),
        'imap_password'  => (string)($_POST['imap_password'] ?? ''),
        'imap_sent_folder'=> trim((string)($_POST['imap_sent_folder'] ?? 'Sent')),
        'smtp_host'      => trim((string)($_POST['smtp_host'] ?? '')),
        'smtp_port'      => (int)($_POST['smtp_port'] ?? 465),
        'smtp_encryption'=> (string)($_POST['smtp_encryption'] ?? 'ssl'),
        'smtp_username'  => trim((string)($_POST['smtp_username'] ?? '')),
        'smtp_password'  => (string)($_POST['smtp_password'] ?? ''),
        'smtp_from_name' => trim((string)($_POST['smtp_from_name'] ?? '')),
    ];

    // For tests / save: if pwd field is blank and we're editing, reuse existing encrypted
    $imap_pwd_for_use = $form['imap_password'] !== ''
        ? $form['imap_password']
        : ($acct['imap_password'] ?? '');
    $smtp_pwd_for_use = $form['smtp_password'] !== ''
        ? $form['smtp_password']
        : ($acct['smtp_password'] ?? '');

    // For test functions we need decrypted-or-plaintext password handed in as if
    // it were already in storage form. encrypt_if_needed makes both cases work.
    $test_acct = $form;
    $test_acct['imap_password'] = email_encrypt_if_needed($imap_pwd_for_use);
    $test_acct['smtp_password'] = email_encrypt_if_needed($smtp_pwd_for_use);

    if ($action === 'test_imap') {
        $r = imc_test_imap($test_acct);
        $test_ok  = $r['ok'];
        $test_msg = 'IMAP: ' . $r['message'];
    } elseif ($action === 'test_smtp') {
        $r = imc_test_smtp($test_acct);
        $test_ok  = $r['ok'];
        $test_msg = 'SMTP: ' . $r['message'];
    } elseif ($action === 'save') {
        // Validate
        if ($form['display_name'] === '')                  $error = 'Display name is required.';
        elseif (!filter_var($form['email_address'], FILTER_VALIDATE_EMAIL))
                                                           $error = 'Email address is not valid.';
        elseif ($form['imap_host'] === '' || $form['imap_username'] === '')
                                                           $error = 'IMAP host and username are required.';
        elseif ($form['smtp_host'] === '' || $form['smtp_username'] === '')
                                                           $error = 'SMTP host and username are required.';
        elseif ($form['imap_password'] === '' && !$acct)
                                                           $error = 'IMAP password is required for a new account.';
        elseif ($form['smtp_password'] === '' && !$acct)
                                                           $error = 'SMTP password is required for a new account.';

        if (!$error) {
            // Check uniqueness on email_address (excluding self)
            $dupe = db_row(
                'SELECT id FROM email_accounts WHERE email_address = :e AND id != :id',
                ['e' => $form['email_address'], 'id' => $id ?: 0]
            );
            if ($dupe) $error = 'Another account already uses this email address.';
        }

        if (!$error) {
            $payload = [
                'display_name'    => mb_substr($form['display_name'], 0, 120),
                'email_address'   => mb_substr(strtolower($form['email_address']), 0, 190),
                'colour'          => mb_substr($form['colour'], 0, 20),
                'imap_host'       => mb_substr($form['imap_host'], 0, 190),
                'imap_port'       => max(1, min(65535, $form['imap_port'])),
                'imap_encryption' => in_array($form['imap_encryption'], ['ssl','tls','none'], true) ? $form['imap_encryption'] : 'ssl',
                'imap_username'   => mb_substr($form['imap_username'], 0, 190),
                'imap_sent_folder'=> mb_substr($form['imap_sent_folder'] ?: 'Sent', 0, 190),
                'smtp_host'       => mb_substr($form['smtp_host'], 0, 190),
                'smtp_port'       => max(1, min(65535, $form['smtp_port'])),
                'smtp_encryption' => in_array($form['smtp_encryption'], ['ssl','tls','none'], true) ? $form['smtp_encryption'] : 'ssl',
                'smtp_username'   => mb_substr($form['smtp_username'], 0, 190),
                'smtp_from_name'  => $form['smtp_from_name'] !== '' ? mb_substr($form['smtp_from_name'], 0, 120) : null,
            ];

            // Only update passwords if a new one was given
            if ($form['imap_password'] !== '') {
                $payload['imap_password'] = email_encrypt($form['imap_password']);
            }
            if ($form['smtp_password'] !== '') {
                $payload['smtp_password'] = email_encrypt($form['smtp_password']);
            }

            if ($acct) {
                db_update('email_accounts', $id, $payload);
                $new_id = $id;
            } else {
                $new_id = db_insert('email_accounts', $payload);
            }

            // Assigned users
            $assigned = array_map('intval', $_POST['users'] ?? []);
            db_exec('DELETE FROM email_account_users WHERE account_id=:id', ['id' => $new_id]);
            foreach ($assigned as $uid) {
                if ($uid > 0) {
                    db_insert('email_account_users', [
                        'account_id' => $new_id,
                        'user_id'    => $uid,
                        'can_send'   => 1,
                    ]);
                }
            }

            header('Location: email-accounts.php?msg=' . urlencode($acct ? 'Account updated.' : 'Account created.'));
            exit;
        }
    }

    // If we got here without redirect, fall through to re-render with form data
    if (!$acct) $acct = [];
    foreach ($form as $k => $v) $acct[$k] = $v;
    if (!isset($acct['id'])) $acct['id'] = $id;
}

$page_title = $acct ? 'Edit email account' : 'New email account';
require __DIR__ . '/_guard.php';

// Lookups for form
$admin_users = db_all("SELECT id, first_name, last_name, email FROM admin_users WHERE active=1 ORDER BY first_name, last_name");
$assigned_user_ids = $id ? array_column(
    db_all('SELECT user_id FROM email_account_users WHERE account_id=:id', ['id' => $id]),
    'user_id'
) : [(int)$me['id']];  // default: assign the creator

// On POST re-render, the chosen users come from $_POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['users']) && is_array($_POST['users'])) {
    $assigned_user_ids = array_map('intval', $_POST['users']);
}

// Try to list folders (for the Sent dropdown) if creds are configured
$folders_list = [];
$folders_error = '';
if (!empty($acct) && !empty($acct['imap_host']) && !empty($acct['imap_username'])) {
    try {
        $probe_acct = $acct;
        // If passwords aren't encrypted yet (POST re-render), encrypt them
        $probe_acct['imap_password'] = email_encrypt_if_needed($acct['imap_password'] ?? '');
        if ($probe_acct['imap_password'] !== '') {
            $folders_list = imc_list_folders($probe_acct);
        }
    } catch (Throwable $e) {
        $folders_error = $e->getMessage();
    }
}

// Pre-fill values
$v = function($key, $default = '') use ($acct) {
    return htmlspecialchars((string)($acct[$key] ?? $default));
};

$settings_section = 'email_accts';
require __DIR__ . '/_settings_open.php';
?>

<style>
.eae-form{max-width:780px;margin:0 auto;}
.eae-form fieldset{
    border:1px solid var(--line);border-radius:8px;padding:1.25rem 1.5rem;margin:0 0 1.25rem;
    background:#fff;
}
.eae-form legend{font-weight:700;padding:0 .5rem;}
.eae-form .row{margin-bottom:.9rem;}
.eae-form .row-grid{display:grid;grid-template-columns:2fr 1fr 1fr;gap:.75rem;}
@media(max-width:600px){.eae-form .row-grid{grid-template-columns:1fr;}}
.eae-form label{font-weight:600;font-size:.84rem;display:block;margin-bottom:.25rem;}
.eae-form input[type="text"],
.eae-form input[type="email"],
.eae-form input[type="password"],
.eae-form input[type="number"],
.eae-form input[type="color"],
.eae-form select{
    width:100%;padding:.55rem .7rem;border:1px solid var(--line);border-radius:5px;
    font-size:.92rem;font-family:inherit;
}
.eae-form .hint{font-size:.76rem;color:var(--ink-muted);margin-top:.2rem;}
.eae-form .users-list{
    display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:.4rem;
}
.eae-form .users-list label{
    font-weight:normal;font-size:.88rem;background:var(--surface-alt);
    padding:.45rem .7rem;border-radius:4px;cursor:pointer;display:flex;align-items:center;gap:.4rem;
}
.eae-form .test-result{
    padding:.6rem .85rem;border-radius:5px;font-size:.85rem;margin-top:.5rem;
}
.eae-form .test-result.ok{background:#ecfdf5;color:#065f46;border:1px solid #6ee7b7;}
.eae-form .test-result.bad{background:#fef2f2;color:#991b1b;border:1px solid #fca5a5;}
.eae-form .test-btn{
    padding:.4rem .85rem;font-size:.82rem;background:#fff;border:1px solid var(--line);
    border-radius:5px;cursor:pointer;font-family:inherit;
}
.eae-form .test-btn:hover{background:#f5f3ee;}
.eae-form .footer-actions{display:flex;gap:.5rem;flex-wrap:wrap;}
</style>

<div class="eae-form">

<p style="margin:0 0 .75rem;">
    <a href="email-accounts.php" style="color:var(--ink-muted);text-decoration:none;font-size:.88rem;">← Back to accounts</a>
</p>

<h1 style="margin:0 0 1.25rem;"><?= $acct && !empty($acct['id']) ? 'Edit account' : 'New email account' ?></h1>

<?php if ($error): ?>
    <div class="alert alert-error" style="margin-bottom:1rem;"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if ($test_msg !== ''): ?>
    <div class="test-result <?= $test_ok ? 'ok' : 'bad' ?>" style="margin-bottom:1rem;">
        <?= $test_ok ? '✓' : '✗' ?> <?= htmlspecialchars($test_msg) ?>
    </div>
<?php endif; ?>

<form method="post">
    <?= csrf_field() ?>

    <fieldset>
        <legend>Account</legend>

        <div class="row">
            <label for="display_name">Display name</label>
            <input type="text" id="display_name" name="display_name" required maxlength="120"
                   value="<?= $v('display_name') ?>" placeholder="e.g. Info Mailbox">
            <p class="hint">Shown as the tab label in the email portal.</p>
        </div>

        <div class="row-grid">
            <div>
                <label for="email_address">Email address</label>
                <input type="email" id="email_address" name="email_address" required maxlength="190"
                       value="<?= $v('email_address') ?>" placeholder="info@buylocallowveld.co.za">
            </div>
            <div>
                <label for="colour">Tab colour</label>
                <input type="color" id="colour" name="colour" value="<?= $v('colour', '#6366f1') ?>">
            </div>
            <div>
                <label for="smtp_from_name">From name (optional)</label>
                <input type="text" id="smtp_from_name" name="smtp_from_name" maxlength="120"
                       value="<?= $v('smtp_from_name') ?>" placeholder="Buy Local Lowveld">
            </div>
        </div>
    </fieldset>

    <fieldset>
        <legend>IMAP (incoming)</legend>

        <div class="row-grid">
            <div>
                <label for="imap_host">Host</label>
                <input type="text" id="imap_host" name="imap_host" required maxlength="190"
                       value="<?= $v('imap_host') ?>" placeholder="mail.example.co.za">
            </div>
            <div>
                <label for="imap_port">Port</label>
                <input type="number" id="imap_port" name="imap_port" min="1" max="65535"
                       value="<?= $v('imap_port', '993') ?>">
            </div>
            <div>
                <label for="imap_encryption">Encryption</label>
                <select id="imap_encryption" name="imap_encryption">
                    <option value="ssl"  <?= ($acct['imap_encryption'] ?? 'ssl')==='ssl'?'selected':'' ?>>SSL (993)</option>
                    <option value="tls"  <?= ($acct['imap_encryption'] ?? '')==='tls'?'selected':'' ?>>TLS / STARTTLS (143)</option>
                    <option value="none" <?= ($acct['imap_encryption'] ?? '')==='none'?'selected':'' ?>>None (143)</option>
                </select>
            </div>
        </div>

        <div class="row-grid" style="grid-template-columns:1fr 1fr;">
            <div>
                <label for="imap_username">Username</label>
                <input type="text" id="imap_username" name="imap_username" required maxlength="190"
                       value="<?= $v('imap_username') ?>" autocomplete="off">
            </div>
            <div>
                <label for="imap_password">Password</label>
                <input type="password" id="imap_password" name="imap_password" autocomplete="new-password"
                       placeholder="<?= !empty($acct['id']) ? '(unchanged)' : '' ?>">
                <?php if (!empty($acct['id'])): ?>
                    <p class="hint">Leave blank to keep the current password.</p>
                <?php endif; ?>
            </div>
        </div>

        <div class="row">
            <label for="imap_sent_folder">Sent folder</label>
            <?php
                $current_sent = $acct['imap_sent_folder'] ?? 'Sent';
                $guessed = !empty($folders_list) ? imc_guess_sent_folder($folders_list) : null;
            ?>
            <?php if (!empty($folders_list)): ?>
                <select id="imap_sent_folder" name="imap_sent_folder">
                    <?php
                    // Make sure the current value is in the list even if it
                    // doesn't match anything the server reports
                    $options = $folders_list;
                    if ($current_sent && !in_array($current_sent, $options, true)) {
                        $options[] = $current_sent;
                    }
                    sort($options, SORT_NATURAL | SORT_FLAG_CASE);
                    foreach ($options as $f):
                        $is_selected = ($f === $current_sent)
                            || ($current_sent === '' && $f === $guessed);
                    ?>
                        <option value="<?= htmlspecialchars($f) ?>" <?= $is_selected ? 'selected' : '' ?>>
                            <?= htmlspecialchars($f) ?>
                            <?= ($guessed && $f === $guessed) ? ' (auto-detected)' : '' ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <p class="hint">Folder where sent messages are saved. Auto-detected from your server's folder list.</p>
            <?php else: ?>
                <input type="text" id="imap_sent_folder" name="imap_sent_folder" maxlength="190"
                       value="<?= htmlspecialchars($current_sent) ?>">
                <p class="hint">
                    <?php if ($folders_error): ?>
                        ⚠ Couldn't list folders: <?= htmlspecialchars(mb_substr($folders_error, 0, 200)) ?><br>
                    <?php endif; ?>
                    Save once with correct IMAP credentials, then come back to pick the right Sent folder.
                    Common names: <code>Sent</code>, <code>INBOX.Sent</code>, <code>Sent Items</code>.
                </p>
            <?php endif; ?>
        </div>

        <button type="submit" name="action" value="test_imap" class="test-btn">↻ Test IMAP connection</button>
    </fieldset>

    <fieldset>
        <legend>SMTP (outgoing)</legend>

        <div class="row-grid">
            <div>
                <label for="smtp_host">Host</label>
                <input type="text" id="smtp_host" name="smtp_host" required maxlength="190"
                       value="<?= $v('smtp_host') ?>" placeholder="mail.example.co.za">
            </div>
            <div>
                <label for="smtp_port">Port</label>
                <input type="number" id="smtp_port" name="smtp_port" min="1" max="65535"
                       value="<?= $v('smtp_port', '465') ?>">
            </div>
            <div>
                <label for="smtp_encryption">Encryption</label>
                <select id="smtp_encryption" name="smtp_encryption">
                    <option value="ssl"  <?= ($acct['smtp_encryption'] ?? 'ssl')==='ssl'?'selected':'' ?>>SSL (465)</option>
                    <option value="tls"  <?= ($acct['smtp_encryption'] ?? '')==='tls'?'selected':'' ?>>TLS / STARTTLS (587)</option>
                    <option value="none" <?= ($acct['smtp_encryption'] ?? '')==='none'?'selected':'' ?>>None (25)</option>
                </select>
            </div>
        </div>

        <div class="row-grid" style="grid-template-columns:1fr 1fr;">
            <div>
                <label for="smtp_username">Username</label>
                <input type="text" id="smtp_username" name="smtp_username" required maxlength="190"
                       value="<?= $v('smtp_username') ?>" autocomplete="off">
            </div>
            <div>
                <label for="smtp_password">Password</label>
                <input type="password" id="smtp_password" name="smtp_password" autocomplete="new-password"
                       placeholder="<?= !empty($acct['id']) ? '(unchanged)' : '' ?>">
            </div>
        </div>

        <button type="submit" name="action" value="test_smtp" class="test-btn">↻ Test SMTP connection</button>
    </fieldset>

    <fieldset>
        <legend>Assigned admin users</legend>
        <p class="hint" style="margin:0 0 .75rem;">Only checked users can read messages from this mailbox.</p>
        <div class="users-list">
        <?php foreach ($admin_users as $u):
            $name = trim(($u['first_name'] ?? '').' '.($u['last_name'] ?? '')) ?: $u['email'];
            $checked = in_array((int)$u['id'], $assigned_user_ids, true);
        ?>
            <label>
                <input type="checkbox" name="users[]" value="<?= (int)$u['id'] ?>" <?= $checked?'checked':'' ?>>
                <span><?= htmlspecialchars($name) ?></span>
            </label>
        <?php endforeach; ?>
        </div>
    </fieldset>

    <div class="footer-actions">
        <button type="submit" name="action" value="save" class="btn">
            <?= !empty($acct['id']) ? 'Save changes' : 'Create account' ?>
        </button>
        <a href="email-accounts.php" class="btn btn-outline">Cancel</a>
    </div>
</form>

</div>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>