<?php
session_start();
include('includes/head.php');

// Check PIN
$admin_pin = "1234";
$submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';

if ($submitted_pin !== $admin_pin) {
    header('Location: commission_report.php?error=Invalid PIN. Settings not updated.');
    exit();
}

// Get admin details for notification
$admin_id = $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? 1;
$adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_name = $adminData['first_name'] ?? 'Administrator';
$admin_email = $adminData['email'] ?? 'admin@system.com';

// Get current settings before update for comparison
$old_settings_sql = "SELECT * FROM referral_settings LIMIT 1";
$old_result = mysqli_query($conn, $old_settings_sql);
$old_settings = mysqli_fetch_assoc($old_result);

// Get form data
$signup_bonus_referrer = floatval($_POST['signup_bonus_referrer']);
$signup_bonus_referred = floatval($_POST['signup_bonus_referred']);
$bot_bonus = floatval($_POST['bot_bonus']);
$discount_per_referral = floatval($_POST['discount_per_referral']);
$max_referral_discount = floatval($_POST['max_referral_discount']);
$is_active = isset($_POST['is_active']) ? 1 : 0;

// Update settings
$sql = "UPDATE referral_settings SET 
        signup_bonus_referrer = '$signup_bonus_referrer',
        signup_bonus_referred = '$signup_bonus_referred',
        bot_bonus = '$bot_bonus',
        discount_per_referral = '$discount_per_referral',
        max_referral_discount = '$max_referral_discount',
        is_active = '$is_active',
        updated_at = NOW()";

