<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';

if ($_SESSION['role_id'] != 1) {
    $_SESSION['error'] = 'Only Super Admin can add demo data.';
    header('Location: ' . getRedirectUrl());
    exit;
}

$pdo = getDB();
header('Content-Type: application/json');

try {
    // Check if demo data already exists
    $tables_to_check = ['categories', 'brands', 'suppliers', 'customers', 'products'];
    foreach ($tables_to_check as $t) {
        $stmt = $pdo->query("SELECT COUNT(*) FROM $t WHERE is_demo = 1");
        if ($stmt->fetchColumn() > 0) {
            echo json_encode(['success' => false, 'message' => 'Demo data already exists. Please remove existing demo data before adding again.']);
            exit;
        }
    }

    $pdo->beginTransaction();
    $user_id = $_SESSION['user_id'];

    // === 1. DEMO CATEGORIES ===
    $categories = [
        ['Mobile Phones', 'Phone', 'All mobile phone products'],
        ['Accessories', 'Accessory', 'Phone accessories and peripherals'],
        ['Spare Parts', 'Spare Part', 'Repair spare parts']
    ];
    $cat_ids = [];
    $stmt = $pdo->prepare("INSERT INTO categories (category_name, category_type, description, status, is_demo) VALUES (?, ?, ?, 1, 1)");
    foreach ($categories as $c) {
        $stmt->execute($c);
        $cat_ids[$c[0]] = $pdo->lastInsertId();
    }

    // === 2. DEMO BRANDS ===
    $brands = ['Apple', 'Samsung', 'Xiaomi', 'Oppo', 'Vivo', 'JBL', 'Baseus'];
    $brand_ids = [];
    $stmt = $pdo->prepare("INSERT INTO brands (brand_name, description, status, is_demo) VALUES (?, ?, 1, 1)");
    foreach ($brands as $b) {
        $stmt->execute([$b, 'Demo brand - ' . $b]);
        $brand_ids[$b] = $pdo->lastInsertId();
    }

    // === 3. DEMO SUPPLIERS ===
    $suppliers = [
        ['SUP-DEMO-001', 'Demo Mobile Supplier', 'Supun Perera', '0771234567', 'supun@demo.lk', '123 Galle Road, Colombo', 'Demo Mobile Wholesale', 10000.00],
        ['SUP-DEMO-002', 'Demo Accessories Supplier', 'Priya Jayawardena', '0772345678', 'priya@demo.lk', '456 Kandy Road, Kandy', 'Demo Accessories Ltd', 5000.00],
        ['SUP-DEMO-003', 'Demo Spare Parts Supplier', 'Lalith Kumara', '0773456789', 'lalith@demo.lk', '789 Main Street, Moratuwa', 'Demo Parts House', 7500.00]
    ];
    $supplier_ids = [];
    $stmt = $pdo->prepare("INSERT INTO suppliers (supplier_code, supplier_name, contact_person, phone, email, address, company_name, opening_balance, current_balance, status, is_demo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)");
    foreach ($suppliers as $s) {
        $stmt->execute([$s[0], $s[1], $s[2], $s[3], $s[4], $s[5], $s[6], $s[7], $s[7]]);
        $supplier_ids[$s[1]] = $pdo->lastInsertId();
    }

    // === 4. DEMO CUSTOMERS ===
    $customers = [
        ['CUST-DEMO-001', 'Kasun Perera', '0711111111', '0711111111', 'kasun@demo.lk', '952323232V', '100 Galle Road, Colombo 03', 0],
        ['CUST-DEMO-002', 'Nimal Fernando', '0722222222', '0722222222', 'nimal@demo.lk', '962424242V', '200 Kandy Road, Kadawatha', 1500],
        ['CUST-DEMO-003', 'Saman Kumara', '0733333333', '0733333333', 'saman@demo.lk', '972525252V', '300 High Level Road, Nugegoda', 0],
        ['CUST-DEMO-004', 'Tharushi Silva', '0744444444', '0744444444', 'tharushi@demo.lk', '982626262V', '400 Temple Road, Kurunegala', 2500],
        ['CUST-DEMO-005', 'Ruwan Jayasinghe', '0755555555', '0755555555', 'ruwan@demo.lk', '992727272V', '500 Beach Road, Negombo', 0]
    ];
    $customer_ids = [];
    $stmt = $pdo->prepare("INSERT INTO customers (customer_code, name, phone, whatsapp, email, nic, address, opening_balance, current_balance, status, is_demo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)");
    foreach ($customers as $c) {
        $stmt->execute([$c[0], $c[1], $c[2], $c[3], $c[4], $c[5], $c[6], $c[7], $c[7]]);
        $customer_ids[$c[1]] = $pdo->lastInsertId();
    }

    // === 5. DEMO PHONE PRODUCTS ===
    $phone_products = [
        ['PROD-DEMO-001', 'iPhone 13 128GB', 'Phone', 'iPhone 13', 'APPLE-13-128', 'IP13-128GB', 180000.00, 229999.00, 215000.00, 15, 3, 365],
        ['PROD-DEMO-002', 'Samsung Galaxy A55', 'Phone', 'SM-A556E', 'SAM-A55-256', 'SM-A556E', 110000.00, 139999.00, 130000.00, 20, 3, 365],
        ['PROD-DEMO-003', 'Redmi Note 13', 'Phone', 'Redmi Note 13', 'XIAOMI-RN13-256', 'RN13-256', 85000.00, 109999.00, 100000.00, 18, 3, 365],
        ['PROD-DEMO-004', 'Oppo Reno 11', 'Phone', 'CPH2599', 'OPPO-R11-256', 'CPH2599', 95000.00, 119999.00, 110000.00, 12, 3, 365],
        ['PROD-DEMO-005', 'Vivo V30', 'Phone', 'V2337', 'VIVO-V30-256', 'V2337', 90000.00, 114999.00, 105000.00, 10, 3, 365]
    ];
    $phone_ids = [];
    $stmt = $pdo->prepare("INSERT INTO products (product_code, product_name, category_id, brand_id, supplier_id, product_type, model, sku, barcode, cost_price, selling_price, wholesale_price, current_stock, low_stock_qty, warranty_period_days, status, is_demo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)");
    foreach ($phone_products as $p) {
        $stmt->execute([$p[0], $p[1], $cat_ids['Mobile Phones'], $brand_ids['Apple'], $supplier_ids['Demo Mobile Supplier'], $p[2], $p[3], $p[4], $p[5], $p[6], $p[7], $p[8], $p[9], $p[10], $p[11]]);
        $phone_ids[$p[1]] = $pdo->lastInsertId();
    }

    // === 6. DEMO ACCESSORY PRODUCTS ===
    $accessory_products = [
        ['PROD-DEMO-006', 'Tempered Glass', 'Accessory', 'iPhone 15/Samsung', 'TG-UNI-001', 'TG001', 250.00, 500.00, 350.00, 100, 10, 0],
        ['PROD-DEMO-007', 'Phone Back Cover', 'Accessory', 'Universal', 'COVER-UNI-002', 'CVR002', 350.00, 650.00, 500.00, 80, 10, 0],
        ['PROD-DEMO-008', 'Type-C Cable', 'Accessory', '1M Braided', 'CABLE-TC-003', 'CBL003', 400.00, 800.00, 600.00, 120, 10, 0],
        ['PROD-DEMO-009', 'Fast Charger', 'Accessory', '25W PD Fast Charger', 'CHGR-25W-004', 'CHG004', 900.00, 1800.00, 1400.00, 60, 10, 0],
        ['PROD-DEMO-010', 'Bluetooth Earbuds', 'Accessory', 'TWS V5.3', 'BUDS-TWS-005', 'BUD005', 3500.00, 5500.00, 4500.00, 40, 5, 90],
        ['PROD-DEMO-011', 'Power Bank', 'Accessory', '10000mAh', 'PB-10K-006', 'PBK006', 2500.00, 4500.00, 3500.00, 35, 5, 180]
    ];
    $accessory_ids = [];
    $stmt = $pdo->prepare("INSERT INTO products (product_code, product_name, category_id, brand_id, supplier_id, product_type, model, sku, barcode, cost_price, selling_price, wholesale_price, current_stock, low_stock_qty, warranty_period_days, status, is_demo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)");
    foreach ($accessory_products as $p) {
        $stmt->execute([$p[0], $p[1], $cat_ids['Accessories'], $brand_ids['Baseus'], $supplier_ids['Demo Accessories Supplier'], $p[2], $p[3], $p[4], $p[5], $p[6], $p[7], $p[8], $p[9], $p[10], $p[11]]);
        $accessory_ids[$p[1]] = $pdo->lastInsertId();
    }

    // === 7. DEMO SPARE PART PRODUCTS ===
    $spare_products = [
        ['PROD-DEMO-012', 'iPhone 13 Display', 'Spare Part', 'iPhone 13 OLED', 'IP13-DISP-001', 'DISP001', 25000.00, 35000.00, 30000.00, 5, 2, 90],
        ['PROD-DEMO-013', 'Samsung A55 Battery', 'Spare Part', 'SM-A556E Battery', 'SAM-A55-BATT-002', 'BATT002', 4500.00, 8000.00, 6500.00, 8, 2, 90],
        ['PROD-DEMO-014', 'Redmi Note 13 Charging Port', 'Spare Part', 'RN13 Charging Flex', 'XIAO-RN13-CHG-003', 'CHG003', 2500.00, 4500.00, 3500.00, 10, 2, 30],
        ['PROD-DEMO-015', 'Oppo Reno 11 Speaker', 'Spare Part', 'CPH2599 Speaker', 'OPPO-R11-SPK-004', 'SPK004', 1800.00, 3500.00, 2500.00, 7, 2, 30],
        ['PROD-DEMO-016', 'Vivo V30 Back Cover', 'Spare Part', 'V2337 Back Housing', 'VIVO-V30-COV-005', 'COV005', 3500.00, 6000.00, 5000.00, 6, 2, 30]
    ];
    $spare_ids = [];
    $stmt = $pdo->prepare("INSERT INTO products (product_code, product_name, category_id, brand_id, supplier_id, product_type, model, sku, barcode, cost_price, selling_price, wholesale_price, current_stock, low_stock_qty, warranty_period_days, status, is_demo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1)");
    foreach ($spare_products as $p) {
        $stmt->execute([$p[0], $p[1], $cat_ids['Spare Parts'], $brand_ids['Apple'], $supplier_ids['Demo Spare Parts Supplier'], $p[2], $p[3], $p[4], $p[5], $p[6], $p[7], $p[8], $p[9], $p[10], $p[11]]);
        $spare_ids[$p[1]] = $pdo->lastInsertId();
    }

    // === 8. DEMO IMEI RECORDS ===
    $imei_base = 356789012345000;
    $imei_index = 1;
    $imei_ids = [];
    $stmt = $pdo->prepare("INSERT INTO product_imei (product_id, imei_number, serial_number, status, is_demo) VALUES (?, ?, ?, 'Available', 1)");
    foreach ($phone_ids as $pname => $pid) {
        for ($j = 0; $j < 3; $j++) {
            $imei_num = $imei_base + $imei_index;
            $serial = 'SN-DEMO-' . str_pad($imei_index, 4, '0', STR_PAD_LEFT);
            $stmt->execute([$pid, (string)$imei_num, $serial]);
            $imei_ids[$imei_num] = $pdo->lastInsertId();
            $imei_index++;
        }
    }

    // === 9. DEMO PURCHASES ===
    // 9a. Phone purchase
    $phone_purchase_id = insertDemoPurchase($pdo, 'PO-DEMO-001', $supplier_ids['Demo Mobile Supplier'], $phone_ids, [
        ['product_id' => $phone_ids['iPhone 13 128GB'], 'quantity' => 5, 'cost_price' => 180000.00, 'selling_price' => 229999.00],
        ['product_id' => $phone_ids['Samsung Galaxy A55'], 'quantity' => 5, 'cost_price' => 110000.00, 'selling_price' => 139999.00],
        ['product_id' => $phone_ids['Redmi Note 13'], 'quantity' => 5, 'cost_price' => 85000.00, 'selling_price' => 109999.00],
        ['product_id' => $phone_ids['Oppo Reno 11'], 'quantity' => 3, 'cost_price' => 95000.00, 'selling_price' => 119999.00],
        ['product_id' => $phone_ids['Vivo V30'], 'quantity' => 3, 'cost_price' => 90000.00, 'selling_price' => 114999.00]
    ], 2000000.00, $user_id);

    // 9b. Accessory purchase
    $acc_purchase_id = insertDemoPurchase($pdo, 'PO-DEMO-002', $supplier_ids['Demo Accessories Supplier'], $accessory_ids, [
        ['product_id' => $accessory_ids['Tempered Glass'], 'quantity' => 50, 'cost_price' => 250.00, 'selling_price' => 500.00],
        ['product_id' => $accessory_ids['Phone Back Cover'], 'quantity' => 40, 'cost_price' => 350.00, 'selling_price' => 650.00],
        ['product_id' => $accessory_ids['Type-C Cable'], 'quantity' => 60, 'cost_price' => 400.00, 'selling_price' => 800.00],
        ['product_id' => $accessory_ids['Fast Charger'], 'quantity' => 30, 'cost_price' => 900.00, 'selling_price' => 1800.00],
        ['product_id' => $accessory_ids['Bluetooth Earbuds'], 'quantity' => 20, 'cost_price' => 3500.00, 'selling_price' => 5500.00],
        ['product_id' => $accessory_ids['Power Bank'], 'quantity' => 15, 'cost_price' => 2500.00, 'selling_price' => 4500.00]
    ], 250000.00, $user_id);

    // 9c. Spare parts purchase
    $spare_purchase_id = insertDemoPurchase($pdo, 'PO-DEMO-003', $supplier_ids['Demo Spare Parts Supplier'], $spare_ids, [
        ['product_id' => $spare_ids['iPhone 13 Display'], 'quantity' => 3, 'cost_price' => 25000.00, 'selling_price' => 35000.00],
        ['product_id' => $spare_ids['Samsung A55 Battery'], 'quantity' => 5, 'cost_price' => 4500.00, 'selling_price' => 8000.00],
        ['product_id' => $spare_ids['Redmi Note 13 Charging Port'], 'quantity' => 5, 'cost_price' => 2500.00, 'selling_price' => 4500.00],
        ['product_id' => $spare_ids['Oppo Reno 11 Speaker'], 'quantity' => 4, 'cost_price' => 1800.00, 'selling_price' => 3500.00],
        ['product_id' => $spare_ids['Vivo V30 Back Cover'], 'quantity' => 4, 'cost_price' => 3500.00, 'selling_price' => 6000.00]
    ], 75000.00, $user_id);

    // === 10. DEMO REPAIR JOBS ===
    // Format: [job_no, customer_id, device_brand, device_model, device_imei, problem_description, device_condition, parts_total, labour_charge, discount_amount, final_amount, paid_amount, due_amount, repair_status, created_by]
    $repairs = [
        ['RJ-DEMO-001', $customer_ids['Kasun Perera'], 'Apple', 'iPhone 13', '356789012345001', 'Screen cracked, display not responding', 'Device has visible cracks on screen', 25000.00, 5000.00, 0, 30000.00, 15000.00, 15000.00, 'Waiting for Parts', $user_id],
        ['RJ-DEMO-002', $customer_ids['Nimal Fernando'], 'Samsung', 'Galaxy A55', '356789012345004', 'Battery draining fast, swelling', 'Battery bulging, back cover lifted', 4500.00, 3000.00, 0, 7500.00, 0, 7500.00, 'Received', $user_id],
        ['RJ-DEMO-003', $customer_ids['Saman Kumara'], 'Xiaomi', 'Redmi Note 13', '356789012345007', 'Charging port loose, not charging', 'Phone is in good condition overall', 2500.00, 2000.00, 0, 4500.00, 2000.00, 2500.00, 'Checking', $user_id],
        ['RJ-DEMO-004', $customer_ids['Tharushi Silva'], 'Oppo', 'Reno 11', '356789012345010', 'Speaker not working during calls', 'Minor scratches on frame', 1800.00, 2000.00, 0, 3800.00, 0, 3800.00, 'Repairing', $user_id],
        ['RJ-DEMO-005', $customer_ids['Ruwan Jayasinghe'], 'Vivo', 'V30', '356789012345013', 'Back cover damaged, needs replacement', 'Back cover cracked, rest of device good', 3500.00, 2500.00, 500.00, 5500.00, 5500.00, 0, 'Completed', $user_id]
    ];
    $repair_ids = [];
    $stmt = $pdo->prepare("INSERT INTO repair_jobs (job_no, customer_id, device_brand, device_model, device_imei, problem_description, device_condition, parts_total, labour_charge, discount_amount, final_amount, paid_amount, due_amount, repair_status, priority, created_by, is_demo, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Medium', ?, 1, NOW())");
    foreach ($repairs as $r) {
        $stmt->execute([$r[0], $r[1], $r[2], $r[3], $r[4], $r[5], $r[6], $r[7], $r[8], $r[9], $r[10], $r[11], $r[12], $r[13], $r[14]]);
        $repair_ids[$r[0]] = $pdo->lastInsertId();
    }

    // Add repair job parts for display/speaker jobs
    $stmt_part = $pdo->prepare("INSERT INTO repair_job_parts (repair_job_id, product_id, quantity, cost_price, selling_price, total_price, is_demo) VALUES (?, ?, ?, ?, ?, ?, 1)");
    $stmt_part->execute([$repair_ids['RJ-DEMO-001'], $spare_ids['iPhone 13 Display'], 1, 25000.00, 35000.00, 30000.00]);
    $stmt_part->execute([$repair_ids['RJ-DEMO-004'], $spare_ids['Oppo Reno 11 Speaker'], 1, 1800.00, 3500.00, 3500.00]);
    $stmt_part->execute([$repair_ids['RJ-DEMO-005'], $spare_ids['Vivo V30 Back Cover'], 1, 3500.00, 6000.00, 5500.00]);

    // Add status history for repair jobs
    $stmt_history = $pdo->prepare("INSERT INTO repair_job_status_history (repair_job_id, old_status, new_status, note, changed_by, is_demo) VALUES (?, NULL, ?, 'Initial status set by demo data', ?, 1)");
    foreach ($repairs as $r) {
        $stmt_history->execute([$repair_ids[$r[0]], $r[7], $user_id]);
    }

    // === 11. DEMO PAYMENTS ===
    $stmt_payment = $pdo->prepare("INSERT INTO payments (payment_no, payment_type, reference_id, supplier_id, amount, payment_method, payment_date, note, received_by, is_demo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)");
    $stmt_payment->execute(['PAY-DEMO-001', 'purchase', $phone_purchase_id, $supplier_ids['Demo Mobile Supplier'], 2000000.00, 'Bank Transfer', date('Y-m-d'), 'Full payment for phone purchase', $user_id]);
    $stmt_payment->execute(['PAY-DEMO-002', 'purchase', $acc_purchase_id, $supplier_ids['Demo Accessories Supplier'], 250000.00, 'Bank Transfer', date('Y-m-d'), 'Full payment for accessory purchase', $user_id]);
    $stmt_payment->execute(['PAY-DEMO-003', 'purchase', $spare_purchase_id, $supplier_ids['Demo Spare Parts Supplier'], 75000.00, 'Cash', date('Y-m-d'), 'Full payment for spare parts purchase', $user_id]);
    $stmt_payment->execute(['PAY-DEMO-004', 'repair', $repair_ids['RJ-DEMO-005'], NULL, 5500.00, 'Cash', date('Y-m-d'), 'Full payment for completed repair - V30 back cover', $user_id]);

    // === 12. DEMO STOCK MOVEMENTS ===
    // Phone stock movements from purchase
    $stmt_sm = $pdo->prepare("INSERT INTO stock_movements (product_id, movement_type, reference_type, reference_id, quantity_in, quantity_out, balance_after, note, created_by, is_demo) VALUES (?, 'purchase', 'purchases', ?, ?, 0, ?, 'Demo purchase received', ?, 1)");
    $phone_purchase_items = [
        ['product_id' => $phone_ids['iPhone 13 128GB'], 'quantity' => 5],
        ['product_id' => $phone_ids['Samsung Galaxy A55'], 'quantity' => 5],
        ['product_id' => $phone_ids['Redmi Note 13'], 'quantity' => 5],
        ['product_id' => $phone_ids['Oppo Reno 11'], 'quantity' => 3],
        ['product_id' => $phone_ids['Vivo V30'], 'quantity' => 3]
    ];
    foreach ($phone_purchase_items as $pi) {
        // Update stock
        $pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")->execute([$pi['quantity'], $pi['product_id']]);
        $stmt_sm->execute([$pi['product_id'], $phone_purchase_id, $pi['quantity'], $pi['quantity'], $user_id]);
    }

    // Accessory stock movements
    $acc_purchase_items = [
        ['product_id' => $accessory_ids['Tempered Glass'], 'quantity' => 50],
        ['product_id' => $accessory_ids['Phone Back Cover'], 'quantity' => 40],
        ['product_id' => $accessory_ids['Type-C Cable'], 'quantity' => 60],
        ['product_id' => $accessory_ids['Fast Charger'], 'quantity' => 30],
        ['product_id' => $accessory_ids['Bluetooth Earbuds'], 'quantity' => 20],
        ['product_id' => $accessory_ids['Power Bank'], 'quantity' => 15]
    ];
    foreach ($acc_purchase_items as $pi) {
        $pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")->execute([$pi['quantity'], $pi['product_id']]);
        $stmt_sm->execute([$pi['product_id'], $acc_purchase_id, $pi['quantity'], $pi['quantity'], $user_id]);
    }

    // Spare parts stock movements
    $spare_purchase_items = [
        ['product_id' => $spare_ids['iPhone 13 Display'], 'quantity' => 3],
        ['product_id' => $spare_ids['Samsung A55 Battery'], 'quantity' => 5],
        ['product_id' => $spare_ids['Redmi Note 13 Charging Port'], 'quantity' => 5],
        ['product_id' => $spare_ids['Oppo Reno 11 Speaker'], 'quantity' => 4],
        ['product_id' => $spare_ids['Vivo V30 Back Cover'], 'quantity' => 4]
    ];
    foreach ($spare_purchase_items as $pi) {
        $pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")->execute([$pi['quantity'], $pi['product_id']]);
        $stmt_sm->execute([$pi['product_id'], $spare_purchase_id, $pi['quantity'], $pi['quantity'], $user_id]);
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'Demo data added successfully!']);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error adding demo data: ' . $e->getMessage()]);
}

