/**
 * API Client untuk komunikasi dengan backend
 * Menggunakan Fetch API untuk HTTP requests
 */

// Base URL untuk API
const API_BASE_URL = '';

// Helper function untuk membuat request
async function makeRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('API request failed:', error);
        throw error;
    }
}

// Positions API
class PositionsAPI {
    async getPositions() {
        try {
            return await makeRequest(`${API_BASE_URL}api/positions.php`);
        } catch (error) {
            console.error('Failed to get positions:', error);
            return { success: false, error: error.message };
        }
    }
}

// Attendance API
class AttendanceAPI {
    async getAttendance(date = null) {
        try {
            const url = date ? 
                `${API_BASE_URL}api/attendance.php?date=${date}` : 
                `${API_BASE_URL}api/attendance.php`;
            return await makeRequest(url);
        } catch (error) {
            console.error('Failed to get attendance:', error);
            return { success: false, error: error.message };
        }
    }

    async updateAttendance(positionId, status, userId, date = null) {
        try {
            const requestDate = date || new Date().toISOString().split('T')[0];
            
            return await makeRequest(`${API_BASE_URL}api/attendance.php`, {
                method: 'POST',
                body: JSON.stringify({
                    position_id: positionId,
                    status: status,
                    user_id: userId,
                    date: requestDate
                })
            });
        } catch (error) {
            console.error('Failed to update attendance:', error);
            return { success: false, error: error.message };
        }
    }
}

// Auth API
class AuthAPI {
    async login(username, password) {
        try {
            return await makeRequest(`${API_BASE_URL}api/auth.php`, {
                method: 'POST',
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            });
        } catch (error) {
            console.error('Failed to login:', error);
            return { success: false, error: error.message };
        }
    }

    async verifyToken(token) {
        try {
            return await makeRequest(`${API_BASE_URL}api/auth.php`, {
                method: 'GET',
                headers: {
                    'Authorization': token
                }
            });
        } catch (error) {
            console.error('Failed to verify token:', error);
            return { success: false, error: error.message };
        }
    }
}

// Users API (untuk admin)
class UsersAPI {
    async getUsers() {
        try {
            return await makeRequest(`${API_BASE_URL}api/users.php`);
        } catch (error) {
            console.error('Failed to get users:', error);
            return { success: false, error: error.message };
        }
    }

    async createUser(userData) {
        try {
            return await makeRequest(`${API_BASE_URL}api/users.php`, {
                method: 'POST',
                body: JSON.stringify(userData)
            });
        } catch (error) {
            console.error('Failed to create user:', error);
            return { success: false, error: error.message };
        }
    }

    async updateUser(userId, userData) {
        try {
            return await makeRequest(`${API_BASE_URL}api/users.php`, {
                method: 'PUT',
                body: JSON.stringify({
                    id: userId,
                    ...userData
                })
            });
        } catch (error) {
            console.error('Failed to update user:', error);
            return { success: false, error: error.message };
        }
    }

    async deleteUser(userId) {
        try {
            return await makeRequest(`${API_BASE_URL}api/users.php`, {
                method: 'DELETE',
                body: JSON.stringify({ id: userId })
            });
        } catch (error) {
            console.error('Failed to delete user:', error);
            return { success: false, error: error.message };
        }
    }
}

// Auto-Reset API - Check and reset attendance for new day
class AutoResetAPI {
    async checkAndReset() {
        try {
            const response = await makeRequest(`${API_BASE_URL}api/check_and_reset.php`);
            
            if (response.success && response.reset_performed) {
                console.log('✅ Attendance auto-reset performed for:', response.date);
                console.log(`   Created ${response.records_created} new attendance records`);
            } else if (response.success) {
                console.log('ℹ️ Attendance already initialized for today:', response.date);
            }
            
            return response;
        } catch (error) {
            console.error('Auto-reset check failed:', error);
            return { success: false, error: error.message };
        }
    }
}

// Create global instances
const positionsAPI = new PositionsAPI();
const attendanceAPI = new AttendanceAPI();
const authAPI = new AuthAPI();
const usersAPI = new UsersAPI();
const autoResetAPI = new AutoResetAPI();

// Export for use in other scripts
window.positionsAPI = positionsAPI;
window.attendanceAPI = attendanceAPI;
window.authAPI = authAPI;
window.usersAPI = usersAPI;
window.autoResetAPI = autoResetAPI;

// Auto-check and reset on page load
(function() {
    // Run auto-reset check when page loads
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            autoResetAPI.checkAndReset();
        });
    } else {
        autoResetAPI.checkAndReset();
    }
})();
