<?php
class SAAuthController {
    public function showLogin(): void {
        if (SuperAuth::check()) redirect('superadmin');
        include APP_ROOT . '/views/superadmin/login.php';
    }

    public function login(): void {
        Security::checkCsrf();
        $identity = strtolower(trim($_POST['email'] ?? ''));
        $pass     = $_POST['password'] ?? '';

        $stmt = db()->prepare("SELECT * FROM superadmins WHERE (email=? OR username=?) AND is_active=1 LIMIT 1");
        $stmt->execute([$identity, $identity]);
        $admin= $stmt->fetch();

        if ($admin && Security::verifyPassword($pass, $admin['password'])) {
            SuperAuth::login($admin);
            redirect('superadmin');
        }

        flash('error', 'Invalid superadmin credentials');
        redirect('superadmin/login');
    }

    public function logout(): void {
        SuperAuth::logout();
        redirect('superadmin/login');
    }

    public function showPasswordReset(): void {
        include APP_ROOT . '/views/superadmin/password-reset.php';
    }

    public function resetPassword(): void {
        Security::checkCsrf();
        $password = $_POST['password'] ?? '';

        if (strlen($password) < 8) {
            flash('error', 'Password must be at least 8 characters long');
            redirect('superadmin/reset-password');
            return;
        }

        // Generate new password hash
        $hash = Security::hashPassword($password);

        // Update or insert superadmin
        $stmt = db()->prepare("SELECT id FROM superadmins WHERE email = ?");
        $stmt->execute(['superadmin@tellerpro.com']);
        $admin = $stmt->fetch();

        if ($admin) {
            $stmt = db()->prepare("UPDATE superadmins SET password = ?, is_active = 1 WHERE id = ?");
            $stmt->execute([$hash, $admin['id']]);
            flash('success', 'Password updated successfully!');
        } else {
            $stmt = db()->prepare("INSERT INTO superadmins (name, username, email, password, is_active, created_at) VALUES (?, ?, ?, ?, 1, NOW())");
            $stmt->execute(['Platform Admin', 'admin', 'superadmin@tellerpro.com', $hash]);
            flash('success', 'Superadmin user created successfully!');
        }

        redirect('superadmin/login');
    }

    /**
     * Performs a total system reset, wiping all tables and resetting IDs to 1.
     * Re-initializes the default superadmin account.
     */
    public function systemReset(): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();

        // One last safety check: verify the confirmation text
        if (($_POST['confirmation'] ?? '') !== 'SYSTEM RESET') {
            flash('error', 'Reset failed: You must type "SYSTEM RESET" to confirm.');
            redirect('superadmin');
            return;
        }

        try {
            db()->beginTransaction();

            // Disable foreign key checks for truncation
            db()->exec("SET FOREIGN_KEY_CHECKS = 0");

            $tables = [
                'plans', 'tenants', 'subscriptions', 'superadmins', 'audit_logs',
                'users', 'locations', 'categories', 'units', 'brands', 'products',
                'batches', 'stock', 'stock_movements', 'stock_adjustments',
                'stock_takings', 'stock_taking_items', 'stock_transfers',
                'stock_transfer_items', 'customers', 'suppliers', 'sales',
                'sale_items', 'purchases', 'purchase_items', 'payments',
                'settings', 'notifications', 'login_attempts', 'tax_groups',
                'roles', 'permissions', 'role_permissions', 'supplier_ledger',
                'customer_ledger'
            ];

            foreach ($tables as $table) {
                // TRUNCATE resets auto-increment IDs to 1
                db()->exec("TRUNCATE TABLE `$table` ");
            }

            // Re-initialize default Super Admin so we don't get locked out
            // Default password is 'admin123' for fresh start
            $defaultPass = Security::hashPassword('admin123');
            $stmt = db()->prepare("INSERT INTO superadmins (id, name, username, email, password, is_active, created_at) VALUES (1, 'Platform Admin', 'admin', 'superadmin@tellerpro.com', ?, 1, NOW())");
            $stmt->execute([$defaultPass]);

            // Re-enable foreign key checks
            db()->exec("SET FOREIGN_KEY_CHECKS = 1");

            db()->commit();

            // Log out from current session since superadmin table was truncated
            SuperAuth::logout();
            
            echo "<script>alert('System has been completely reset to factory settings. All IDs now start from 1. Default Login: superadmin@tellerpro.com / admin123'); window.location.href='" . APP_URL . "/superadmin/login';</script>";
            exit;

        } catch (Exception $e) {
            db()->rollBack();
            db()->exec("SET FOREIGN_KEY_CHECKS = 1");
            flash('error', 'System reset failed: ' . $e->getMessage());
            redirect('superadmin');
        }
    }
}
