/**
 * API Helper — Handles all HTTP requests to the PHP backend.
 * Automatically includes JWT token and handles errors.
 */

const API = {
    // Dynamically detect base URL (detects if project is in a subdirectory)
    baseUrl: (function() {
        // Remove trailing index.html or filename from pathname
        const path = window.location.pathname.replace(/\/[^\/]*$/, '');
        return path + '/api/index.php';
    })(),

    /**
     * Build URL with query-parameter routing (for maximum server compatibility)
     */
    buildUrl: function(endpoint, params = {}) {
        const urlParams = new URLSearchParams(params);
        // Remove leading slash if present
        const route = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
        urlParams.set('r', route);
        return this.baseUrl + '?' + urlParams.toString();
    },

    /**
     * Get the stored JWT token
     */
    getToken: function() {
        return localStorage.getItem('jwt_token');
    },

    /**
     * Build headers with JWT authorization
     */
    getHeaders: function() {
        const headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };
        const token = this.getToken();
        if (token) {
            headers['Authorization'] = 'Bearer ' + token;
        }
        return headers;
    },

    /**
     * GET request
     */
    get: async function(endpoint, params = {}) {
        const url = this.buildUrl(endpoint, params);

        console.log(`[API] GET ${url}`);
        const response = await fetch(url, {
            method: 'GET',
            headers: this.getHeaders()
        });

        return this.handleResponse(response, `GET ${endpoint}`);
    },

    /**
     * POST request
     */
    post: async function(endpoint, data = {}) {
        const url = this.buildUrl(endpoint);
        console.log(`[API] POST ${url}`, data);
        const response = await fetch(url, {
            method: 'POST',
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        });

        return this.handleResponse(response, `POST ${endpoint}`);
    },

    /**
     * PUT request
     */
    put: async function(endpoint, data = {}) {
        const url = this.buildUrl(endpoint);
        // Method Spoofing for cPanel/Shared Hosting
        console.log(`[API] PUT (Spoofed) ${url}`, data);
        const headers = this.getHeaders();
        headers['X-HTTP-Method-Override'] = 'PUT';

        const response = await fetch(url, {
            method: 'POST', // Use POST to bypass server-side PUT blocking
            headers: headers,
            body: JSON.stringify({ ...data, _method: 'PUT' })
        });

        return this.handleResponse(response, `PUT ${endpoint}`);
    },

    /**
     * DELETE request
     */
    delete: async function(endpoint, id) {
        const url = this.buildUrl(endpoint + '/' + id);
        // Method Spoofing for cPanel/Shared Hosting
        console.log(`[API] DELETE (Spoofed) ${url}`);
        const headers = this.getHeaders();
        headers['X-HTTP-Method-Override'] = 'DELETE';

        const response = await fetch(url, {
            method: 'POST', // Use POST to bypass server-side DELETE blocking
            headers: headers,
            body: JSON.stringify({ _method: 'DELETE' })
        });

        return this.handleResponse(response, `DELETE ${endpoint}/${id}`);
    },

    /**
     * Handle API response — parse JSON, handle errors
     */
    handleResponse: async function(response, debugName = 'Request') {
        let data;
        try {
            data = await response.json();
            console.log(`[API] Response from ${debugName}:`, data);
        } catch (e) {
            console.error(`[API] Error parsing response from ${debugName}:`, response);
            throw new Error('سرور سے غیر متوقع جواب آیا۔');
        }

        if (!response.ok) {
            console.warn(`[API] Error Response (${response.status}) from ${debugName}:`, data);
            // Handle 401 — redirect to login
            if (response.status === 401) {
                localStorage.removeItem('jwt_token');
                localStorage.removeItem('current_user');
                if (window.location.hash !== '#login') {
                    Toast.danger(data.message || 'سیشن ختم ہو گیا۔ دوبارہ لاگ ان کریں۔');
                    window.location.hash = '#login';
                }
                throw new Error(data.message || 'Unauthorized');
            }

            // Handle 403
            if (response.status === 403) {
                Toast.danger(data.message || 'آپ کو اس عمل کی اجازت نہیں ہے۔');
                throw new Error(data.message || 'Forbidden');
            }

            // Handle validation errors (422)
            if (response.status === 422) {
                let errorMsg = data.message || 'توثیق ناکام۔';
                if (data.errors) {
                    const errorList = Object.values(data.errors).flat();
                    errorMsg += '\n' + errorList.join('\n');
                }
                Toast.warning(errorMsg);
                throw new Error(errorMsg);
            }

            // Generic error
            Toast.danger(data.message || 'غلطی ہو گئی۔');
            throw new Error(data.message || 'Request failed');
        }

        return data;
    },

    /**
     * Check if user is logged in
     */
    isLoggedIn: function() {
        return !!this.getToken();
    },

    /**
     * Get current user from localStorage
     */
    getCurrentUser: function() {
        const userData = localStorage.getItem('current_user');
        return userData ? JSON.parse(userData) : null;
    },

    /**
     * Save current user to localStorage
     */
    setCurrentUser: function(user) {
        localStorage.setItem('current_user', JSON.stringify(user));
    },

    /**
     * Logout
     */
    logout: async function() {
        try {
            await this.post('/auth/logout');
        } catch (e) {
            // Ignore errors during logout
        }
        localStorage.removeItem('jwt_token');
        localStorage.removeItem('current_user');
        window.location.hash = '#login';
        window.location.reload();
    }
};
