<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../config/encrypt.php';
$user = requireAuth();
$db   = getDB();

$action   = post('action', 'list');
$clientId = (int)post('client_id', 0);

if ($action === 'list') {
    if (!$clientId) apiError('Client ID required.', 422);
    $stmt = $db->prepare("SELECT * FROM client_email_accounts WHERE client_id = ? ORDER BY email_address");
    $stmt->execute([$clientId]);
    $rows = $stmt->fetchAll();
    foreach ($rows as &$r) {
        $r['password_plain'] = !empty($r['password_enc']) ? ewDecrypt($r['password_enc']) : '';
        unset($r['password_enc']);
    }
    apiSuccess(['accounts' => $rows]);
}

if ($action === 'delete') {
    $id = (int)post('id', 0);
    $db->prepare("DELETE FROM client_email_accounts WHERE id=?")->execute([$id]);
    apiSuccess([], 'Deleted.');
}

// save
$id       = (int)post('id', 0);
$email    = trim(post('email_address', ''));
if (!$clientId) apiError('Client ID required.', 422);
if (!$email)    apiError('Email address required.', 422);

$pwPlain = post('password_plain', '');
$pwEnc   = $pwPlain ? ewEncrypt($pwPlain) : null;

if ($id) {
    $sql = "UPDATE client_email_accounts SET email_address=?,display_name=?,provider=?,
            imap_host=?,imap_port=?,imap_ssl=?,smtp_host=?,smtp_port=?,smtp_ssl=?,
            username=?,webmail_url=?,notes=?" . ($pwEnc ? ",password_enc=?" : "") . " WHERE id=? AND client_id=?";
    $params = [
        $email, post('display_name'), post('provider'),
        post('imap_host'), post('imap_port') ?: 993, post('imap_ssl') ? 1 : 0,
        post('smtp_host'), post('smtp_port') ?: 587, post('smtp_ssl') ? 1 : 0,
        post('username'), post('webmail_url'), post('notes'),
    ];
    if ($pwEnc) $params[] = $pwEnc;
    $params[] = $id;
    $params[] = $clientId;
    $db->prepare($sql)->execute($params);
    apiSuccess(['id' => $id], 'Updated.');
} else {
    $db->prepare("
        INSERT INTO client_email_accounts
            (client_id,email_address,display_name,provider,imap_host,imap_port,imap_ssl,
             smtp_host,smtp_port,smtp_ssl,username,password_enc,webmail_url,notes,created_by)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ")->execute([
        $clientId, $email, post('display_name'), post('provider'),
        post('imap_host'), post('imap_port') ?: 993, post('imap_ssl') ? 1 : 0,
        post('smtp_host'), post('smtp_port') ?: 587, post('smtp_ssl') ? 1 : 0,
        post('username'), $pwEnc, post('webmail_url'), post('notes'), $user['id']
    ]);
    apiSuccess(['id' => (int)$db->lastInsertId()], 'Email account added.', 201);
}
