<?php
// Show all errors for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include DB connection
include_once("../connection.php"); // Adjust path as needed

// Vendor names to insert
$vendors = [
    'Aquaa Treat', 'Siva Sam Traders', 'SivaRam Traders', 'A B Enterprises', 'Lalitha Electricals ', 'Ikam LandScape', 'Shree Ambika Electricals', 'Siva Glass & PlyWoods', 'Sri Venlateswara Hardwares', 'Shri Vaibhaav Enterprises', 'Universal Hardware ', 'Shanthi Hardware', 'Aqua Pools System', 'Royal Electricals'
];

foreach ($vendors as $vendor_name) {
    // Step 1: Check for existing vendor (case-insensitive)
    $check_sql = "SELECT 1 FROM vendor_master WHERE LOWER(vendor_name) = LOWER(?) LIMIT 1";
    $check_stmt = $con->prepare($check_sql);
    $check_stmt->bind_param("s", $vendor_name);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows === 0) {
        // Step 2: Get last vendor_code
        $result = $con->query("SELECT vendor_code FROM vendor_master WHERE vendor_code LIKE 'VEN-%' ORDER BY id DESC LIMIT 1");

        $last_code = "VEN-178"; // Default fallback
        if ($row = $result->fetch_assoc()) {
            $last_code = $row['vendor_code'];
        }

        $last_number = intval(substr($last_code, 4));
        $new_number = $last_number + 1;
        $new_code = "VEN-" . str_pad($new_number, 3, "0", STR_PAD_LEFT);

        // Step 3: Insert new vendor
        $insert_sql = "INSERT INTO vendor_master (vendor_code, vendor_name, created_on) VALUES (?, ?, NOW())";
        $insert_stmt = $con->prepare($insert_sql);
        $insert_stmt->bind_param("ss", $new_code, $vendor_name);
        if ($insert_stmt->execute()) {
            echo "✅ Inserted: $vendor_name as $new_code<br>";
        } else {
            echo "❌ Insert failed for $vendor_name: " . $con->error . "<br>";
        }
    } else {
        echo "⚠️ Skipped (already exists): $vendor_name<br>";
    }
}
?>
