<?php
// ============================================================
//  db/seed.php — one-time data import
// ============================================================
//
//  Usage (from project root):
//     php db/seed.php
//
//  Or browse to /buylocal/db/seed.php ONCE after creating the DB
//  and running schema.sql. Delete this file (or gate it) after
//  running in production.
//
// ============================================================

require_once __DIR__ . '/../includes/db.php';

// Basic safety: only allow from CLI or localhost
$is_cli = (PHP_SAPI === 'cli');
$is_local = in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
if (!$is_cli && !$is_local) {
    http_response_code(403);
    exit("Seed script not accessible over the web. Run via CLI or delete this file.\n");
}

$categories = require __DIR__ . '/../data/categories.php';
$listings   = require __DIR__ . '/../data/listings.php';
$packages   = require __DIR__ . '/../data/packages.php';
$blog       = require __DIR__ . '/../data/blog.php';

$out = fn($msg) => print(($is_cli ? '' : '<p>') . $msg . ($is_cli ? "\n" : '</p>'));

$out('Seeding database…');

// -- Categories ------------------------------------------------
foreach ($categories as $i => $c) {
    db_exec(
        'INSERT IGNORE INTO categories (slug, name, icon, sort_order) VALUES (:slug,:name,:icon,:so)',
        ['slug' => $c['slug'], 'name' => $c['name'], 'icon' => $c['icon'] ?? null, 'so' => $i]
    );
}
$out('  ✓ ' . count($categories) . ' categories');

// -- Blog posts ------------------------------------------------
foreach ($blog as $p) {
    db_exec(
        'INSERT IGNORE INTO blog_posts (slug, title, excerpt, body, posted_at, published)
           VALUES (:s,:t,:e,:b,:d,1)',
        ['s' => $p['slug'], 't' => $p['title'], 'e' => $p['excerpt'],
         'b' => $p['body'], 'd' => $p['date']]
    );
}
$out('  ✓ ' . count($blog) . ' blog posts');

// -- Branding items --------------------------------------------
foreach ($packages['branding'] as $b) {
    // Extract first numeric chunk from price string as cents
    $cents = 0;
    if (preg_match('/(\d[\d ]*)/', $b['price'], $m)) {
        $cents = ((int)str_replace(' ', '', $m[1])) * 100;
    }
    db_exec(
        'INSERT IGNORE INTO branding_items (slug, name, price_cents, price_display, description)
           VALUES (:s,:n,:c,:d,:desc)',
        ['s' => $b['slug'], 'n' => $b['name'],
         'c' => $cents, 'd' => $b['price'], 'desc' => $b['description']]
    );
}
$out('  ✓ ' . count($packages['branding']) . ' branding items');

// -- Demo admin ------------------------------------------------
$admin_email = 'admin@buylocallowveld.co.za';
$existing_admin = db_row('SELECT id FROM members WHERE email = :e', ['e' => $admin_email]);
if (!$existing_admin) {
    db_insert('members', [
        'email'         => $admin_email,
        'password_hash' => password_hash('admin1234', PASSWORD_BCRYPT, ['cost' => AUTH_BCRYPT_COST]),
        'first_name'    => 'Site',
        'last_name'     => 'Admin',
        'business_name' => 'Buy Local Lowveld',
        'role'          => 'admin',
        'status'        => 'active',
        'tier'          => 'Platinum',
    ]);
    $out('  ✓ admin created: admin@buylocallowveld.co.za / admin1234 (CHANGE IN PRODUCTION)');
} else {
    $out('  ~ admin already exists');
}

// -- Dummy members for each Phase 1 listing --------------------
$default_pw = 'demo1234';
$default_hash = password_hash($default_pw, PASSWORD_BCRYPT, ['cost' => AUTH_BCRYPT_COST]);

foreach ($listings as $l) {
    $existing = db_row('SELECT id FROM members WHERE email = :e', ['e' => $l['email']]);

    if (!$existing) {
        // Parse "First Last" out of the business for the demo
        $names = explode(' ', $l['name'], 2);
        $member_id = db_insert('members', [
            'email'         => $l['email'],
            'password_hash' => $default_hash,
            'first_name'    => $names[0] ?? 'Owner',
            'last_name'     => $names[1] ?? 'Member',
            'phone'         => $l['phone'] ?? null,
            'business_name' => $l['name'],
            'industry'      => $l['category'],
            'tier'          => $l['tier'],
            'status'        => 'active',
            'join_date'     => date('Y-m-d', strtotime('-6 months')),
            'renewal_date'  => date('Y-m-d', strtotime('+6 months')),
            'banking_details' => "Bank: Example Bank\nAccount: 1234567890\nBranch: 250655",
        ]);
    } else {
        $member_id = (int)$existing['id'];
    }

    // Listing (one-shot insert, linked to the member)
    $has_listing = db_value('SELECT id FROM listings WHERE slug = :s', ['s' => $l['slug']]);
    if (!$has_listing) {
        db_insert('listings', [
            'member_id'     => $member_id,
            'slug'          => $l['slug'],
            'name'          => $l['name'],
            'category_slug' => $l['category'],
            'tier'          => $l['tier'],
            'featured'      => !empty($l['featured']) ? 1 : 0,
            'description'   => $l['description'],
            'phone'         => $l['phone'] ?? null,
            'email'         => $l['email'] ?? null,
            'website'       => $l['website'] ?? null,
            'address'       => $l['address'] ?? null,
        ]);
    }

    // Seed a paid membership invoice so View Statement has something to show
    $inv_number = 'INV-' . date('Y') . '-' . str_pad((string)$member_id, 4, '0', STR_PAD_LEFT);
    $has_inv = db_value('SELECT id FROM invoices WHERE number = :n', ['n' => $inv_number]);
    if (!$has_inv) {
        // NOTE: PHP 7.4-compatible — the original used match() which is 8.0+
        switch ($l['tier']) {
            case 'Silver':   $tier_price =  120000; break;
            case 'Gold':     $tier_price =  250000; break;
            case 'Platinum': $tier_price =  500000; break;
            case 'Diamond':  $tier_price = 1000000; break;
            case 'Bronze':
            default:         $tier_price =   50000;
        }
        $inv_id = db_insert('invoices', [
            'member_id'    => $member_id,
            'type'         => 'membership',
            'number'       => $inv_number,
            'description'  => $l['tier'] . ' membership (annual)',
            'amount_cents' => $tier_price,
            'status'       => 'paid',
            'issued_at'    => date('Y-m-d', strtotime('-6 months')),
            'due_at'       => date('Y-m-d', strtotime('-5 months')),
            'paid_at'      => date('Y-m-d H:i:s', strtotime('-5 months')),
        ]);
        // Matching transactions: charge + payment
        db_insert('transactions', [
            'member_id'    => $member_id,
            'invoice_id'   => $inv_id,
            'type'         => 'charge',
            'amount_cents' => $tier_price,
            'description'  => 'Membership charge',
            'occurred_at'  => date('Y-m-d H:i:s', strtotime('-6 months')),
        ]);
        db_insert('transactions', [
            'member_id'    => $member_id,
            'invoice_id'   => $inv_id,
            'type'         => 'payment',
            'amount_cents' => -$tier_price,
            'description'  => 'Payment received',
            'reference'    => 'SEED-' . $inv_id,
            'occurred_at'  => date('Y-m-d H:i:s', strtotime('-5 months')),
        ]);
    }
}
$out('  ✓ ' . count($listings) . ' members + listings + seed invoices');

$out('Done. Demo login: any of the listing emails above, password "demo1234"');
$out('Admin login: admin@buylocallowveld.co.za / admin1234');