<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

require_once "../account/include/db.php";

// --- ACTION LOGIC (Add / Edit / Delete) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // 1. DELETE ACTION
    if ($action === 'delete' && isset($_POST['plan_id'])) {
        $plan_id = (int)$_POST['plan_id'];
        $del_q = "DELETE FROM `investments` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $plan_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Investment plan deleted successfully.";
                $_SESSION['swal_title'] = "Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. ADD ACTION
    elseif ($action === 'add') {
        $u_id     = (int)$_POST['user_id'];
        $p_name   = mysqli_real_escape_string($conn, $_POST['plan_name']);
        $amt      = (float)$_POST['amount'];
        $d_return = (float)$_POST['daily_return'];
        $dur      = (int)$_POST['duration'];
        $stat     = mysqli_real_escape_string($conn, $_POST['status']);
        $end_date = date('Y-m-d H:i:s', strtotime("+$dur days"));

        $add_q = "INSERT INTO `investments` (`user_id`, `plan_name`, `amount`, `daily_return`, `duration`, `status`, `end_at`) 
                  VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        if ($stmt = mysqli_prepare($conn, $add_q)) {
            mysqli_stmt_bind_param($stmt, "isddiss", $u_id, $p_name, $amt, $d_return, $dur, $stat, $end_date);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "New investment added for User ID #$u_id";
                $_SESSION['swal_title'] = "Success";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. EDIT ACTION
    elseif ($action === 'edit' && isset($_POST['plan_id'])) {
        $plan_id  = (int)$_POST['plan_id'];
        $p_name   = mysqli_real_escape_string($conn, $_POST['plan_name']);
        $amt      = (float)$_POST['amount'];
        $d_return = (float)$_POST['daily_return'];
        $dur      = (int)$_POST['duration'];
        $stat     = mysqli_real_escape_string($conn, $_POST['status']);

        $upd_q = "UPDATE `investments` SET `plan_name` = ?, `amount` = ?, `daily_return` = ?, `duration` = ?, `status` = ? WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "sddisi", $p_name, $amt, $d_return, $dur, $stat, $plan_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Investment details updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: manage_plans.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION & DATA FETCH ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `investments`");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

$query = "SELECT i.*, u.full_name, u.username 
          FROM `investments` i 
          JOIN `users` u ON i.user_id = u.id 
          ORDER BY i.created_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Premiumtrustglobal Admin</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">Active Investments</h1>
        </div>
        <button onclick="addPlanModal()" class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2.5 rounded-lg text-sm font-bold shadow-lg shadow-blue-900/20 transition-all flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
            Add New Investment
        </button>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[900px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4 font-medium">User / Plan</th>
                        <th class="p-4 font-medium">Principal</th>
                        <th class="p-4 font-medium">Daily ROI</th>
                        <th class="p-4 font-medium">Duration</th>
                        <th class="p-4 font-medium">Status</th>
                        <th class="p-4 font-medium text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4">
                                <div class="font-bold text-slate-100"><?php echo htmlspecialchars($row['plan_name'] ?? 'N/A'); ?></div>
                                <div class="text-[11px] text-slate-500">For: <?php echo htmlspecialchars($row['full_name'] ?? ''); ?> (@<?php echo htmlspecialchars($row['username'] ?? ''); ?>)</div>
                            </td>
                            <td class="p-4">
                                <span class="text-emerald-400 font-mono font-bold">$<?php echo number_format($row['amount'], 2); ?></span>
                            </td>
                            <td class="p-4 text-blue-400 font-mono font-semibold">
                                $<?php echo number_format($row['daily_return'], 2); ?>/day
                            </td>
                            <td class="p-4 text-xs">
                                <div class="text-slate-300"><?php echo $row['duration']; ?> Days</div>
                                <div class="text-[10px] text-slate-500 italic">Ends: <?php echo date('M d, Y', strtotime($row['end_at'])); ?></div>
                            </td>
                            <td class="p-4">
                                <?php if($row['status'] === 'active'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Running</span>
                                <?php elseif($row['status'] === 'completed'): ?>
                                    <span class="status-pill bg-blue-500/10 text-blue-500 border border-blue-500/20">Finished</span>
                                <?php else: ?>
                                    <span class="status-pill bg-red-500/10 text-red-500 border border-red-500/20"><?php echo htmlspecialchars($row['status']); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3">
                                    <button onclick="editPlanModal(<?php echo htmlspecialchars(json_encode($row)); ?>)" class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Edit</button>
                                    <form method="POST" class="inline" onsubmit="return confirm('Delete this investment record?');">
                                        <input type="hidden" name="plan_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="6" class="p-12 text-center text-slate-500 italic">No active investment plans found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500 font-medium">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
function addPlanModal() {
    Swal.fire({
        title: 'Add User Investment',
        background: '#0f172a',
        color: '#f1f5f9',
        html: `
            <form id="addPlanForm" method="POST" class="text-left">
                <input type="hidden" name="action" value="add">
                <div class="grid grid-cols-1 gap-4 mt-4">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">User ID</label>
                        <input type="number" name="user_id" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Plan Name</label>
                        <input type="text" name="plan_name" placeholder="e.g. Diamond Plan" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Amount ($)</label>
                            <input type="number" step="0.01" name="amount" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        </div>
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Daily ROI ($)</label>
                            <input type="number" step="0.01" name="daily_return" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Duration (Days)</label>
                            <input type="number" name="duration" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        </div>
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Initial Status</label>
                            <select name="status" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                                <option value="active">Active</option>
                                <option value="pending">Pending</option>
                            </select>
                        </div>
                    </div>
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Create Investment',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('addPlanForm').submit(); }
    });
}

function editPlanModal(data) {
    Swal.fire({
        title: 'Edit Investment',
        background: '#0f172a',
        color: '#f1f5f9',
        html: `
            <form id="editPlanForm" method="POST" class="text-left">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="plan_id" value="${data.id}">
                <div class="grid grid-cols-1 gap-4 mt-4">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Plan Name</label>
                        <input type="text" name="plan_name" value="${data.plan_name}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Amount ($)</label>
                            <input type="number" step="0.01" name="amount" value="${data.amount}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        </div>
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Daily ROI ($)</label>
                            <input type="number" step="0.01" name="daily_return" value="${data.daily_return}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Duration (Days)</label>
                            <input type="number" name="duration" value="${data.duration}" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                        </div>
                        <div>
                            <label class="text-[10px] uppercase font-bold text-slate-500">Status</label>
                            <select name="status" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                                <option value="active" ${data.status === 'active' ? 'selected' : ''}>Active</option>
                                <option value="completed" ${data.status === 'completed' ? 'selected' : ''}>Completed</option>
                                <option value="pending" ${data.status === 'pending' ? 'selected' : ''}>Pending</option>
                            </select> 
                        </div>
                    </div>
                </div>
            </form>
        `,
        showCancelButton: true,
        confirmButtonText: 'Save Changes',
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('editPlanForm').submit(); }
    });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>