<?php
require_once __DIR__ . '/config/database.php';

$workshops = [
    ['NEXGEN AUTOMOTIVE', "37, OLORUNSOGO R, ABIOLA WAY", 'ABEOKUTA'],
    ['CARLOHA ABUJA', 'Ben Nnaji st, Kubwa 901101', 'Abuja'],
    ['KAURA MOTORS', 'PLOT 1110, AIRPORT RD, CENTRAL DISTRICT', 'ABUJA'],
    ['COMBINES SYSTEM LTD', 'BY OYEMEKUN WAY', 'AKURE'],
    ['AUTOPOINTE QUICK FIX', 'BY VIO SITE', 'ASABA'],
    ['DIVERSE AUTOS', 'Blk 3, Bay 3, Edo Production center', 'BENIN CITY'],
    ['INGRACE MOTORS', '4, PHC EXPRESS WAY OUT, IND LAYOUT', 'ENUGU'],
    ['TIOTEC MOTORS', '100, Independence lay out, Enugu', 'ENUGU'],
    ['COMBINES SYSTEM LTD', 'MOSHOOD ABIOLA WAY', 'IBADAN'],
    ['Ulim8 Auto center', 'abeokuta express way', 'Ikeja'],
    ['GBOSE MOTIORS', 'Along Asa Dam, Ilorin South link road, by Eucharistic School', 'ILORIN'],
    ['KAURA MOTORS', 'AB2, Namidi Azikwe Way, Express bypass, P.O. Box 974', 'KADUNA'],
    ['Carloha Kano', 'Dan Hassan Rd', 'Kano'],
    ['Ayolola Motors Limited', 'Bode Thomas Surulere', 'LAGOS'],
    ['CARLOHA SHOWROOM', '3rd Axial Rd, beside Heyden Filling Station, between Alapere and Ogudu, Alapere', 'LAGOS'],
    ['Carloha V.I', 'Oriental', 'Lagos'],
    ['CARBON CAR CARE AND TYRES', '43, AKIN ADESOLA ST V.I., LAGOS', 'LAGOS'],
    ['CARBON CAR CARE AND TYRES', 'BY CIRCLE MALL, JAKANDE', 'LAGOS'],
    ['FLICK WHEEL AUTOS', '7, Etal Avenue, off Oregun Road, OREGUN, OJOTA', 'LAGOS'],
    ['AFFORDABLE CARS', '76, OPEBI ROAD, IKEJA', 'LAGOS'],
    ['AFFORDABLE CARS', 'LEKKI', 'LAGOS'],
    ['CARBON CAR CARE AND TYRES', 'IKATE, LEKKI-AJAH EXP. WAY', 'LEKKI'],
    ['AUTOPOINTE QUICK FIX', 'OGUNNUSI RD, OJODU, BESIDE STANBIC BANK, OJODU', 'OJODU, LAGOS'],
    ['AUTOPOINTE QUICK FIX', 'BY VIO SITE, BOLADE, OSHODI', 'OSHODI, LAGOS'],
    ['COMBINES SYSTEM LTD', 'CENTRAL', 'OSHOGBO'],
    ['SCOUCH MOTORS', '15, EZIMGBU LINK ROAD', 'PORT HARCOURT'],
    ['DANASCO MOTORS', '13A, aso street, eliminigwe Estate, Elelenwo', 'PORT HARCOURT'],
    ['T & T AUTOS', '7 EDMAC EXTENTION, OPPOSITE EDMAC AVENUE, OFF EAST WEST ROAD, PORT HARCOURT', 'PORT HARCOURT'],
    ['T & T AUTOS', '115, ABA ROAD, OPPOSITE APRICOT HOTEL', 'UMUAHIA'],
    ['DM MOTORS', '140, Aka road, Uyo', 'UYO'],
    ['Fudons Automobile Nigeria Ltd', 'Bayelsa Palm Express way', 'Yenagoa'],
];

$pdo->beginTransaction();
try {
    $imported = 0;
    $found = 0;
    $nameCount = [];

    $stmtCheck = $pdo->prepare("SELECT id FROM workshops WHERE name = ? AND deleted_at IS NULL");
    $stmtInsert = $pdo->prepare("INSERT INTO workshops (name, address, city, vendor_type, status) VALUES (?, ?, ?, 'Workshop', 'active')");

    foreach ($workshops as $w) {
        $baseName = trim($w[0]);
        $address = trim($w[1]);
        $city = trim($w[2]);

        // Make name unique by appending city for duplicate names
        if (!isset($nameCount[$baseName])) {
            $nameCount[$baseName] = 0;
        }
        $nameCount[$baseName]++;
        $suffix = $nameCount[$baseName];

        // Check if base name already exists in DB
        $stmtCheck->execute([$baseName]);
        $existingId = $stmtCheck->fetchColumn();

        $name = $baseName;
        if ($existingId && $suffix > 1) {
            // This branch name already exists in DB, and we've seen it before in the list
            $name = $baseName . ' (' . $city . ')';
        } elseif ($existingId && $suffix === 1) {
            // First occurrence but it exists in DB from a previous import
            $name = $baseName . ' (' . $city . ')';
        }

        // Check again with suffixed name
        if ($name !== $baseName) {
            $stmtCheck->execute([$name]);
            if ($stmtCheck->fetchColumn()) {
                echo "  Found existing: {$name}\n";
                $found++;
                continue;
            }
        } elseif ($existingId) {
            echo "  Found existing: {$name}\n";
            $found++;
            continue;
        }

        $stmtInsert->execute([$name, $address, $city]);
        $imported++;
        echo "  Created: {$name} ({$city})\n";
    }

    $pdo->commit();
    echo "\n=== Summary ===\nCreated: {$imported}, Already existed: {$found}\n";
} catch (Throwable $e) {
    $pdo->rollBack();
    echo "ERROR: {$e->getMessage()}\n";
    exit(1);
}
