<?php
require_once __DIR__.'/../includes/importer.php';
$admin = require_admin();
verify_csrf();
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'convert') {
    try {
        $id = (int)($_POST['id'] ?? 0);
        $seed = one('SELECT s.*, c.currency_code, c.timezone_default FROM mj_company_seed s LEFT JOIN mj_countries c ON c.id=s.country_id WHERE s.id=? LIMIT 1', [$id]);
        if (!$seed) { throw new RuntimeException('Seed row not found.'); }
        $tz = $seed['timezone'] ?: ($seed['timezone_default'] ?: 'UTC');
        $ownerEmail = $seed['email'] ?: ('company_'.$id.'@example.local');
        $userId = mj_user_id_by_email($ownerEmail, $seed['entity_name'].' Owner', (int)$seed['country_id'], $tz);
        $catId = mj_category_id_by_name($seed['category_text'] ?: 'Other Businesses', 'company');
        $slug = slugify($seed['entity_name']).'-'.substr(bin2hex(random_bytes(3)),0,6);
        q('INSERT INTO mj_companies(user_id,category_id,country_id,state_id,city_id,timezone,name,slug,registration_no,description,phone,email,website,address,latitude,longitude,status,is_verified,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,"active",0,NOW())', [
            $userId,$catId,(int)$seed['country_id'],$seed['state_id'],$seed['city_id'],$tz,$seed['entity_name'],$slug,$seed['uen'],$seed['services'] ?: $seed['primary_activity'],$seed['phone'],$seed['email'],$seed['website'],$seed['address_text'],$seed['latitude'],$seed['longitude']
        ]);
        $companyId = (int)db()->lastInsertId();
        q('INSERT INTO mj_company_branches(company_id,country_id,state_id,city_id,name,timezone,phone,email,address,is_main,is_active) VALUES(?,?,?,?,?,?,?,?,?,1,1)', [$companyId,(int)$seed['country_id'],$seed['state_id'],$seed['city_id'],'Main Branch',$tz,$seed['phone'],$seed['email'],$seed['address_text']]);
        foreach (preg_split('/[|;]+/', (string)$seed['services'], -1, PREG_SPLIT_NO_EMPTY) as $svc) {
            $svc = trim($svc);
            if ($svc !== '') { q('INSERT INTO mj_company_services(company_id,name,description,is_bookable) VALUES(?,?,?,0)', [$companyId,$svc,$svc]); }
        }
        q('UPDATE mj_company_seed SET is_claimed=1, claimed_company_id=? WHERE id=?', [$companyId,$id]);
        admin_log('convert_seed_to_company','mj_company_seed',$id,['company_id'=>$companyId]);
        flash('success','Business seed converted to company profile.');
        redirect('company-seed.php');
    } catch (Throwable $e) { flash('error',$e->getMessage()); redirect('company-seed.php'); }
}
$qry = trim($_GET['q'] ?? '');
$country = trim($_GET['country'] ?? '');
$params = [];
$where = 'WHERE 1=1';
if ($qry !== '') { $where .= ' AND (s.entity_name LIKE ? OR s.address_text LIKE ? OR s.services LIKE ? OR s.uen LIKE ?)'; $like='%'.$qry.'%'; $params = array_merge($params, [$like,$like,$like,$like]); }
if ($country !== '') { $where .= ' AND c.iso2=?'; $params[] = strtoupper($country); }
$rows = all_rows('SELECT s.*, c.name country_name, c.iso2 FROM mj_company_seed s LEFT JOIN mj_countries c ON c.id=s.country_id '.$where.' ORDER BY s.id DESC LIMIT 300', $params);
$countries = all_rows('SELECT iso2,name FROM mj_countries WHERE is_active=1 ORDER BY name');
$adminTitle = 'Business Seed';
include __DIR__.'/_header.php';
?>
<div class="admin-top"><h1>Business Seed / Unclaimed Companies</h1><a class="btn-primary" href="import-center.php">Import More</a></div>
<form class="card card-body form-row" method="get">
<input class="form-control" name="q" value="<?=e($qry)?>" placeholder="Search company, UEN, address, services">
<select class="form-control" name="country"><option value="">All countries</option><?php foreach($countries as $c): ?><option value="<?=e($c['iso2'])?>" <?=$country===$c['iso2']?'selected':''?>><?=e($c['name'])?></option><?php endforeach; ?></select>
<button class="btn-secondary">Search</button>
</form>
<table class="table"><tr><th>ID</th><th>Company</th><th>Country</th><th>Source</th><th>Address</th><th>Contact</th><th>Claimed</th><th>Action</th></tr>
<?php foreach($rows as $r): ?><tr>
<td><?=e($r['id'])?></td><td><b><?=e($r['entity_name'])?></b><br><small><?=e($r['uen'] ?: $r['source_ref'])?></small></td><td><?=e($r['country_name'])?></td><td><?=e($r['source'])?></td><td><?=e($r['address_text'])?></td><td><?=e(trim(($r['phone']?:'').' '.($r['email']?:'').' '.($r['website']?:'')))?></td><td><?=e($r['is_claimed']?'Yes':'No')?></td>
<td><?php if(!$r['is_claimed']): ?><form method="post"><?=csrf_input()?><input type="hidden" name="action" value="convert"><input type="hidden" name="id" value="<?=e($r['id'])?>"><button class="btn-secondary">Convert to Company</button></form><?php else: ?><a href="../company.php?id=<?=e($r['claimed_company_id'])?>" target="_blank">View</a><?php endif; ?></td>
</tr><?php endforeach; ?></table>
<?php include __DIR__.'/_footer.php'; ?>
