<?php
/**
 * Agentic Square - Premium Administrative Core General Settings Engine
 * CodeCanyon Secure Execution Core Template Architecture
 */

// Inject Core Global Application Engine Paths
require_once __DIR__ . '/../config/config.php';

/**
 * STRICT SECURITY AUDIT GUARD (Envato Marketplace Compliant)
 */
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$success_message = '';
$error_message   = '';

ensure_transaction_fee_schema();

try {
    $seoColumn = $pdo->query("SHOW COLUMNS FROM general_settings LIKE 'seo_meta_title'")->fetch(PDO::FETCH_ASSOC);

    if (!$seoColumn) {
        $pdo->exec("ALTER TABLE general_settings ADD COLUMN seo_meta_title VARCHAR(255) NULL AFTER business_name");
    }

    $gtmColumn = $pdo->query("SHOW COLUMNS FROM general_settings LIKE 'gtm_container_id'")->fetch(PDO::FETCH_ASSOC);

    if (!$gtmColumn) {
        $pdo->exec("ALTER TABLE general_settings ADD COLUMN gtm_container_id VARCHAR(32) NULL AFTER seo_meta_title");
    }
} catch (\PDOException $e) {
    $error_message = "Metadata column check failed: " . $e->getMessage();
}

// ------------------------------------------------------------------------
// ACTION ROUTER: Handle Form Update Form Post Requests
// ------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize basic text strings
    $business_name   = filter_var(trim($_POST['business_name'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $seo_meta_title  = filter_var(trim($_POST['seo_meta_title'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $gtm_container_id = strtoupper(trim($_POST['gtm_container_id'] ?? ''));
    $gtm_container_id = preg_match('/^GTM-[A-Z0-9]+$/', $gtm_container_id) ? $gtm_container_id : '';
    $support_email = filter_var(
    trim($_POST['support_email'] ?? ''),
    FILTER_SANITIZE_EMAIL
);
    $contact_address = filter_var(trim($_POST['contact_address'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $city            = filter_var(trim($_POST['city'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $state           = filter_var(trim($_POST['state'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $post_code       = filter_var(trim($_POST['post_code'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $country         = filter_var(trim($_POST['country'] ?? ''), FILTER_SANITIZE_SPECIAL_CHARS);
    $currency        = filter_var(trim($_POST['currency'] ?? 'USD'), FILTER_SANITIZE_SPECIAL_CHARS);
    $commission_type = in_array($_POST['commission_type'] ?? '', ['fixed', 'percentage']) ? $_POST['commission_type'] : 'percentage';
    $commission_rate = filter_var($_POST['commission_rate'] ?? 0, FILTER_VALIDATE_FLOAT);
    $transaction_fee_rate = filter_var($_POST['transaction_fee_rate'] ?? 0, FILTER_VALIDATE_FLOAT);
    $timezone        = filter_var(trim($_POST['timezone'] ?? 'UTC'), FILTER_SANITIZE_SPECIAL_CHARS);

    if ($transaction_fee_rate === false || $transaction_fee_rate < 0) {
        $transaction_fee_rate = 0.00;
    }
    
    // NEW ELEMENT: Extract, validate, and isolate minimum withdrawal threshold limits
    $min_withdrawal_amount = filter_var($_POST['min_withdrawal_amount'] ?? 0, FILTER_VALIDATE_FLOAT);
    if ($min_withdrawal_amount === false || $min_withdrawal_amount < 0) {
        $min_withdrawal_amount = 0.00;
    }

    // Dynamic Image File Processing Pipeline
    $logo_destination = $_POST['existing_logo'] ?? '';
    
    if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] === UPLOAD_ERR_OK) {
        $file_tmp_path = $_FILES['logo_file']['tmp_name'];
        $file_name     = $_FILES['logo_file']['name'];
        $file_size     = $_FILES['logo_file']['size'];
        
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'svg', 'webp'];
        
        // Enforce production security rules on corporate assets upload variables
        if (in_array($file_ext, $allowed_extensions) && $file_size <= 2097152) { // 2MB Bounds
            $upload_dir = __DIR__ . '/../uploads/branding/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $new_file_name    = 'logo_' . time() . '.' . $file_ext;
            $target_file_path = $upload_dir . $new_file_name;
            
            if (move_uploaded_file($file_tmp_path, $target_file_path)) {
                $logo_destination = 'uploads/branding/' . $new_file_name;
            }
        } else {
            $error_message = "Invalid logo format or file size exceeded boundaries (Max 2MB PNG/SVG/JPG/WebP).";
        }
    }

    if (empty($error_message)) {
        try {
            // Force strict targeted atomic replacement query matching index unit 1
            $update_sql = "UPDATE general_settings SET 
                business_name = :business_name,
                seo_meta_title = :seo_meta_title,
                gtm_container_id = :gtm_container_id,
                support_email = :support_email,
                logo_path = :logo_path,
                contact_address = :contact_address,
                city = :city,
                state = :state,
                post_code = :post_code,
                country = :country,
                currency = :currency,
                commission_type = :commission_type,
                commission_rate = :commission_rate,
                transaction_fee_rate = :transaction_fee_rate,
                min_withdrawal_amount = :min_withdrawal_amount,
                timezone = :timezone
                WHERE id = 1";
                
            $stmt = $pdo->prepare($update_sql);
            $stmt->execute([
                'business_name'         => $business_name,
                'seo_meta_title'        => $seo_meta_title,
                'gtm_container_id'      => $gtm_container_id,
                'support_email' => $support_email,
                'logo_path'              => $logo_destination,
                'contact_address'        => $contact_address,
                'city'                   => $city,
                'state'                  => $state,
                'post_code'              => $post_code,
                'country'                => $country,
                'currency'               => $currency,
                'commission_type'        => $commission_type,
                'commission_rate'        => $commission_rate,
                'transaction_fee_rate'   => $transaction_fee_rate,
                'min_withdrawal_amount'  => $min_withdrawal_amount,
                'timezone'               => $timezone
            ]);
            
            $success_message = "Global operational settings matrix updated successfully.";
        } catch (\PDOException $e) {
            $error_message = "Database operational write constraint violation: " . $e->getMessage();
        }
    }
}

// ------------------------------------------------------------------------
// DATA POPULATION LAYER: Hydrate Active Interface Content
// ------------------------------------------------------------------------
$settings = $pdo->query("SELECT * FROM general_settings WHERE id = 1 LIMIT 1")->fetch();

// Arrays configuration loaders for selectors
$currencies = ['USD' => 'US Dollar ($)', 'EUR' => 'Euro (€)', 'GBP' => 'Pound Sterling (£)', 'CAD' => 'Canadian Dollar (C$)', 'AUD' => 'Australian Dollar (A$)', 'JPY' => 'Japanese Yen (¥)', 'INR' => 'Indian Rupee (₹)', 'SGD' => 'Singapore Dollar (S$)'];
$timezones  = DateTimeZone::listIdentifiers();

// Inject standard secure UI Header Wrapper layout component
$page_title = 'General Settings';
require_once __DIR__ . '/../sections/header.php';
?>

<div class="min-h-screen bg-nftDark text-white antialiased">
    
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-12 px-4 sm:px-6 lg:px-8 transition-all duration-300">
        <div class="max-w-4xl mx-auto space-y-8">
            
            <div class="flex items-center space-x-2 text-xs text-nftTextGray uppercase tracking-widest font-bold">
                <a href="settings.php" class="hover:text-nftAccentCyan transition-colors">Settings Hub</a>
                <span>/</span>
                <span class="text-white">// Core Configuration</span>
            </div>

            <div class="border-b border-slate-900 pb-6">
                <h1 class="text-3xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-white to-nftAccentCyan">General Engine Configurations</h1>
                <p class="text-sm text-nftTextGray mt-1">Control system identity parameters, business vectors, fiscal properties, and localized chronologies.</p>
            </div>

            <?php if (!empty($success_message)): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl text-sm flex items-center space-x-2">
                    <i class="fa-solid fa-circle-check text-base"></i>
                    <span><?php echo $success_message; ?></span>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($error_message)): ?>
                <div class="bg-rose-500/10 border border-rose-500/20 text-rose-400 p-4 rounded-xl text-sm flex items-center space-x-2">
                    <i class="fa-solid fa-triangle-exclamation text-base"></i>
                    <span><?php echo $error_message; ?></span>
                </div>
            <?php endif; ?>

            <form action="general-setting.php" method="POST" enctype="multipart/form-data" class="space-y-6">
                <input type="hidden" name="existing_logo" value="<?php echo htmlspecialchars($settings['logo_path'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-6">
                    <h2 class="text-base font-bold text-nftAccentCyan flex items-center space-x-2">
                        <i class="fa-solid fa-building-columns text-sm"></i>
                        <span>Platform Identity Blueprint</span>
                    </h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 items-center">
                        <div class="md:col-span-1 space-y-2">
                            <label class="block text-xs font-bold uppercase tracking-wider text-nftTextGray">Global Platform Logo</label>
                            <div class="border border-dashed border-slate-800 bg-slate-950/40 rounded-xl p-4 flex flex-col items-center justify-center text-center space-y-3 relative group">
                                <?php if (!empty($settings['logo_path'])): ?>
                                    <img src="../<?php echo htmlspecialchars($settings['logo_path'], ENT_QUOTES, 'UTF-8'); ?>" class="max-h-12 object-contain rounded" alt="Corporate Brand Logo">
                                <?php else: ?>
                                    <i class="fa-solid fa-circle-user text-3xl text-slate-700"></i>
                                <?php endif; ?>
                                <span class="text-[10px] text-nftTextGray block group-hover:text-nftAccentCyan transition-colors">Change Image Asset</span>
                                <input type="file" name="logo_file" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
                            </div>
                        </div>
                        
                        <div class="md:col-span-2 space-y-4">
	                            <div class="space-y-1">
	                                <label for="business_name" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Registered Business Name</label>
	                                <input type="text" id="business_name" name="business_name" required value="<?php echo htmlspecialchars($settings['business_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
	                            </div>
	                            <div class="space-y-1">
	                                <label for="seo_meta_title" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">SEO Meta Title</label>
	                                <input type="text" id="seo_meta_title" name="seo_meta_title" maxlength="255" value="<?php echo htmlspecialchars($settings['seo_meta_title'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="Agentic Square - Premium AI Marketplace" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all">
	                                <p class="text-[11px] text-slate-500">Home page title uses this directly. Other pages append it after the page title.</p>
	                            </div>
	                            <div class="space-y-1">
	                                <label for="gtm_container_id" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Google Tag Manager Container ID</label>
	                                <input type="text" id="gtm_container_id" name="gtm_container_id" maxlength="32" value="<?php echo htmlspecialchars($settings['gtm_container_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="GTM-XXXXXXX" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all font-mono uppercase">
	                                <p class="text-[11px] text-slate-500">Paste only the GTM container ID. The site will place the head script and body noscript automatically.</p>
	                            </div>
		                        </div>
                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4">
                    <h2 class="text-base font-bold text-nftAccentPurple flex items-center space-x-2">
                        <i class="fa-solid fa-map-location-dot text-sm"></i>
                        <span>Corporate Location Coordinates</span>
                    </h2>
                    
                    <div class="space-y-1">
                        <label for="contact_address" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Street Fulfillment Address</label>
                        <input type="text" id="contact_address" name="contact_address" value="<?php echo htmlspecialchars($settings['contact_address'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                    </div>

                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div class="space-y-1">
                            <label for="city" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">City</label>
                            <input type="text" id="city" name="city" value="<?php echo htmlspecialchars($settings['city'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                        </div>
                        <div class="space-y-1">
                            <label for="state" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">State / Region</label>
                            <input type="text" id="state" name="state" value="<?php echo htmlspecialchars($settings['state'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                        </div>
                        <div class="space-y-1">
                            <label for="post_code" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Postal / ZIP Code</label>
                            <input type="text" id="post_code" name="post_code" value="<?php echo htmlspecialchars($settings['post_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                        </div>
                        <div class="space-y-1">
                            <label for="country" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Country</label>
                            <input type="text" id="country" name="country" value="<?php echo htmlspecialchars($settings['country'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                        </div>
                        
                    </div>
                    <div class="space-y-1">
    <label for="support_email" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">
        Support Email
    </label>

    <input
        type="email"
        id="support_email"
        name="support_email"
        value="<?php echo htmlspecialchars($settings['support_email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
        placeholder="support@example.com"
        class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white placeholder-slate-600 focus:outline-none transition-all"
    >
</div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4">
                    <h2 class="text-base font-bold text-nftAccentCyan flex items-center space-x-2">
                        <i class="fa-solid fa-money-bill-transfer text-sm"></i>
                        <span>Transactional & Settlement Matrix</span>
                    </h2>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="space-y-1">
                            <label for="currency" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Platform Base Currency</label>
                            <select id="currency" name="currency" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                                <?php foreach ($currencies as $iso => $title): ?>
                                    <option value="<?php echo $iso; ?>" <?php echo (($settings['currency'] ?? 'USD') === $iso) ? 'selected' : ''; ?>><?php echo $title; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="space-y-1">
                            <label for="min_withdrawal_amount" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Seller Minimum Payout Target</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-slate-500 font-mono text-sm font-semibold">
                                    <?php echo htmlspecialchars(currency_symbol($settings['currency'] ?? 'USD'), ENT_QUOTES, 'UTF-8'); ?>
                                </span>
                                <input type="number" step="0.01" min="0" id="min_withdrawal_amount" name="min_withdrawal_amount" value="<?php echo htmlspecialchars($settings['min_withdrawal_amount'] ?? '0.00', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl pl-14 pr-4 py-3 text-sm text-white font-mono focus:outline-none transition-all" placeholder="0.00">
                            </div>
                        </div>

                        <div class="space-y-1">
                            <label for="commission_type" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Author Split Strategy</label>
                            <select id="commission_type" name="commission_type" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
                                <option value="percentage" <?php echo (($settings['commission_type'] ?? 'percentage') === 'percentage') ? 'selected' : ''; ?>>Percentage Fee (%)</option>
                                <option value="fixed" <?php echo (($settings['commission_type'] ?? 'fixed') === 'fixed') ? 'selected' : ''; ?>>Fixed Fee Per Conversion</option>
                            </select>
                        </div>

	                        <div class="space-y-1">
	                            <label for="commission_rate" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Platform Cut Yield Rate</label>
	                            <input type="number" step="0.01" id="commission_rate" name="commission_rate" value="<?php echo htmlspecialchars($settings['commission_rate'] ?? '0.00', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
	                        </div>

	                        <div class="space-y-1 md:col-span-2">
	                            <label for="transaction_fee_rate" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Customer Transaction Fee (%)</label>
	                            <input type="number" step="0.01" min="0" id="transaction_fee_rate" name="transaction_fee_rate" value="<?php echo htmlspecialchars($settings['transaction_fee_rate'] ?? '0.00', ENT_QUOTES, 'UTF-8'); ?>" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all">
	                            <p class="text-[11px] text-slate-500">This percentage is added on top of the item price for customers. Seller commission still uses the original item price.</p>
	                        </div>
	                    </div>
                </div>

                <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4">
                    <h2 class="text-base font-bold text-nftAccentPurple flex items-center space-x-2">
                        <i class="fa-solid fa-clock text-sm"></i>
                        <span>Cron Clock System Sync</span>
                    </h2>
                    
                    <div class="space-y-1">
                        <label for="timezone" class="text-xs font-bold uppercase tracking-wider text-nftTextGray">Database Target System Timezone</label>
                        <select id="timezone" name="timezone" class="w-full bg-slate-950 border border-slate-800 focus:border-nftAccentCyan rounded-xl px-4 py-3 text-sm text-white focus:outline-none transition-all custom-scrollbar">
                            <?php foreach ($timezones as $tz_ident): ?>
                                <option value="<?php echo $tz_ident; ?>" <?php echo (($settings['timezone'] ?? 'UTC') === $tz_ident) ? 'selected' : ''; ?>><?php echo $tz_ident; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="flex items-center justify-end space-x-4 pt-4 border-t border-slate-900">
                    <a href="settings.php" class="px-6 py-3 rounded-xl border border-slate-800 text-xs font-bold tracking-widest text-nftTextGray uppercase hover:bg-slate-900 hover:text-white transition-colors">Cancel Modifications</a>
                    <button type="submit" class="px-6 py-3 rounded-xl bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple font-bold text-xs tracking-widest text-white uppercase shadow-lg shadow-cyan-500/10 hover:shadow-cyan-500/20 transition-all">Save Config Matrix</button>
                </div>

            </form>

        </div>
    </main>

</div>

</body>
</html>
