<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: admin_login.php");
    exit();
}
require_once 'db.php';

// Handle profit actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action == 'delete') {
        $profit_id = intval($_POST['profit_id']);
        
        $delete_query = "DELETE FROM profits WHERE id = ?";
        $stmt = mysqli_prepare($conn, $delete_query);
        mysqli_stmt_bind_param($stmt, "i", $profit_id);
        
        if (mysqli_stmt_execute($stmt)) {
            $success = "Profit entry deleted successfully!";
        } else {
            $error = "Failed to delete profit entry!";
        }
        mysqli_stmt_close($stmt);
        
    } elseif ($action == 'add_profit') {
        $user_id = intval($_POST['user_id']);
        $amount = floatval($_POST['amount']);
        $source = mysqli_real_escape_string($conn, $_POST['source']);
        
        if (empty($source)) {
            $source = "Admin Added";
        }
        
        $sql = "INSERT INTO profits (user_id, amount, source, created_at) VALUES (?, ?, ?, NOW())";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "ids", $user_id, $amount, $source);
        
        if (mysqli_stmt_execute($stmt)) {
            $success = "Profit of $" . number_format($amount, 2) . " added successfully!";
        } else {
            $error = "Failed to add profit!";
        }
        mysqli_stmt_close($stmt);
        
    } elseif ($action == 'edit_profit') {
        $profit_id = intval($_POST['profit_id']);
        $amount = floatval($_POST['amount']);
        $source = mysqli_real_escape_string($conn, $_POST['source']);
        
        $sql = "UPDATE profits SET amount = ?, source = ? WHERE id = ?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "dsi", $amount, $source, $profit_id);
        
        if (mysqli_stmt_execute($stmt)) {
            $success = "Profit updated successfully!";
        } else {
            $error = "Failed to update profit!";
        }
        mysqli_stmt_close($stmt);
    }
}

// Get filter
$filter_user = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Build query
$where_clause = "WHERE 1=1";
if ($filter_user > 0) {
    $where_clause .= " AND p.user_id = $filter_user";
}
if (!empty($search)) {
    $where_clause .= " AND (u.phone_number LIKE '%$search%' OR u.email LIKE '%$search%' OR p.source LIKE '%$search%')";
}

// Get all profits with user information
$query = "SELECT p.*, u.phone_number, u.email 
          FROM profits p 
          JOIN users u ON p.user_id = u.id 
          $where_clause
          ORDER BY p.created_at DESC
          LIMIT 100";
$profits_result = mysqli_query($conn, $query);

// Get statistics
$stats_query = "SELECT 
                COUNT(*) as total_entries,
                SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as total_profits,
                SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END) as total_deductions,
                SUM(amount) as net_profit
                FROM profits";
$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);

