<?php
// ============================================================
//  MJPOS – Developer Controller
//  RESTRICTED: developer + super_admin only
// ============================================================
class DeveloperController extends Controller
{
    private function guard(): void
    {
        Auth::requireLogin();
        $role = Auth::role();

        // Allow: developer role, super_admin, admin, or any role with developer.access permission
        $allowed = in_array($role, ['developer','super_admin','admin'], true)
                || Auth::can('developer.access');

        if (!$allowed) {
            http_response_code(403);
            require APP_PATH . '/views/errors/403.php';
            exit;
        }
    }

    // ── Dashboard ────────────────────────────────────────────
    public function index(): void
    {
        $this->guard();

        // Table row counts
        $tables = [
            'sales'            => 'Sales',
            'sale_items'       => 'Sale Items',
            'sale_payments'    => 'Sale Payments',
            'purchases'        => 'Purchases',
            'purchase_items'   => 'Purchase Items',
            'expenses'         => 'Expenses',
            'cheque_tracking'  => 'Cheques',
            'customers'        => 'Customers',
            'suppliers'        => 'Suppliers',
            'products'         => 'Products',
            'stock_movements'  => 'Stock Movements',
            'activity_logs'    => 'Activity Logs',
            'customer_payments'=> 'Customer Payments',
        ];

        $counts = [];
        foreach ($tables as $tbl => $label) {
            try {
                $counts[$tbl] = ['label'=>$label, 'count'=>(int)Database::fetchColumn("SELECT COUNT(*) FROM `$tbl`")];
            } catch (Exception $e) {
                $counts[$tbl] = ['label'=>$label, 'count'=>'—'];
            }
        }

        // DB size
        $dbName = DB_NAME ?? 'mjpos_db';
        try {
            $dbSize = Database::fetchOne(
                "SELECT ROUND(SUM(data_length+index_length)/1024/1024,2) AS mb
                 FROM information_schema.tables
                 WHERE table_schema = ?", [$dbName]
            );
        } catch(Exception $e) {
            $dbSize = ['mb'=>'?'];
        }

        $pageTitle  = '🛠 Developer Tools';
        $breadcrumb = [['label'=>'Developer'],['label'=>'Tools']];
        ob_start();
        require APP_PATH . '/views/developer/index.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }

    // ── Clear data — confirm page ────────────────────────────
    public function clearConfirm(): void
    {
        $this->guard();

        $pageTitle  = '⚠ Clear Database — Confirm';
        $breadcrumb = [['label'=>'Developer','url'=>APP_URL.'/developer'],['label'=>'Clear Data']];
        ob_start();
        require APP_PATH . '/views/developer/clear_confirm.php';
        $content = ob_get_clean();
        require APP_PATH . '/views/layouts/main.php';
    }

    // ── Execute clear ────────────────────────────────────────
    public function clearExecute(): void
    {
        $this->guard();
        Auth::requireCsrf();

        $confirm1 = $this->post('confirm_text', '');
        $confirm2 = $this->post('confirm_check', '');
        $scope    = $this->post('scope', 'transactions');

        // Double confirmation
        if ($confirm1 !== 'CLEAR ALL DATA' || $confirm2 !== '1') {
            redirectWith(APP_URL.'/developer/clear', 'error',
                'Confirmation failed. Type exactly: CLEAR ALL DATA');
            return;
        }

        try {
            Database::execute('SET FOREIGN_KEY_CHECKS = 0');

            if ($scope === 'transactions' || $scope === 'full') {
                // ── Transaction data ─────────────────────────
                $transactionTables = [
                    'sale_payments', 'sale_items', 'sales',
                    'purchase_items', 'purchases',
                    'expenses',
                    'cheque_tracking',
                    'customer_payments',
                    'stock_movements',
                ];
                foreach ($transactionTables as $t) {
                    try { Database::execute("TRUNCATE TABLE `$t`"); } catch(Exception $e) {}
                }
                // Reset customer & supplier balances
                Database::execute('UPDATE customers SET current_balance=0, loyalty_points=0');
                Database::execute('UPDATE suppliers SET current_balance=0');
                // Reset product stock to 0
                Database::execute('UPDATE products SET current_stock=0');
            }

            if ($scope === 'full') {
                // ── Full clear: also remove customers/suppliers/products ──
                try { Database::execute("TRUNCATE TABLE customers"); } catch(Exception $e) {}
                try { Database::execute("TRUNCATE TABLE suppliers"); } catch(Exception $e) {}
                try { Database::execute("TRUNCATE TABLE products"); } catch(Exception $e) {}
                // Re-insert Walk-in customer
                Database::execute(
                    "INSERT INTO customers (id,customer_name,status) VALUES (1,'Walk-in Customer','active')"
                );
            }

            if ($scope === 'logs') {
                try { Database::execute("TRUNCATE TABLE activity_logs"); } catch(Exception $e) {}
            }

            Database::execute('SET FOREIGN_KEY_CHECKS = 1');

            // Reset auto-increments on key tables
            foreach(['sales','purchases','expenses','customers','suppliers','products'] as $t) {
                try { Database::execute("ALTER TABLE `$t` AUTO_INCREMENT = 1"); } catch(Exception $e) {}
            }

            $scopeLabel = match($scope) {
                'transactions' => 'Transaction Data',
                'full'         => 'Full User Data',
                'logs'         => 'Activity Logs',
                default        => $scope,
            };

            Auth::logAudit(Auth::id(), 'developer_clear', 'database',
                "DATABASE CLEARED: {$scopeLabel} by " . Auth::name());

            redirectWith(APP_URL.'/developer', 'success',
                "✅ {$scopeLabel} cleared successfully. Database is clean.");

        } catch (Exception $e) {
            Database::execute('SET FOREIGN_KEY_CHECKS = 1');
            redirectWith(APP_URL.'/developer/clear', 'error',
                'Clear failed: ' . $e->getMessage());
        }
    }
}