<?php

declare(strict_types=1);

namespace SuperAdmin\Controllers;

/**
 * Super Admin System Settings Controller
 *
 * Manages system-wide settings that affect all branches:
 *   - Certificate generation cost (how much each certificate costs the branch)
 *   - Marksheet generation cost
 *   - ID card cost
 *   - Admit card cost
 *   - Referral commission percentage (earned by referring branch)
 *   - Default pass marks percentage
 *   - Grade system (marks ranges → grades)
 *   - Certificate serial number prefix
 *   - Verification portal URL
 *
 * Settings are stored in the `settings` table (using both setting_key/setting_value
 * AND key_name/value columns for compatibility).
 */
class SuperAdminSettingsController extends SuperAdminBaseController
{
    /** All settings managed by this controller */
    private const SETTINGS = [
        // Pricing (per document, in INR — deducted from branch wallet)
        'cert_cost_certificate'   => ['label' => 'Certificate Generation Cost (₹)', 'type' => 'number', 'default' => '50', 'group' => 'Document Pricing'],
        'cert_cost_marksheet'     => ['label' => 'Marksheet Generation Cost (₹)', 'type' => 'number', 'default' => '30', 'group' => 'Document Pricing'],
        'cert_cost_id_card'       => ['label' => 'ID Card Generation Cost (₹)', 'type' => 'number', 'default' => '10', 'group' => 'Document Pricing'],
        'cert_cost_admit_card'    => ['label' => 'Admit Card Generation Cost (₹)', 'type' => 'number', 'default' => '5', 'group' => 'Document Pricing'],
        'cert_cost_affiliation'   => ['label' => 'Affiliation Certificate Cost (₹)', 'type' => 'number', 'default' => '0', 'group' => 'Document Pricing'],
        'cert_cost_authorization' => ['label' => 'Authorization Letter Cost (₹)', 'type' => 'number', 'default' => '0', 'group' => 'Document Pricing'],

        // Referral
        'referral_commission_pct' => ['label' => 'Referral Commission (%)', 'type' => 'number', 'default' => '10', 'group' => 'Referral System',
            'help' => 'When a referred branch generates a certificate, the referring branch earns this % of the certificate cost.'],
        'referral_bonus_on_join'  => ['label' => 'Referral Join Bonus (₹)', 'type' => 'number', 'default' => '500', 'group' => 'Referral System',
            'help' => 'One-time bonus credited to referring branch when a new branch joins via their referral code.'],

        // Grading
        'grade_a_plus_min' => ['label' => 'A+ Grade — Min %', 'type' => 'number', 'default' => '90', 'group' => 'Grade System'],
        'grade_a_min'      => ['label' => 'A Grade — Min %', 'type' => 'number', 'default' => '80', 'group' => 'Grade System'],
        'grade_b_plus_min' => ['label' => 'B+ Grade — Min %', 'type' => 'number', 'default' => '70', 'group' => 'Grade System'],
        'grade_b_min'      => ['label' => 'B Grade — Min %', 'type' => 'number', 'default' => '60', 'group' => 'Grade System'],
        'grade_c_min'      => ['label' => 'C Grade — Min %', 'type' => 'number', 'default' => '40', 'group' => 'Grade System'],
        'default_pass_pct' => ['label' => 'Default Pass Marks %', 'type' => 'number', 'default' => '40', 'group' => 'Grade System'],

        // Certificate serial
        'cert_serial_prefix'      => ['label' => 'Certificate Serial Prefix', 'type' => 'text', 'default' => 'GMIND', 'group' => 'Serial Numbers',
            'help' => 'All certificate numbers will start with this prefix, e.g. GMIND-2026-00001'],
        'marksheet_serial_prefix' => ['label' => 'Marksheet Serial Prefix', 'type' => 'text', 'default' => 'MS', 'group' => 'Serial Numbers'],

        // Verification
        'verification_portal_url' => ['label' => 'Verification Portal URL', 'type' => 'url', 'default' => '', 'group' => 'Verification',
            'help' => 'Public URL where anyone can verify certificates/marksheets. Leave blank to use default (/verify).'],
    ];

    /**
     * Display settings form.
     */
    public function index(): void
    {
        requireSuperAdmin();

        // Fetch all current values from DB
        $currentValues = [];
        try {
            // Try new schema (setting_key/setting_value)
            $stmt = $this->db->query("SELECT `setting_key`, `setting_value` FROM `settings` WHERE `setting_key` IS NOT NULL AND `setting_key` != ''");
            $rows = $stmt->fetchAll() ?: [];
            foreach ($rows as $row) {
                $currentValues[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Throwable $e) {}

        try {
            // Also try legacy schema (key_name/value)
            $stmt = $this->db->query("SELECT `key_name`, `value` FROM `settings` WHERE `key_name` IS NOT NULL AND `key_name` != ''");
            $rows = $stmt->fetchAll() ?: [];
            foreach ($rows as $row) {
                if (!isset($currentValues[$row['key_name']]) || $currentValues[$row['key_name']] === '') {
                    $currentValues[$row['key_name']] = $row['value'];
                }
            }
        } catch (\Throwable $e) {}

        // Merge with defaults
        $settings = [];
        foreach (self::SETTINGS as $key => $config) {
            $settings[$key] = $currentValues[$key] ?? $config['default'];
        }

        // Group settings
        $groups = [];
        foreach (self::SETTINGS as $key => $config) {
            $groupName = $config['group'];
            if (!isset($groups[$groupName])) {
                $groups[$groupName] = [];
            }
            $groups[$groupName][$key] = $config;
        }

        $this->superAdminView('settings/index', [
            'title'       => 'System Settings',
            'currentPage' => 'settings',
            'settings'    => $settings,
            'groups'      => $groups,
        ]);
    }

    /**
     * Update all settings.
     */
    public function update(): void
    {
        requireSuperAdmin();
        $this->validateCsrf();

        $updated = 0;
        foreach (self::SETTINGS as $key => $config) {
            $value = trim($_POST[$key] ?? '');
            if ($value === '') $value = $config['default'];

            // Sanitize
            if ($config['type'] === 'number') {
                $value = (string) (float) $value;
            } else {
                $value = sanitize($value);
            }

            // Upsert into settings table (both schemas)
            try {
                $stmt = $this->db->prepare(
                    "INSERT INTO `settings` (`key_name`, `value`, `setting_key`, `setting_value`)
                     VALUES (:key, :value, :key2, :value2)
                     ON DUPLICATE KEY UPDATE
                        `setting_value` = :value3, `value` = :value4"
                );
                $stmt->execute([
                    ':key'    => $key,
                    ':value'  => $value,
                    ':key2'   => $key,
                    ':value2' => $value,
                    ':value3' => $value,
                    ':value4' => $value,
                ]);
                $updated++;
            } catch (\Throwable $e) {
                error_log("Setting update failed for '{$key}': " . $e->getMessage());
            }
        }

        $this->auditLog('settings_update', 'settings', null, "Updated {$updated} system settings");
        flash('success', "Settings updated successfully. ({$updated} settings saved)");
        redirect(BASE_PATH . '/super-admin/settings');
    }
}