// Helper function
function insertDemoPurchase($pdo, $purchase_no, $supplier_id, $product_map, $items, $paid_amount, $user_id) {
    $total = 0;
    foreach ($items as $item) {
        $total += $item['quantity'] * $item['cost_price'];
    }
    $subtotal = $total;
    $due = $total - $paid_amount;

    $stmt = $pdo->prepare("INSERT INTO purchases (purchase_no, supplier_id, purchase_date, subtotal, discount, tax, total_amount, paid_amount, due_amount, purchase_status, note, created_by, is_demo) VALUES (?, ?, CURDATE(), ?, 0, 0, ?, ?, ?, 'Received', 'Demo purchase - auto generated', ?, 1)");
    $stmt->execute([$purchase_no, $supplier_id, $subtotal, $total, $paid_amount, $due, $user_id]);
    $purchase_id = $pdo->lastInsertId();

    $stmt_item = $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, quantity, cost_price, selling_price, total_price, is_demo) VALUES (?, ?, ?, ?, ?, ?, 1)");
    foreach ($items as $item) {
        $stmt_item->execute([$purchase_id, $item['product_id'], $item['quantity'], $item['cost_price'], $item['selling_price'], $item['quantity'] * $item['cost_price']]);
    }

    // Update supplier balance
    $pdo->prepare("UPDATE suppliers SET current_balance = current_balance + ? WHERE id = ?")->execute([$due, $supplier_id]);

    return $purchase_id;
}
