<?php
class SATenantsController {
    public function index(): void {
        SuperAuth::requireLogin();
        $tenants = db()->query("SELECT * FROM tenants ORDER BY created_at DESC")->fetchAll();
        $pageTitle = 'Manage Tenants';
        ob_start();
        include APP_ROOT . '/views/superadmin/tenants/index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/superadmin/layout.php';
    }

    public function show(string $id): void {
        SuperAuth::requireLogin();
        $tenant = db()->prepare("SELECT * FROM tenants WHERE id=?");
        $tenant->execute([$id]);
        $tenant = $tenant->fetch();

        if (!$tenant) { flash('error', 'Tenant not found'); redirect('superadmin/tenants'); }

        $sub = db()->prepare("SELECT s.*, p.name as plan_name FROM subscriptions s JOIN plans p ON p.id=s.plan_id WHERE s.tenant_id=? ORDER BY s.created_at DESC LIMIT 1");
        $sub->execute([$id]);
        $subscription = $sub->fetch();

        $pageTitle = 'View Tenant: ' . e($tenant['business_name']);
        ob_start();
        include APP_ROOT . '/views/superadmin/tenants/show.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/superadmin/layout.php';
    }

    public function suspend(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();
        db()->prepare("UPDATE tenants SET status='suspended' WHERE id=?")->execute([$id]);
        flash('warning', 'Tenant suspended successfully');
        redirect('superadmin/tenants/' . $id);
    }

    public function activate(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();
        db()->prepare("UPDATE tenants SET status='active' WHERE id=?")->execute([$id]);
        flash('success', 'Tenant activated successfully');
        redirect('superadmin/tenants/' . $id);
    }

    public function loginAsAdmin(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();

        // Get tenant info
        $tenant = db()->prepare("SELECT * FROM tenants WHERE id=?");
        $tenant->execute([$id]);
        $tenant = $tenant->fetch();

        if (!$tenant) { flash('error', 'Tenant not found'); redirect('superadmin/tenants'); }

        // Find admin user for this tenant
        $user = db()->prepare("SELECT * FROM users WHERE tenant_id=? AND role IN ('admin','owner') AND is_active=1 LIMIT 1");
        $user->execute([$id]);
        $user = $user->fetch();

        if (!$user) { flash('error', 'No active admin user found for this tenant'); redirect('superadmin/tenants/' . $id); }

        // Log in as the tenant admin
        Auth::login($user, $tenant);
        flash('success', 'Logged in as ' . e($user['name']));
        redirect('dashboard');
    }

    public function resetPassword(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();

        // Get tenant info
        $tenant = db()->prepare("SELECT * FROM tenants WHERE id=?");
        $tenant->execute([$id]);
        $tenant = $tenant->fetch();

        if (!$tenant) { flash('error', 'Tenant not found'); redirect('superadmin/tenants'); }

        // Find admin user for this tenant
        $user = db()->prepare("SELECT * FROM users WHERE tenant_id=? AND role IN ('admin','owner') LIMIT 1");
        $user->execute([$id]);
        $user = $user->fetch();

        if (!$user) { flash('error', 'No admin user found for this tenant'); redirect('superadmin/tenants/' . $id); }

        // Generate new random password
        $newPassword = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'), 0, 12);
        $hashedPassword = Security::hashPassword($newPassword);

        // Update password
        db()->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hashedPassword, $user['id']]);

        flash('success', 'Password reset successfully. New password: ' . $newPassword);
        redirect('superadmin/tenants/' . $id);
    }

    public function destroy(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();

        try {
            db()->beginTransaction();

            // 1. Delete dependent transaction records that lack ON DELETE CASCADE or block deletion
            // Purchase Items & Purchases
            db()->prepare("DELETE FROM purchase_items WHERE tenant_id=?")->execute([$id]);
            db()->prepare("DELETE FROM purchases WHERE tenant_id=?")->execute([$id]);

            // Sale Items & Sales
            db()->prepare("DELETE FROM sale_items WHERE tenant_id=?")->execute([$id]);
            db()->prepare("DELETE FROM sales WHERE tenant_id=?")->execute([$id]);

            // Stock Transfer Items & Transfers
            db()->prepare("DELETE FROM stock_transfer_items WHERE tenant_id=?")->execute([$id]);
            db()->prepare("DELETE FROM stock_transfers WHERE tenant_id=?")->execute([$id]);

            // Stock Movements (redundant as it has cascade, but for safety)
            db()->prepare("DELETE FROM stock_movements WHERE tenant_id=?")->execute([$id]);

            // Payments
            db()->prepare("DELETE FROM payments WHERE tenant_id=?")->execute([$id]);

            // Finally delete the tenant (this will cascade to users, locations, products, etc.)
            db()->prepare("DELETE FROM tenants WHERE id=?")->execute([$id]);

            db()->commit();
            flash('warning', 'Tenant account and all related data purged successfully');
        } catch (Exception $e) {
            db()->rollBack();
            error_log("Failed to delete tenant $id: " . $e->getMessage());
            flash('error', 'Error deleting tenant: ' . $e->getMessage());
        }

        redirect('superadmin/tenants');
    }
}

