const API_URL = 'http://localhost/AAbank_mob/backend/api.php';

const getAuthToken = () => localStorage.getItem('iosco_token') || '';

const authHeaders = () => ({
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${getAuthToken()}`
});

export const fetchUserData = async () => {
    try {
        const response = await fetch(`${API_URL}/user`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch user data');
        const data = await response.json();
        return {
            balance: data.account ? data.account.balance : 0,
            accountNumber: data.account ? data.account.account_number : '',
            accountStatus: data.account ? data.account.status : 'active',
            currency: 'USD',
            transactions: data.recent_transactions || [],
            cards: data.cards || [],
            user: data.user || {}
        };
    } catch (error) {
        console.error(error);
        return { balance: 0, currency: 'USD', transactions: [], cards: [], user: {} };
    }
};

export const sendMoney = async (data) => {
    const response = await fetch(`${API_URL}/transfer`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({
            receiver_username: data.recipientName,
            amount: data.amount
        })
    });
    const resData = await response.json();
    if (!response.ok) throw new Error(resData.message || "Transfer failed");
    return { success: true, message: resData.message };
};

export const createCard = async (type = 'debit') => {
    const response = await fetch(`${API_URL}/user/cards`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({ type })
    });
    const resData = await response.json();
    if (!response.ok) throw new Error(resData.message || "Failed to create card");
    return resData;
};

// Loans
export const fetchLoans = async () => {
    try {
        const response = await fetch(`${API_URL}/loan`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch loans');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const applyLoan = async (loanData) => {
    const response = await fetch(`${API_URL}/loan`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(loanData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Loan application failed');
    return data;
};

// Deposits
export const depositMoney = async (depositData) => {
    const response = await fetch(`${API_URL}/deposit`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(depositData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Deposit failed');
    return data;
};

// Admin
export const fetchAdminStats = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/stats`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch stats');
        return await response.json();
    } catch (error) {
        console.error(error);
        return {};
    }
};

export const fetchAllUsers = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/users`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch users');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const createAdminUser = async (userData) => {
    const response = await fetch(`${API_URL}/admin/users`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(userData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to create user');
    return data;
};

export const updateAdminUser = async (userData) => {
    const response = await fetch(`${API_URL}/admin/users`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify(userData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to update user');
    return data;
};

export const deleteAdminUser = async (userId) => {
    const response = await fetch(`${API_URL}/admin/users`, {
        method: 'DELETE',
        headers: authHeaders(),
        body: JSON.stringify({ id: userId })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to delete user');
    return data;
};

export const adjustBalance = async (userId, amount) => {
    const response = await fetch(`${API_URL}/admin/balance`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify({ user_id: userId, amount })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to adjust balance');
    return data;
};

export const fetchAllTransactions = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/transactions`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch transactions');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const fetchAllCards = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/cards`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch cards');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const fetchAllLoans = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/loans`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch loans');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const updateLoanStatus = async (id, status) => {
    const response = await fetch(`${API_URL}/admin/loans`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify({ id, status })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to update loan');
    return data;
};

export const blockAdminAccount = async (accountId, status = 'frozen') => {
    const response = await fetch(`${API_URL}/admin/accounts`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify({ account_id: accountId, status })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to update account');
    return data;
};

// Notes
export const fetchNotes = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/notes`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch notes');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};

export const createNote = async (noteData) => {
    const response = await fetch(`${API_URL}/admin/notes`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(noteData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to create note');
    return data;
};

export const updateNote = async (noteData) => {
    const response = await fetch(`${API_URL}/admin/notes`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify(noteData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to update note');
    return data;
};

export const deleteNote = async (id) => {
    const response = await fetch(`${API_URL}/admin/notes`, {
        method: 'DELETE',
        headers: authHeaders(),
        body: JSON.stringify({ id })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to delete note');
    return data;
};

// Settings
export const fetchSettings = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/settings`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch settings');
        return await response.json();
    } catch (error) {
        console.error(error);
        return {};
    }
};

export const updateSettings = async (settings) => {
    const response = await fetch(`${API_URL}/admin/settings`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify(settings)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Failed to update settings');
    return data;
};

// Payments (utilities, internet, etc.)
export const makePayment = async (paymentData) => {
    const response = await fetch(`${API_URL}/pay`, {
        method: 'POST', headers: authHeaders(), body: JSON.stringify(paymentData)
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Ошибка платежа');
    return data;
};

export const fetchPayments = async () => {
    try {
        const r = await fetch(`${API_URL}/pay`, { headers: authHeaders() });
        if (!r.ok) return [];
        return await r.json();
    } catch { return []; }
};

// Card management
export const blockCard = async (cardId, status = 'blocked') => {
    const response = await fetch(`${API_URL}/cards/block`, {
        method: 'PUT', headers: authHeaders(), body: JSON.stringify({ card_id: cardId, status })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Ошибка');
    return data;
};

export const updateCardLimits = async (cardId, dailyLimit, monthlyLimit) => {
    const response = await fetch(`${API_URL}/cards/limit`, {
        method: 'PUT', headers: authHeaders(),
        body: JSON.stringify({ card_id: cardId, daily_limit: dailyLimit, monthly_limit: monthlyLimit })
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.message || 'Ошибка');
    return data;
};

// Currency rates (static + free public API)
export const fetchCurrencyRates = async () => {
    try {
        const r = await fetch('https://api.exchangerate-api.com/v4/latest/USD');
        if (r.ok) { const d = await r.json(); return d.rates; }
    } catch { /* fallback */ }
    // Static fallback
    return { EUR: 0.92, RUB: 91.5, GBP: 0.79, JPY: 149.5, CNY: 7.24, CHF: 0.89, AED: 3.67, TRY: 32.1, KZT: 449.5, UAH: 38.2 };
};

// Logs
export const fetchLogs = async () => {
    try {
        const response = await fetch(`${API_URL}/admin/logs`, {
            method: 'GET',
            headers: authHeaders()
        });
        if (!response.ok) throw new Error('Failed to fetch logs');
        return await response.json();
    } catch (error) {
        console.error(error);
        return [];
    }
};
