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

try {
    $db = db();
    $db->beginTransaction();

    // 1. Clean up if exists
    $stmt = $db->prepare("SELECT id FROM tenants WHERE business_email = ?");
    $stmt->execute(['demo@tellerpro.com']);
    $existing = $stmt->fetch();
    if ($existing) {
        $db->prepare("DELETE FROM tenants WHERE id = ?")->execute([$existing['id']]);
    }

    // 2. Create Tenant
    $db->prepare("INSERT INTO tenants (slug, business_name, business_email, status, trial_ends_at) VALUES (?,?,?,?,?)")
       ->execute(['demo-store', 'Demo Store', 'demo@tellerpro.com', 'active', '2030-01-01']);
    $tenantId = $db->lastInsertId();

    // 3. Create Admin User
    $password = Security::hashPassword('Password@123');
    $db->prepare("INSERT INTO users (tenant_id, name, email, password, role) VALUES (?,?,?,?,?)")
       ->execute([$tenantId, 'Demo Manager', 'demo@tellerpro.com', $password, 'admin']);

    // 4. Create Location
    $db->prepare("INSERT INTO locations (tenant_id, name, code, type) VALUES (?,?,?,?)")
       ->execute([$tenantId, 'Main Warehouse', 'MW-01', 'warehouse']);

    // 5. Subscribe to Pro Plan (assumes plan with id 2 exists)
    $db->prepare("INSERT INTO subscriptions (tenant_id, plan_id, amount, billing_cycle, status) VALUES (?,?,?,?,?)")
       ->execute([$tenantId, 2, 29.00, 'monthly', 'active']);

    $db->commit();
    echo "SUCCESS: Demo account created.\n";
    echo "Email: demo@tellerpro.com\n";
    echo "Password: Password@123\n";

} catch (Exception $e) {
    if ($db->inTransaction()) $db->rollBack();
    echo "ERROR: " . $e->getMessage() . "\n";
}
