<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = ['success' => false, 'message' => '', 'settings' => [], 'channels' => [], 'employees' => []];

if (!isLoggedIn() || getCurrentUser()['role'] !== 'admin') {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

try {
    // Fetch general system settings
    $stmt = $pdo->query("SELECT key, value FROM system_settings");
    $response['settings'] = $stmt->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];

    // Fetch notification channels settings
    $stmt_chan = $pdo->query("SELECT * FROM notification_channels");
    $response['channels'] = $stmt_chan->fetchAll(PDO::FETCH_ASSOC) ?: [];

    // Fetch all employees for default referrer code dropdown
    $stmt_emp = $pdo->query("SELECT id, username, employee_code FROM users WHERE employee_code IS NOT NULL AND employee_code != '' ORDER BY username ASC");
    $response['employees'] = $stmt_emp->fetchAll(PDO::FETCH_ASSOC) ?: [];
    $response['success'] = true;
} catch (PDOException $e) { }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['success'] = false;
        $response['message'] = "Security check failed (CSRF).";
        echo json_encode($response);
        exit();
    }

    if (isset($_POST['save_channel'])) {
        $channel_name = trim($_POST['channel_name'] ?? '');
        $is_enabled = isset($_POST['is_enabled']) ? 1 : 0;
        
        $config_data = [];
        if ($channel_name === 'email') {
            $config_data['smtp_host'] = trim($_POST['smtp_host'] ?? '');
            $config_data['smtp_port'] = trim($_POST['smtp_port'] ?? '');
            $config_data['smtp_user'] = trim($_POST['smtp_user'] ?? '');
            $config_data['smtp_pass'] = trim($_POST['smtp_pass'] ?? '');
        } elseif ($channel_name === 'sms') {
            $config_data['provider'] = trim($_POST['sms_provider'] ?? 'twilio');
            $config_data['account_sid'] = trim($_POST['sms_sid'] ?? '');
            $config_data['auth_token'] = trim($_POST['sms_token'] ?? '');
        } elseif ($channel_name === 'whatsapp') {
            $config_data['api_url'] = trim($_POST['wa_url'] ?? '');
            $config_data['token'] = trim($_POST['wa_token'] ?? '');
        } elseif ($channel_name === 'telegram') {
            $config_data['bot_token'] = trim($_POST['tg_token'] ?? '');
            $config_data['chat_id'] = trim($_POST['tg_chat'] ?? '');
        } elseif ($channel_name === 'push') {
            $config_data['app_id'] = trim($_POST['push_app_id'] ?? '');
            $config_data['api_key'] = trim($_POST['push_key'] ?? '');
        }

        try {
            $stmt = $pdo->prepare("
                INSERT INTO notification_channels (channel_name, is_enabled, config_json) 
                VALUES (?, ?, ?) 
                ON CONFLICT (channel_name) 
                DO UPDATE SET is_enabled = EXCLUDED.is_enabled, config_json = EXCLUDED.config_json
            ");
            $stmt->execute([$channel_name, $is_enabled, json_encode($config_data)]);
            $response['success'] = true;
            $response['message'] = "Channel config updated.";
        } catch (PDOException $e) {
            $response['success'] = false;
            $response['message'] = "Database error: " . $e->getMessage();
        }
    } elseif (isset($_POST['save_general'])) {
        $prefix = trim($_POST['emp_code_prefix'] ?? 'REPL');
        $length = (int)($_POST['emp_code_length'] ?? 15);
        
        if (strlen($prefix) < 4 || strlen($prefix) > 5) {
            $response['success'] = false;
            $response['message'] = "Employee code prefix must be exactly 4 or 5 characters.";
            echo json_encode($response);
            exit();
        } elseif ($length < 15 || $length > 30) {
            $response['success'] = false;
            $response['message'] = "Employee code target length must be between 15 and 30 characters.";
            echo json_encode($response);
            exit();
        } elseif ($length <= strlen($prefix)) {
            $response['success'] = false;
            $response['message'] = "Employee code target length must be greater than prefix length.";
            echo json_encode($response);
            exit();
        }

        $min_dep = (float)($_POST['bank_verification_min_deposit'] ?? 1.01);
        $max_dep = (float)($_POST['bank_verification_max_deposit'] ?? 1.99);

        if ($min_dep < 0) {
            $response['success'] = false;
            $response['message'] = "Minimum deposit amount cannot be negative.";
            echo json_encode($response);
            exit();
        } elseif ($max_dep < 0) {
            $response['success'] = false;
            $response['message'] = "Maximum deposit amount cannot be negative.";
            echo json_encode($response);
            exit();
        } elseif ($min_dep > $max_dep) {
            $response['success'] = false;
            $response['message'] = "Minimum deposit amount cannot be greater than the maximum deposit amount.";
            echo json_encode($response);
            exit();
        }

        $settings = [
            'site_name' => trim($_POST['site_name'] ?? 'RENENET EDUCARE'),
            'site_tagline' => trim($_POST['site_tagline'] ?? ''),
            'site_logo' => trim($_POST['site_logo'] ?? ''),
            'site_favicon' => trim($_POST['site_favicon'] ?? ''),
            'hide_site_name' => isset($_POST['hide_site_name']) ? '1' : '0',
            'registration_mode' => trim($_POST['registration_mode'] ?? 'invite_only'),
            'default_referrer_code' => trim($_POST['default_referrer_code'] ?? ''),
            
            'company_email' => trim($_POST['company_email'] ?? ''),
            'company_address' => trim($_POST['company_address'] ?? ''),
            'company_gstin' => trim($_POST['company_gstin'] ?? ''),
            'gst_rate' => (float)($_POST['gst_rate'] ?? 18.00),
            
            'default_referral_commission' => (float)($_POST['default_referral_commission'] ?? 10.00),
            'signup_bonus' => (float)($_POST['signup_bonus'] ?? 0.00),
            'referral_bonus' => (float)($_POST['referral_bonus'] ?? 0.00),
            'referral_bonus_levels' => (int)($_POST['referral_bonus_levels'] ?? 1),
            'referral_bonus_cap' => (float)($_POST['referral_bonus_cap'] ?? 0.00),
            
            'emp_code_prefix' => $prefix,
            'emp_code_length' => $length,
            'emp_code_default_type' => trim($_POST['emp_code_default_type'] ?? 'generated'),
            'emp_code_custom_value' => trim($_POST['emp_code_custom_value'] ?? ''),
            
            'razorpay_key_id' => trim($_POST['razorpay_key_id'] ?? ''),
            'razorpay_key_secret' => trim($_POST['razorpay_key_secret'] ?? ''),
            
            'bank_verification_min_deposit' => (float)($_POST['bank_verification_min_deposit'] ?? 1.01),
            'bank_verification_max_deposit' => (float)($_POST['bank_verification_max_deposit'] ?? 1.99),
            'default_kyc_required_docs' => (int)($_POST['default_kyc_required_docs'] ?? 2),

            'footer_copyright_text' => trim($_POST['footer_copyright_text'] ?? ''),
            'footer_about_text' => trim($_POST['footer_about_text'] ?? ''),
            'footer_facebook_url' => trim($_POST['footer_facebook_url'] ?? ''),
            'footer_twitter_url' => trim($_POST['footer_twitter_url'] ?? ''),
            'footer_linkedin_url' => trim($_POST['footer_linkedin_url'] ?? ''),
            'footer_instagram_url' => trim($_POST['footer_instagram_url'] ?? '')
        ];

        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO system_settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value");
            foreach ($settings as $k => $v) {
                $stmt->execute([$k, (string)$v]);
            }
            $pdo->commit();
            $response['success'] = true;
            $response['message'] = "General settings updated successfully.";
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            $response['success'] = false;
            $response['message'] = "Database error: " . $e->getMessage();
        }
    }
}

echo json_encode($response);
