<?php
/*
Add these cases inside handlers/settings.php after you read $action and after $account_id is available.
This code assumes you already have jsonResponse($success, $message = '') and $conn.
*/

// ADD ACCOUNT EMAIL
if ($action === 'add_account_email') {

    $email = trim($_POST['email'] ?? '');
    $is_default = (int)($_POST['is_default'] ?? 0);

    if (!$email) {
        jsonResponse(false, 'Email required');
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        jsonResponse(false, 'Invalid email');
    }

    if ($is_default === 1) {
        $stmt = $conn->prepare("UPDATE accounts_email SET is_default = 0 WHERE account_id = ?");
        $stmt->bind_param("i", $account_id);
        $stmt->execute();
    }

    $stmt = $conn->prepare("INSERT INTO accounts_email (account_id, email, is_default) VALUES (?, ?, ?)");
    $stmt->bind_param("isi", $account_id, $email, $is_default);

    if ($stmt->execute()) {
        jsonResponse(true);
    }

    jsonResponse(false, 'Email already exists or could not be saved');
}

// SET DEFAULT ACCOUNT EMAIL
if ($action === 'set_default_account_email') {

    $id = (int)($_POST['id'] ?? 0);

    if (!$id) {
        jsonResponse(false, 'Missing email id');
    }

    $stmt = $conn->prepare("UPDATE accounts_email SET is_default = 0 WHERE account_id = ?");
    $stmt->bind_param("i", $account_id);
    $stmt->execute();

    $stmt = $conn->prepare("UPDATE accounts_email SET is_default = 1 WHERE id = ? AND account_id = ?");
    $stmt->bind_param("ii", $id, $account_id);
    $stmt->execute();

    jsonResponse(true);
}

// DELETE ACCOUNT EMAIL
if ($action === 'delete_account_email') {

    $id = (int)($_POST['id'] ?? 0);

    if (!$id) {
        jsonResponse(false, 'Missing email id');
    }

    $stmt = $conn->prepare("DELETE FROM accounts_email WHERE id = ? AND account_id = ?");
    $stmt->bind_param("ii", $id, $account_id);
    $stmt->execute();

    jsonResponse(true);
}