// Get all users for dropdown
$users_query = "SELECT id, phone_number, email FROM users ORDER BY phone_number ASC";
$users_result = mysqli_query($conn, $users_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Profits - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            background-color: #000;
            color: #fff;
            font-family: Arial, sans-serif;
            font-size: 13px;
        }
        .header {
            background: #111;
            padding: 12px 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .header h1 {
            color: #fff;
            font-size: 18px;
        }
        .back-btn {
            color: #FFD700;
            text-decoration: none;
            font-size: 20px;
        }
        .logout-btn {
            background: #f87171;
            color: #fff;
            padding: 8px 15px;
            border-radius: 5px;
            text-decoration: none;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .container {
            padding: 12px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .alert {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .alert-success {
            background: #1a4d1a;
            border: 1px solid #2d7a2d;
            color: #4ade80;
        }
        .alert-error {
            background: #4d1a1a;
            border: 1px solid #7a2d2d;
            color: #f87171;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .stat-card {
            background: #111;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        .stat-number {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stat-label {
            color: #888;
            font-size: 10px;
        }
        .stat-card:nth-child(1) .stat-number { color: #FFD700; }
        .stat-card:nth-child(2) .stat-number { color: #4ade80; }
        .stat-card:nth-child(3) .stat-number { color: #f87171; }
        .stat-card:nth-child(4) .stat-number { color: #3b82f6; }
        
        .controls {
            background: #111;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: grid;
            gap: 10px;
        }
        .controls-row {
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 10px;
        }
        .search-box {
            display: flex;
            gap: 10px;
        }
        .search-box input,
        .search-box select {
            flex: 1;
            padding: 10px;
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            color: #fff;
            font-size: 12px;
        }
        .search-box input:focus,
        .search-box select:focus {
            outline: none;
            border-color: #FFD700;
        }
        .btn-add {
            background: #4ade80;
            color: #000;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            font-size: 12px;
            white-space: nowrap;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .btn-add:hover {
            background: #22c55e;
        }
        .btn-search {
            background: #FFD700;
            color: #000;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            font-size: 12px;
        }
        .btn-search:hover {
            background: #FFA500;
        }
        .btn-clear {
            background: #666;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            font-size: 12px;
            text-decoration: none;
            display: inline-block;
        }
        .btn-clear:hover {
            background: #888;
        }
        
        .profits-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .profit-card {
            background: #111;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            border-left: 4px solid #333;
        }
        .profit-card.positive {
            border-left-color: #4ade80;
        }
        .profit-card.negative {
            border-left-color: #f87171;
        }
        .profit-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }
        .profit-amount {
            font-size: 20px;
            font-weight: bold;
        }
        .profit-amount.positive {
            color: #4ade80;
        }
        .profit-amount.negative {
            color: #f87171;
        }
        .profit-source {
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 10px;
            font-weight: bold;
            background: #333;
            color: #fff;
        }
        .profit-info {
            display: grid;
            gap: 8px;
            margin-bottom: 12px;
        }
        .info-row {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 12px;
        }
        .info-label {
            color: #888;
            min-width: 80px;
        }
        .info-value {
            color: #fff;
        }
        .action-buttons {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }
        .btn {
            flex: 1;
            padding: 8px;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            font-size: 11px;
            transition: all 0.3s;
        }
        .btn-edit {
            background: #3b82f6;
            color: #fff;
        }
        .btn-edit:hover {
            background: #2563eb;
        }
        .btn-delete {
            background: #f87171;
            color: #fff;
        }
        .btn-delete:hover {
            background: #ef4444;
        }
        .no-profits {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .no-profits i {
            font-size: 50px;
            margin-bottom: 15px;
            opacity: 0.3;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            overflow-y: auto;
        }
        .modal-content {
            background-color: #111;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #333;
            width: 90%;
            max-width: 500px;
            border-radius: 10px;
            position: relative;
        }
        .close {
            color: #888;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 20px;
        }
        .close:hover {
            color: #fff;
        }
        .modal h2 {
            color: #FFD700;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #fff;
            font-size: 12px;
        }
        .form-group select,
        .form-group input {
            width: 100%;
            padding: 10px;
            background: #000;
            border: 1px solid #333;
            border-radius: 5px;
            color: #fff;
            font-size: 14px;
        }
        .form-group select:focus,
        .form-group input:focus {
            outline: none;
            border-color: #FFD700;
        }
        .btn-submit {
            width: 100%;
            padding: 12px;
            background: #FFD700;
            color: #000;
            border: none;
            border-radius: 5px;
            font-weight: bold;
            cursor: pointer;
            font-size: 14px;
            margin-top: 10px;
        }
        .btn-submit:hover {
            background: #FFA500;
        }

        @media (max-width: 768px) {
            .controls-row {
                grid-template-columns: 1fr;
            }
            .search-box {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <a href="admin_dashboard.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
            <h1><i class="fas fa-coins"></i> Manage Profits</h1>
        </div>
        <a href="admin_logout.php" class="logout-btn">
            <i class="fas fa-sign-out-alt"></i> Logout
        </a>
    </div>

    <div class="container">
        <?php if (isset($success)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <span><?php echo $success; ?></span>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error)): ?>
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span><?php echo $error; ?></span>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $stats['total_entries']; ?></div>
                <div class="stat-label">Total Entries</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['total_profits'], 2); ?></div>
                <div class="stat-label">Total Profits</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format(abs($stats['total_deductions']), 2); ?></div>
                <div class="stat-label">Total Deductions</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">$<?php echo number_format($stats['net_profit'], 2); ?></div>
                <div class="stat-label">Net Profit</div>
            </div>
        </div>

        <!-- Controls -->
        <div class="controls">
            <div class="controls-row">
                <form method="GET" class="search-box">
                    <input type="text" name="search" placeholder="Search by phone, email, or source..." value="<?php echo htmlspecialchars($search); ?>">
                    <select name="user_id">
                        <option value="0">All Users</option>
                        <?php 
                        mysqli_data_seek($users_result, 0);
                        while ($user = mysqli_fetch_assoc($users_result)): 
                        ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $filter_user == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['phone_number']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                    <button type="submit" class="btn-search"><i class="fas fa-search"></i> Search</button>
                    <?php if (!empty($search) || $filter_user > 0): ?>
                    <a href="admin_profits.php" class="btn-clear"><i class="fas fa-times"></i> Clear</a>
                    <?php endif; ?>
                </form>
                <button type="button" class="btn-add" onclick="openAddModal()">
                    <i class="fas fa-plus"></i> Add Profit
                </button>
            </div>
        </div>

        <!-- Profits List -->
        <div class="profits-list">
            <?php if ($profits_result && mysqli_num_rows($profits_result) > 0): ?>
                <?php while ($profit = mysqli_fetch_assoc($profits_result)): 
                    $is_positive = $profit['amount'] >= 0;
                    $card_class = $is_positive ? 'positive' : 'negative';
                ?>
                <div class="profit-card <?php echo $card_class; ?>">
                    <div class="profit-header">
                        <div class="profit-amount <?php echo $card_class; ?>">
                            <i class="fas fa-<?php echo $is_positive ? 'arrow-up' : 'arrow-down'; ?>"></i>
                            <?php echo $is_positive ? '+' : ''; ?>$<?php echo number_format($profit['amount'], 2); ?>
                        </div>
                        <span class="profit-source">
                            <?php echo htmlspecialchars($profit['source'] ?? 'N/A'); ?>
                        </span>
                    </div>
                    
                    <div class="profit-info">
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-user"></i> User:</span>
                            <span class="info-value"><?php echo htmlspecialchars($profit['phone_number']); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-envelope"></i> Email:</span>
                            <span class="info-value"><?php echo htmlspecialchars($profit['email']); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-clock"></i> Date:</span>
                            <span class="info-value"><?php echo date('M d, Y - h:i A', strtotime($profit['created_at'])); ?></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label"><i class="fas fa-hashtag"></i> ID:</span>
                            <span class="info-value">#<?php echo $profit['id']; ?></span>
                        </div>
                    </div>

                    <div class="action-buttons">
                        <button type="button" class="btn btn-edit" onclick="openEditModal(<?php echo $profit['id']; ?>, <?php echo $profit['amount']; ?>, '<?php echo htmlspecialchars($profit['source'] ?? '', ENT_QUOTES); ?>', '<?php echo htmlspecialchars($profit['phone_number']); ?>')">
                            <i class="fas fa-edit"></i> Edit
                        </button>
                        <form method="POST" style="flex: 1; margin: 0;" onsubmit="return confirm('Are you sure you want to DELETE this profit entry?');">
                            <input type="hidden" name="profit_id" value="<?php echo $profit['id']; ?>">
                            <input type="hidden" name="action" value="delete">
                            <button type="submit" class="btn btn-delete">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </form>
                    </div>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="no-profits">
                    <i class="fas fa-coins"></i>
                    <p>No profit entries found</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add Profit Modal -->
    <div id="addModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeAddModal()">&times;</span>
            <h2><i class="fas fa-plus"></i> Add Profit Entry</h2>
            
            <form method="POST">
                <input type="hidden" name="action" value="add_profit">
                
                <div class="form-group">
                    <label>Select User</label>
                    <select name="user_id" required>
                        <option value="">-- Select User --</option>
                        <?php 
                        mysqli_data_seek($users_result, 0);
                        while ($user = mysqli_fetch_assoc($users_result)): 
                        ?>
                        <option value="<?php echo $user['id']; ?>">
                            <?php echo htmlspecialchars($user['phone_number']); ?> - <?php echo htmlspecialchars($user['email']); ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Amount ($)</label>
                    <input type="number" name="amount" step="0.01" placeholder="Enter amount (use negative for deduction)" required>
                    <small style="color: #888; font-size: 11px;">Enter negative amount to deduct profit</small>
                </div>
                
                <div class="form-group">
                    <label>Source/Reason</label>
                    <input type="text" name="source" placeholder="E.g., Investment Matured, Bonus, Admin Adjustment" required>
                </div>
                
                <button type="submit" class="btn-submit">
                    <i class="fas fa-check"></i> Add Profit
                </button>
            </form>
        </div>
    </div>

    <!-- Edit Profit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeEditModal()">&times;</span>
            <h2><i class="fas fa-edit"></i> Edit Profit Entry</h2>
            <p style="color: #888; margin-bottom: 20px; font-size: 12px;">User: <span id="editModalUserPhone"></span></p>
            
            <form method="POST">
                <input type="hidden" name="profit_id" id="editModalProfitId">
                <input type="hidden" name="action" value="edit_profit">
                
                <div class="form-group">
                    <label>Amount ($)</label>
                    <input type="number" name="amount" id="editModalAmount" step="0.01" placeholder="Enter amount" required>
                </div>
                
                <div class="form-group">
                    <label>Source/Reason</label>
                    <input type="text" name="source" id="editModalSource" placeholder="E.g., Investment Matured, Bonus" required>
                </div>
                
                <button type="submit" class="btn-submit">
                    <i class="fas fa-check"></i> Update Profit
                </button>
            </form>
        </div>
    </div>

    <script>
        // Auto-hide alerts
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                alert.style.transition = 'opacity 0.5s';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            });
        }, 5000);

        // Add Modal functions
        function openAddModal() {
            document.getElementById('addModal').style.display = 'block';
        }

        function closeAddModal() {
            document.getElementById('addModal').style.display = 'none';
        }

        // Edit Modal functions
        function openEditModal(profitId, amount, source, userPhone) {
            document.getElementById('editModalProfitId').value = profitId;
            document.getElementById('editModalAmount').value = amount;
            document.getElementById('editModalSource').value = source;
            document.getElementById('editModalUserPhone').textContent = userPhone;
            document.getElementById('editModal').style.display = 'block';
        }

        function closeEditModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const addModal = document.getElementById('addModal');
            const editModal = document.getElementById('editModal');
            if (event.target == addModal) {
                closeAddModal();
            }
            if (event.target == editModal) {
                closeEditModal();
            }
        }
    </script>
</body>
</html>
<?php
mysqli_close($conn);
?>