<?php
// organization/includes/org_heal.php
// ---------------------------------------------------------------------------
// Self-healing routine for the Organisation data model.
//
// The users.role ENUM originally shipped WITHOUT 'org_admin' / 'org_staff'.
// Because of that, every account created for an organisation was saved with an
// empty role — so org admins could not log in, staff never appeared in any
// list, and the wallet-creation trigger (which keys off role='org_staff')
// never fired, leaving those staff with no wallet to fund.
//
// dabil_org_heal() makes the schema and data correct. It is safe to call on
// every relevant page load: it only does work when something actually needs
// fixing, and all statements are idempotent.
// ---------------------------------------------------------------------------

if (!function_exists('dabil_org_heal')) {
    function dabil_org_heal(mysqli $conn): void {

        // 1) Ensure the role ENUM supports the organisation roles.
        $needs_alter = true;
        if ($res = @$conn->query(
            "SELECT COLUMN_TYPE FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'role'"
        )) {
            $type = (string)($res->fetch_row()[0] ?? '');
            if ($type !== '' && strpos($type, "'org_admin'") !== false && strpos($type, "'org_staff'") !== false) {
                $needs_alter = false;
            }
        }
        if ($needs_alter) {
            @$conn->query(
                "ALTER TABLE `users` MODIFY COLUMN `role`
                 ENUM('super_admin','restaurant_admin','staff','waiter','customer','org_admin','org_staff')
                 NOT NULL DEFAULT 'customer'"
            );
        }

        // 2) Repair accounts that were saved with a blank role.
        //    Staff carry an employee_id or a department; the org admin has neither.
        //    Do staff first, then treat any remaining org-linked blank rows as the admin.
        @$conn->query(
            "UPDATE users SET role = 'org_staff'
             WHERE (role = '' OR role IS NULL) AND organization_id IS NOT NULL
               AND ((employee_id IS NOT NULL AND employee_id <> '')
                    OR (department IS NOT NULL AND department <> ''))"
        );
        @$conn->query(
            "UPDATE users SET role = 'org_admin'
             WHERE (role = '' OR role IS NULL) AND organization_id IS NOT NULL"
        );

        // 3) Backfill the wallets the insert-trigger would have created for staff.
        @$conn->query(
            "INSERT INTO wallets (user_id, wallet_type, balance, created_at)
             SELECT u.id, 'customer', 0.00, NOW() FROM users u
             WHERE u.role = 'org_staff'
               AND NOT EXISTS (SELECT 1 FROM wallets w WHERE w.user_id = u.id AND w.wallet_type = 'customer')"
        );
        @$conn->query(
            "INSERT INTO wallets (user_id, wallet_type, organization_id, balance, created_at)
             SELECT u.id, 'meal_ticket', u.organization_id, 0.00, NOW() FROM users u
             WHERE u.role = 'org_staff'
               AND NOT EXISTS (SELECT 1 FROM wallets w WHERE w.user_id = u.id AND w.wallet_type = 'meal_ticket')"
        );
    }
}
