<?php
namespace App\Modules\System\Controllers;

/**
 * System Reset Controller
 * ⚠ DANGER ZONE — Irreversible data wipe for the authenticated user
 *
 * Security layers:
 * 1. POST-only   → rejects all GET requests
 * 2. CSRF token  → prevents cross-site forgery
 * 3. Confirmation phrase: user must type "DELETE ALL DATA"
 * 4. Password re-verification → confirms it's the real account owner
 * 5. DB transaction → all-or-nothing reset (no partial deletes)
 * 6. Rate limit: max 1 reset per 24h (stored in session)
 *
 * PRESERVES: users, user_settings, login_attempts (system tables)
 * WIPES:     all module data tables for the current user_id
 */
class ResetController extends \Core\Controller {

    /** Tables to wipe — ORDER MATTERS (children before parents due to FK) */
    private const WIPE_TABLES = [
        // Vault
        'vault_entries',

        // Health
        'health_med_logs',
        'health_water_logs',
        'health_blood_sugar',
        'health_symptoms_log',
        'health_activities',
        'health_labs',
        'health_meals',
        'health_fasts',
        'health_prescriptions',
        'health_medications',
        'health_weight_logs',
        'health_profile',

        // Finance
        'finance_expenses',
        'finance_incomes',
        'finance_installments',
        'finance_debts',
        'finance_investments',
        'finance_saving_goals',
        'fin_categories',

        // Habits
        'habit_logs',
        'habits',

        // Behavior / DES
        'behavior_logs',
        'behavior_habits',
        'behavior_identity_scores',

        // Journal
        'journal_entries',

        // Calendar
        'calendar_time_blocks',
        'calendar_events',

        // Todo
        'todo_daily_logs',
        'todo_tasks',

        // Spiritual
        'spiritual_charity',
        'spiritual_quran',
        'spiritual_adhkar',
        'spiritual_prayers',
        'spiritual_daily_logs',

        // Education
        'edu_courses',
        'edu_skills',
        'edu_programs',

        // Monthly Plans
        'monthly_plan_items',
        'monthly_plans',

        // Advisor & Reminders
        'advisor_memory',
        'reminder_logs',
        'smart_reminders',
        'notifications',
        'action_logs',
    ];

    public function execute() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect('/system/settings');
        }

        verify_csrf_token($_POST['csrf_token'] ?? '');

        $userId = $this->userId;
        if (!$userId) redirect('/auth/login');

        // ── Rate limit: 1 reset per 24h ───────────────────────────
        $lastReset = $_SESSION['last_system_reset'] ?? 0;
        if ((time() - $lastReset) < 86400 && $lastReset > 0) {
            $remaining = round((86400 - (time() - $lastReset)) / 3600, 1);
            set_flash_message('reset_error',
                "تم تنفيذ إعادة تعيين مؤخراً. يرجى الانتظار {$remaining} ساعة قبل المحاولة مرة أخرى.",
                'danger'
            );
            redirect('/system/settings');
        }

        // ── Verify confirmation phrase ────────────────────────────
        $phrase = trim($_POST['confirm_phrase'] ?? '');
        if ($phrase !== 'DELETE ALL DATA') {
            set_flash_message('reset_error',
                'العبارة التأكيدية غير صحيحة. يجب كتابة: DELETE ALL DATA بالضبط.',
                'danger'
            );
            redirect('/system/settings');
        }

        // ── Verify password ───────────────────────────────────────
        $password = $_POST['confirm_password'] ?? '';
        $db = \Core\Database::getInstance();
        $user = $db->query(
            "SELECT id, password_hash FROM users WHERE id = ? LIMIT 1",
            [$userId]
        )->fetch();

        if (!$user || !password_verify($password, $user->password_hash)) {
            set_flash_message('reset_error',
                'كلمة المرور غير صحيحة. لم يتم حذف أي بيانات.',
                'danger'
            );
            redirect('/system/settings');
        }

        // ── Execute reset inside a transaction ────────────────────
        try {
            $pdo = $db->getPDO();
            $pdo->beginTransaction();
            $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');

            $wiped   = 0;
            $skipped = [];
            foreach (self::WIPE_TABLES as $table) {
                try {
                    $stmt = $pdo->prepare("DELETE FROM `{$table}` WHERE user_id = ?");
                    $stmt->execute([$userId]);
                    $wiped += $stmt->rowCount();
                } catch (\PDOException $te) {
                    // Table doesn't exist in this installation — skip gracefully
                    $skipped[] = $table;
                }
            }

            $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
            $pdo->commit();

            // Reset user settings to defaults (keep the row, reset values)
            $db->query(
                "UPDATE user_settings SET
                    personality_mode = 'calm',
                    focus_mode       = 0,
                    onboarding_done  = 0,
                    theme            = 'light',
                    updated_at       = CURRENT_TIMESTAMP
                 WHERE user_id = ?",
                [$userId]
            );

            // Clear all session data except identity
            $savedId       = $_SESSION['user_id'];
            $savedUsername = $_SESSION['username'];
            session_unset();
            $_SESSION['user_id']             = $savedId;
            $_SESSION['username']            = $savedUsername;
            $_SESSION['_last_activity']      = time();
            $_SESSION['last_system_reset']   = time();
            $_SESSION['theme']               = 'light';
            $_SESSION['onboarding_done']     = false;

            // Log the action
            try {
                $db->query(
                    "INSERT INTO action_logs (user_id, module, action, description) VALUES (?, 'System', 'reset', ?)",
                    [$userId, "System reset executed. {$wiped} records deleted."]
                );
            } catch (\Throwable $le) {}

            set_flash_message('system',
                "✅ تم إعادة تعيين النظام بنجاح. تم حذف {$wiped} سجل من بياناتك.",
                'success'
            );
            redirect('/');

        } catch (\Throwable $e) {
            if (isset($pdo) && $pdo->inTransaction()) {
                $pdo->rollBack();
                $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');
            }
            error_log('[OTIS Reset] ' . $e->getMessage());
            set_flash_message('reset_error',
                'حدث خطأ غير متوقع أثناء إعادة التعيين. لم يتم حذف أي بيانات. تحقق من السجلات.',
                'danger'
            );
            redirect('/system/settings');
        }
    }
}