if (mysqli_query($conn, $sql)) {
    // Log activity
    logAdminActivity(
        'Commission Settings Updated',
        "Updated commission settings: Referrer Bonus: $$signup_bonus_referrer, Referred Bonus: $$signup_bonus_referred, Bot Bonus: $$bot_bonus",
        'Commission',
        0,
        'referral_settings'
    );
    
    // NOTIFICATION: Commission Settings Updated (ADMIN)
    $mail_subject = "Commission Settings Updated";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Commission Settings Updated</h2>
                        
                        <p class='message'>
                            The referral and commission settings have been updated successfully by an administrator.
                        </p>

                        <!-- Settings Comparison Table -->
                        <div class='details-section'>
                            <h3 style='color: #2c3e50; margin-bottom: 15px;'>📋 Settings Changes</h3>
                            <table style='width: 100%; border-collapse: collapse; margin: 15px 0; background: white;'>
                                <thead>
                                    <tr style='background: #f8f9fa; border-bottom: 2px solid #dee2e6;'>
                                        <th style='padding: 12px; text-align: left; border: 1px solid #dee2e6;'>Setting</th>
                                        <th style='padding: 12px; text-align: left; border: 1px solid #dee2e6;'>Previous Value</th>
                                        <th style='padding: 12px; text-align: left; border: 1px solid #dee2e6;'>New Value</th>
                                        <th style='padding: 12px; text-align: left; border: 1px solid #dee2e6;'>Change</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Signup Bonus (Referrer)</strong></td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($old_settings['signup_bonus_referrer'], 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($signup_bonus_referrer, 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . 
                                            ($signup_bonus_referrer > $old_settings['signup_bonus_referrer'] ? '<span style="color: #28a745;">▲ +$' . number_format($signup_bonus_referrer - $old_settings['signup_bonus_referrer'], 2) . '</span>' : 
                                             ($signup_bonus_referrer < $old_settings['signup_bonus_referrer'] ? '<span style="color: #dc3545;">▼ -$' . number_format($old_settings['signup_bonus_referrer'] - $signup_bonus_referrer, 2) . '</span>' : 
                                             '<span style="color: #6c757d;">No change</span>')) . "
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Signup Bonus (Referred)</strong></td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($old_settings['signup_bonus_referred'], 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($signup_bonus_referred, 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . 
                                            ($signup_bonus_referred > $old_settings['signup_bonus_referred'] ? '<span style="color: #28a745;">▲ +$' . number_format($signup_bonus_referred - $old_settings['signup_bonus_referred'], 2) . '</span>' : 
                                             ($signup_bonus_referred < $old_settings['signup_bonus_referred'] ? '<span style="color: #dc3545;">▼ -$' . number_format($old_settings['signup_bonus_referred'] - $signup_bonus_referred, 2) . '</span>' : 
                                             '<span style="color: #6c757d;">No change</span>')) . "
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Bot Subscription Bonus</strong></td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($old_settings['bot_bonus'], 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($bot_bonus, 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . 
                                            ($bot_bonus > $old_settings['bot_bonus'] ? '<span style="color: #28a745;">▲ +$' . number_format($bot_bonus - $old_settings['bot_bonus'], 2) . '</span>' : 
                                             ($bot_bonus < $old_settings['bot_bonus'] ? '<span style="color: #dc3545;">▼ -$' . number_format($old_settings['bot_bonus'] - $bot_bonus, 2) . '</span>' : 
                                             '<span style="color: #6c757d;">No change</span>')) . "
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Discount Per Referral</strong></td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($old_settings['discount_per_referral'], 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($discount_per_referral, 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . 
                                            ($discount_per_referral > $old_settings['discount_per_referral'] ? '<span style="color: #28a745;">▲ +$' . number_format($discount_per_referral - $old_settings['discount_per_referral'], 2) . '</span>' : 
                                             ($discount_per_referral < $old_settings['discount_per_referral'] ? '<span style="color: #dc3545;">▼ -$' . number_format($old_settings['discount_per_referral'] - $discount_per_referral, 2) . '</span>' : 
                                             '<span style="color: #6c757d;">No change</span>')) . "
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Max Referral Discount</strong></td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($old_settings['max_referral_discount'], 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>$" . number_format($max_referral_discount, 2) . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . 
                                            ($max_referral_discount > $old_settings['max_referral_discount'] ? '<span style="color: #28a745;">▲ +$' . number_format($max_referral_discount - $old_settings['max_referral_discount'], 2) . '</span>' : 
                                             ($max_referral_discount < $old_settings['max_referral_discount'] ? '<span style="color: #dc3545;">▼ -$' . number_format($old_settings['max_referral_discount'] - $max_referral_discount, 2) . '</span>' : 
                                             '<span style="color: #6c757d;">No change</span>')) . "
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'><strong>Commission Program Status</strong></td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . ($old_settings['is_active'] ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . ($is_active ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "</td>
                                        <td style='padding: 12px; border: 1px solid #dee2e6;'>" . 
                                            ($is_active != $old_settings['is_active'] ? '<span style="color: #ffc107;">⚡ Status Changed</span>' : 
                                             '<span style="color: #6c757d;">No change</span>') . "
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <!-- Update Information -->
                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #495057;'>⚙️ Update Information</h4>
                            <p style='color: #495057;'>
                                <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                <strong>Update Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                <strong>Action:</strong> Commission Settings Modified
                            </p>
                        </div>

                        <!-- Financial Impact Analysis -->
                        <div style='background: " . ($is_active ? '#d4edda' : '#f8d7da') . "; border: 1px solid " . ($is_active ? '#c3e6cb' : '#f5c6cb') . "; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: " . ($is_active ? '#155724' : '#721c24') . ";'>💰 Financial Impact Analysis</h4>
                            <p style='color: " . ($is_active ? '#155724' : '#721c24') . ";'>
                                <strong>Program Status:</strong> " . ($is_active ? 'ACTIVE - Commissions are being paid' : 'INACTIVE - No commissions are being paid') . "<br>
                                <strong>Referrer Bonus:</strong> $" . number_format($signup_bonus_referrer, 2) . " per new referred user<br>
                                <strong>Referred Bonus:</strong> $" . number_format($signup_bonus_referred, 2) . " for signing up<br>
                                <strong>Bot Bonus:</strong> $" . number_format($bot_bonus, 2) . " per bot subscription<br>
                                <strong>Discount Structure:</strong> $" . number_format($discount_per_referral, 2) . " per referral up to $" . number_format($max_referral_discount, 2) . "
                            </p>
                        </div>

                        <!-- System-Wide Effects -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📊 System-Wide Effects</h3>
                            <p style='color: #6c757d;'>
                                These changes will affect:<br>
                                • All new user registrations from now onward<br>
                                • All future bot subscription commissions<br>
                                • Referral discount calculations for existing referrers<br>
                                • Overall platform commission expenses<br><br>
                                <strong>Previous settings saved in system logs.</strong>
                            </p>
                        </div>

                        <!-- Admin Actions -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/admin/commission_report.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                View Commission Report
                            </a>
                            <a href='" . $myUrl . "/admin/referral_settings.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Edit Settings Again
                            </a>
                        </div>

                        <!-- Audit Information -->
                        <div class='support-section'>
                            <p class='support-text'>Audit Trail Information:</p>
                            <p style='color: #6c757d; font-size: 12px;'>
                                <strong>Setting ID:</strong> referral_settings (System Configuration)<br>
                                <strong>Update Method:</strong> Manual via Admin Panel<br>
                                <strong>Admin ID:</strong> " . $admin_id . "<br>
                                <strong>Change Logged:</strong> Yes (admin_activities table)<br>
                                <strong>Timestamp:</strong> " . date('Y-m-d H:i:s') . "
                            </p>
                        </div>
                    </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    header('Location: commission_report.php?success=Commission settings updated successfully!');
} else {
    header('Location: commission_report.php?error=Failed to update commission settings.');
}
exit();
?>