// Mock Data Store - Sri Lanka Context

// Helper for formatting currency
const formatLKR = (amount) => {
  return new Intl.NumberFormat('en-LK', {
    style: 'currency',
    currency: 'LKR',
    minimumFractionDigits: 2
  }).format(amount);
};

// Generate Mock Barcodes
const generateMockBarcode = (pid, vIndex) => `2026${pid.toString().padStart(2, '0')}${vIndex.toString().padStart(2, '0')}`;

// Helper: Date Range Filter — handles MySQL format '2026-03-20 09:41:14' and ISO format
const isDateInRange = (dateStr, startDate, endDate) => {
    if (!dateStr) return false;
    // MySQL returns '2026-03-20 09:41:14' with a space; JS Date needs 'T' for reliable parsing
    const normalized = String(dateStr).replace(' ', 'T');
    const d = new Date(normalized);
    if (isNaN(d.getTime())) return false;
    const start = startDate ? new Date(startDate) : new Date('2000-01-01');
    const end = endDate ? new Date(endDate + 'T23:59:59') : new Date('2099-12-31');
    return d >= start && d <= end;
};

// Helper: Check for upcoming birthdays (Next 3 days)
const getUpcomingBirthdays = (customers) => {
    const today = new Date();
    const threeDaysFromNow = new Date();
    threeDaysFromNow.setDate(today.getDate() + 3);
    
    return customers.filter(c => {
        if (!c.birthday) return false;
        const bday = new Date(c.birthday);
        // Set current year for comparison
        bday.setFullYear(today.getFullYear());
        
        // Handle case where birthday might be early next year if today is Dec 30
        const bdayNextYear = new Date(bday);
        bdayNextYear.setFullYear(today.getFullYear() + 1);

    return (bday >= today && bday <= threeDaysFromNow) || 
           (bdayNextYear >= today && bdayNextYear <= threeDaysFromNow);
});
};

const MOCK_USERS = [];

const MOCK_PAYMENT_METHODS = [
    { id: 'cash', name: 'Cash', icon: 'icon-banknote' },
    { id: 'card', name: 'Card', icon: 'icon-credit-card' },
    { id: 'qr', name: 'QR Payment', icon: 'icon-qr-code' }
];

let MOCK_PRODUCTS = [];

let MOCK_CUSTOMERS = [];

let MOCK_TRANSACTIONS = [];

let MOCK_CREDIT_NOTES = [];

let MOCK_PROMOTIONS = [];

const MOCK_RETURN_REASONS = [
    "Damaged Item",
    "Size Mismatch",
    "Color Mismatch",
    "Defective Fabric",
    "Change of Mind",
    "Other"
];

// --- New Modules Data ---

let MOCK_SUPPLIERS = [];

let MOCK_SUPPLIER_PAYMENTS = [];

const MOCK_EXPENSE_CATEGORIES = [
    "Marketing", "Salary", "Electricity Bill", "Rent", "Water Bill", "Consumables", "Foods", "Maintenance", "Other"
];

let MOCK_EXPENSES = [];

let MOCK_STATS = {
  salesToday: 0.00,
  salesMonth: 0.00,
  ordersToday: 0,
  returnsToday: 0,
  lowStockItems: 0,
  totalInventoryValue: 0.00,
  creditsIssuedToday: 0,
  creditsRedeemedToday: 0,
  outstandingCreditValue: 0.00
};

// Audit Logs Store
let MOCK_LOGS = [];

// Helper: Log Activity
const logActivity = (user, action, details) => {
    const newLog = {
        id: Date.now(),
        timestamp: new Date().toLocaleString('en-GB'), // 24h format preferred in SL
        user: user ? user.name : 'Unknown',
        action,
        details
    };
    // Add to front
    MOCK_LOGS.unshift(newLog);
    // Keep only last 100
    if (MOCK_LOGS.length > 100) {
        MOCK_LOGS.pop();
    }
    return newLog;
};

// Helper: Find Product Variation by Barcode
const findProductByBarcode = (barcode) => {
    if (!barcode) return null;
    for (const product of MOCK_PRODUCTS) {
        const variation = product.variations.find(v => v.barcode === barcode);
        if (variation) {
            return {
                ...product,
                selectedVariation: variation
            };
        }
    }
    return null;
};

// Helper: Get Total Stock for Product
const getProductTotalStock = (product) => {
    return product.variations.reduce((acc, v) => acc + v.stock, 0);
};

// Create Credit Note or Gift Voucher
const createCreditNote = (amount, originalInvoiceId, reason = "Return", type = "CREDIT", customerDetails = null) => {
    const timestamp = Date.now().toString().slice(-4);
    const prefix = type === 'VOUCHER' ? 'GV' : 'CN';
    const creditId = `${prefix}-${timestamp}`;
    // Simplify barcode for vouchers to be easily scannable
    const barcode = `${prefix}${timestamp}${Math.floor(Math.random() * 99)}`;
    
    const newCreditNote = {
        creditId,
        originalInvoiceId,
        amount: -Math.abs(amount), // Ensure negative
        barcode,
        reason,
        type, // 'CREDIT' or 'VOUCHER'
        createdDate: new Date().toISOString().split('T')[0],
        isUsed: false,
        usedDate: null,
        customerDetails // { name, email, phone }
    };
    
    // Add to store
    MOCK_CREDIT_NOTES.push(newCreditNote);
    
    // Update stats
    MOCK_STATS.creditsIssuedToday++;
    MOCK_STATS.outstandingCreditValue += Math.abs(amount);

    return newCreditNote;
};

