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

$commission_id = isset($_POST['commission_id']) ? intval($_POST['commission_id']) : 0;
$admin_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
$correct_pin = "1234";

if ($admin_pin !== $correct_pin) {
    echo json_encode(array('success' => false, 'message' => 'Invalid PIN'));
    exit();
}

// Get admin details for notification
$admin_id = $_SESSION['user_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'] ?? 'System Administrator';
$admin_email = $adminData['email'] ?? 'admin@system.com';

if ($commission_id > 0) {
    // Get commission details before deletion
    $sql = "SELECT rt.*, 
                   u1.first_name as referrer_first, u1.last_name as referrer_last, u1.email as referrer_email,
                   u2.first_name as referred_first, u2.last_name as referred_last, u2.email as referred_email
            FROM referral_transactions rt
            LEFT JOIN users u1 ON rt.referrer_id = u1.id
            LEFT JOIN users u2 ON rt.referred_id = u2.id
            WHERE rt.id = $commission_id";
    $result = mysqli_query($conn, $sql);
    $commission = mysqli_fetch_assoc($result);
    
    if ($commission) {
        // Get user's current referral balance before deletion
        $referrer_id = $commission['referrer_id'];
        $balance_sql = "SELECT referral_balance FROM users WHERE id = '$referrer_id'";
        $balance_result = mysqli_query($conn, $balance_sql);
        $balance_data = mysqli_fetch_assoc($balance_result);
        $old_referral_balance = $balance_data['referral_balance'] ?? 0;
        
        // Calculate new balance after deletion
        $commission_amount = floatval($commission['amount']);
        $new_referral_balance = $old_referral_balance - $commission_amount;
        
        // Delete the commission record
        $delete_sql = "DELETE FROM referral_transactions WHERE id = $commission_id";
        
        if (mysqli_query($conn, $delete_sql)) {
            // Update user's referral balance
            $update_balance_sql = "UPDATE users SET referral_balance = '$new_referral_balance' WHERE id = '$referrer_id'";
            mysqli_query($conn, $update_balance_sql);
            
            // Log activity
            logAdminActivity(
                'Commission Record Deleted',
                "Deleted commission record ID $commission_id (Amount: $" . $commission['amount'] . ", Type: " . $commission['transaction_type'] . ")",
                'Commission',
                $commission_id,
                'referral_transactions'
            );
            
            // NOTIFICATION: Commission Deleted (ADMIN)
            $mail_subject = "Commission Record Deleted";
            $mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Commission Record Deleted</h2>
                                
                                <p class='message'>
                                    A referral commission record has been deleted from the system by an administrator.
                                </p>

                                <!-- Deletion Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Commission ID:</strong> COMM-" . $commission_id . "<br>
                                        <strong>Amount:</strong> <span style='color: #dc3545;'>-$" . number_format($commission_amount, 2) . "</span><br>
                                        <strong>Type:</strong> " . $commission['transaction_type'] . "<br>
                                        <strong>Description:</strong> " . $commission['description'] . "<br>
                                        <strong>Original Date:</strong> " . date('F j, Y g:i A', strtotime($commission['created_at'])) . "<br>
                                        <strong>Deleted By:</strong> " . $admin_name . " (Admin ID: " . $admin_id . ")<br>
                                        <strong>Deletion Time:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                        <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>PERMANENTLY DELETED</span>
                                    </div>
                                </div>

                                <!-- User Information -->
                                <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #495057;'>👤 Affected Users</h4>
                                    <p style='color: #495057;'>
                                        <strong>Referrer (Received Commission):</strong><br>
                                        • Name: " . $commission['referrer_first'] . " " . $commission['referrer_last'] . "<br>
                                        • Email: " . $commission['referrer_email'] . "<br>
                                        • User ID: " . $commission['referrer_id'] . "<br>
                                        • Old Referral Balance: $" . number_format($old_referral_balance, 2) . "<br>
                                        • New Referral Balance: $" . number_format($new_referral_balance, 2) . "<br><br>
                                        
                                        <strong>Referred User (Triggered Commission):</strong><br>
                                        • Name: " . $commission['referred_first'] . " " . $commission['referred_last'] . "<br>
                                        • Email: " . $commission['referred_email'] . "<br>
                                        • User ID: " . $commission['referred_id'] . "
                                    </p>
                                </div>

                                <!-- Financial Impact -->
                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #721c24;'>💰 Financial Impact</h4>
                                    <p style='color: #721c24;'>
                                        <strong>Direct Impact:</strong><br>
                                        • $" . number_format($commission_amount, 2) . " removed from referral balance<br>
                                        • Balance adjustment: $" . number_format($old_referral_balance, 2) . " → $" . number_format($new_referral_balance, 2) . "<br>
                                        • Commission removed from user's earnings history<br>
                                        • This action affects user's total referral earnings
                                    </p>
                                </div>

                                <!-- Reason for Deletion -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>🗑️ Possible Reasons for Deletion</h3>
                                    <p style='color: #6c757d;'>Common administrative reasons:</p>
                                    <ul style='color: #6c757d;'>
                                        <li>Duplicate commission entry</li>
                                        <li>Fraudulent or invalid referral</li>
                                        <li>Commission calculation error</li>
                                        <li>User account closure or refund</li>
                                        <li>Compliance or audit requirements</li>
                                        <li>System cleanup of test data</li>
                                    </ul>
                                </div>

                                <!-- User Notification Consideration -->
                                <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #856404;'>📢 User Notification Consideration</h4>
                                    <p style='color: #856404;'>
                                        <strong>Important:</strong> The user whose balance was adjusted has NOT been automatically notified.<br>
                                        <strong>Recommended Action:</strong> Consider notifying the affected user about this adjustment if it was due to an error or policy change.
                                    </p>
                                </div>

                                <!-- Admin Actions -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/admin/referrals.php?user_id=" . $commission['referrer_id'] . "' 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 User Referrals
                                    </a>
                                    <a href='" . $myUrl . "/admin/users.php?id=" . $commission['referrer_id'] . "' 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;'>
                                        View User Profile
                                    </a>
                                </div>

                                <!-- System Information -->
                                <div class='support-section'>
                                    <p class='support-text'>System Information:</p>
                                    <p style='color: #6c757d; font-size: 12px;'>
                                        <strong>Table Affected:</strong> referral_transactions<br>
                                        <strong>Record ID:</strong> " . $commission_id . "<br>
                                        <strong>Action Type:</strong> Manual Deletion<br>
                                        <strong>Audit Trail:</strong> Logged in admin_activities
                                    </p>
                                </div>
                            </div>";

            // Send admin notification
            require_once("../proccess/admin_mailer.php");
            
            echo json_encode(array('success' => true, 'message' => 'Commission record deleted successfully'));
        } else {
            echo json_encode(array('success' => false, 'message' => 'Failed to delete commission record'));
        }
    } else {
        echo json_encode(array('success' => false, 'message' => 'Commission record not found'));
    }
} else {
    echo json_encode(array('success' => false, 'message' => 'Invalid commission ID'));
}
?>