// Find Credit Note (Search by ID or Barcode)
const findCreditNote = (query) => {
    const q = query.trim().toUpperCase();
    return MOCK_CREDIT_NOTES.find(cn => 
        cn.barcode === q || cn.creditId === q
    );
};

// Helper alias for backward compatibility or specific use
const findCreditNoteByBarcode = (barcode) => findCreditNote(barcode);

// Redeem Credit Note
const redeemCreditNote = (barcodeOrId) => {
    const note = findCreditNote(barcodeOrId);
    if (note && !note.isUsed) {
        note.isUsed = true;
        note.usedDate = new Date().toISOString().split('T')[0];
        MOCK_STATS.creditsRedeemedToday++;
        MOCK_STATS.outstandingCreditValue -= Math.abs(note.amount);
        return true;
    }
    return false;
};

// Mock Invoice Details Fetcher (for Returns UI and Invoice Scan in POS)
// IMPORTANT: reads from window.MockData.transactions (not MOCK_TRANSACTIONS)
// because BackendLoader replaces window.MockData.transactions with live DB data
const getMockInvoiceDetails = (invoiceId) => {
    // Always use the live reference so it works after BackendLoader populates it
    const allTransactions = (window.MockData && window.MockData.transactions) ? window.MockData.transactions : MOCK_TRANSACTIONS;
    const trx = allTransactions.find(t => t.id === invoiceId);
    if (!trx) return null; // Only return if invoice exists

    const customerId = trx.customerId || trx.customer_id;
    const customerName = trx.customer || trx.customer_name || 'Guest';

    // Generate some items based on the invoice ID seed for display
    const items = [];
    const count = Array.isArray(trx.items) ? trx.items.length : (typeof trx.items === 'number' ? trx.items : 1);
    
    const seed = invoiceId.split('').reduce((a,b)=>a+b.charCodeAt(0),0);
    
    const productPool = (window.MockData && window.MockData.products) ? window.MockData.products : MOCK_PRODUCTS;
    if (productPool.length === 0) return { items: [], customerId, customerName };

    for (let i = 0; i < Math.max(1, count); i++) {
        const prodIndex = (seed + i) % productPool.length;
        const prod = productPool[prodIndex];
        
        let discount = 0;
        let finalTotal = prod.price;
        const promoPool = (window.MockData && window.MockData.promotions) ? window.MockData.promotions : MOCK_PROMOTIONS;
        const promo = promoPool.find(p => p.isActive && p.applicableProducts && p.applicableProducts.includes(prod.id));
        if (promo) {
            if (promo.discountType === 'fixed') discount = promo.value;
            else if (promo.discountType === 'percentage') discount = prod.price * (promo.value / 100);
            finalTotal = prod.price - discount;
        }

        items.push({
            ...prod,
            qty: 1,
            variation: prod.variations[0],
            uniqueId: `${invoiceId}-${i}`,
            finalTotal: finalTotal
        });
    }
    return { items, customerId, customerName };
};

// Export to Excel Simulator
const exportToExcel = (data, filename) => {
    if (!data || data.length === 0) {
        alert("No data to export!");
        return;
    }
    
    // Create CSV header
    const headers = Object.keys(data[0]);
    const csvRows = [];
    csvRows.push(headers.join(","));
    
    // Add data rows
    for (const row of data) {
        const values = headers.map(header => {
            const val = row[header];
            if (typeof val === 'number') return val;
            const escaped = ('' + val).replace(/"/g, '\\"');
            return `"${escaped}"`;
        });
        csvRows.push(values.join(","));
    }
    
    const csvContent = "data:text/csv;charset=utf-8," + csvRows.join("\n");
    
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `${filename}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};

window.MockData = {
  users: MOCK_USERS,
  paymentMethods: MOCK_PAYMENT_METHODS,
  products: MOCK_PRODUCTS,
  customers: MOCK_CUSTOMERS,
  transactions: MOCK_TRANSACTIONS,
  creditNotes: MOCK_CREDIT_NOTES,
  promotions: MOCK_PROMOTIONS,
  returnReasons: MOCK_RETURN_REASONS,
  suppliers: MOCK_SUPPLIERS,
  supplierPayments: MOCK_SUPPLIER_PAYMENTS,
  expenses: MOCK_EXPENSES,
  expenseCategories: MOCK_EXPENSE_CATEGORIES,
  stats: MOCK_STATS,
  formatLKR,
  findProductByBarcode,
  getProductTotalStock,
  createCreditNote,
  findCreditNoteByBarcode, // kept for compatibility
  findCreditNote, // New
  redeemCreditNote,
  getMockInvoiceDetails,
  exportToExcel,
  isDateInRange,
  getUpcomingBirthdays,
  logs: MOCK_LOGS,
  logActivity
};
