<?php
session_start();
require_once 'php/adminconfig.php';
// Enhanced login and role check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: signin-admin.php');
    exit();
}
// Simple logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: signin-admin.php');
    exit();
}

// Fetch all trading plans from the database
$query = "SELECT * FROM trading_plan ORDER BY id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$trading_plans = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle plan deletion
if (isset($_POST['delete_plan']) && isset($_POST['plan_id'])) {
    $plan_id = intval($_POST['plan_id']);
    
    try {
        $delete_query = "DELETE FROM trading_plan WHERE id = :plan_id";
        $delete_stmt = $conn->prepare($delete_query);
        $delete_stmt->bindParam(':plan_id', $plan_id, PDO::PARAM_INT);
        $delete_stmt->execute();
        
        // Set success message
        $_SESSION['success_message'] = "Trading plan deleted successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error deleting trading plan: " . $e->getMessage();
    }
}

// Handle plan data update
if (isset($_POST['update_plan']) && isset($_POST['plan_id'])) {
    $plan_id = intval($_POST['plan_id']);
    
    // Get all fields from the form excluding plan_id and update_plan
    $updateFields = [];
    $params = [];
    
    // Check if is_unlimited checkbox is set
    $is_unlimited = isset($_POST['is_unlimited']) ? 1 : 0;
    
    foreach ($_POST as $key => $value) {
        if ($key !== 'plan_id' && $key !== 'update_plan' && $key !== 'is_unlimited') {
            // Skip empty maximum_price if is_unlimited is checked
            if ($key === 'maximum_price' && $is_unlimited) {
                continue;
            }
            
            $updateFields[] = "$key = :$key";
            $params[":$key"] = $value;
        }
    }
    
    // Add is_unlimited field separately
    $updateFields[] = "is_unlimited = :is_unlimited";
    $params[":is_unlimited"] = $is_unlimited;
    
    if (!empty($updateFields)) {
        try {
            $update_query = "UPDATE trading_plan SET " . implode(", ", $updateFields) . " WHERE id = :plan_id";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bindParam(':plan_id', $plan_id, PDO::PARAM_INT);
            
            foreach ($params as $param => $value) {
                $update_stmt->bindValue($param, $value);
            }
            
            $update_stmt->execute();
            
            // Set success message
            $_SESSION['success_message'] = "Trading plan updated successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating trading plan: " . $e->getMessage();
        }
    }
}

// Handle new plan creation
if (isset($_POST['create_plan'])) {
    // Required fields validation
    if (empty($_POST['package_title']) || empty($_POST['minimum_price']) || 
        empty($_POST['duration']) || empty($_POST['daily_return_percent']) || 
        empty($_POST['asset_type'])) {
        $_SESSION['error_message'] = "All fields except maximum price are required.";
    } else {
        $package_title = $_POST['package_title'];
        $minimum_price = $_POST['minimum_price'];
        $maximum_price = !empty($_POST['maximum_price']) ? $_POST['maximum_price'] : null;
        $is_unlimited = isset($_POST['is_unlimited']) ? 1 : 0;
        $duration = $_POST['duration'];
        $daily_return_percent = $_POST['daily_return_percent'];
        $asset_type = $_POST['asset_type'];
        $icon = !empty($_POST['icon']) ? $_POST['icon'] : 'fa-chart-line'; // Default icon
        
        try {
            $insert_query = "INSERT INTO trading_plan (package_title, minimum_price, maximum_price, is_unlimited, duration, daily_return_percent, asset_type, icon) 
                           VALUES (:package_title, :minimum_price, :maximum_price, :is_unlimited, :duration, :daily_return_percent, :asset_type, :icon)";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bindParam(':package_title', $package_title);
            $insert_stmt->bindParam(':minimum_price', $minimum_price);
            $insert_stmt->bindParam(':maximum_price', $maximum_price);
            $insert_stmt->bindParam(':is_unlimited', $is_unlimited, PDO::PARAM_INT);
            $insert_stmt->bindParam(':duration', $duration);
            $insert_stmt->bindParam(':daily_return_percent', $daily_return_percent);
            $insert_stmt->bindParam(':asset_type', $asset_type);
            $insert_stmt->bindParam(':icon', $icon);
            $insert_stmt->execute();
            
            $_SESSION['success_message'] = "New trading plan created successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $_SESSION['error_message'] = "Package title already exists.";
            } else {
                $_SESSION['error_message'] = "Error creating trading plan: " . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9, user-scalable=no" />
    <title>Trading Plans Management - TradeWave plc</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="css/admin.css">
    
</head>
<body>

    <?php include "required/admin-nav.php" ?>

    <div class="pc">
    <div class="containeer">
        <div class="page-header">
            <h2 class="page-title">Manage Trading Plans</h2>
            <button class="btn btn-success" id="addPlanBtn">
                <i class="fas fa-plus"></i> Add New Trading Plan
            </button>
        </div>
        
        <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success">
                <span class="close-alert">&times;</span>
                <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger">
                <span class="close-alert">&times;</span>
                <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
            </div>
        <?php endif; ?>
        
        <div class="admin-grid">
            <?php foreach ($trading_plans as $plan): ?>
                <div class="admin-card" data-id="<?php echo $plan['id']; ?>">
                    <div class="admin-icon">
                        <i class="fas <?php echo htmlspecialchars($plan['icon'] ?: 'fa-chart-line'); ?>"></i>
                    </div>
                    <div class="admin-name">
                        <?php echo htmlspecialchars($plan['package_title']); ?>
                    </div>
                    <div class="admin-minimum_price">
                        <i class="fas fa-money-bill-wave"></i> 
                        <?php echo '$' . number_format($plan['minimum_price'], 2); ?>
                    </div>
                    <div class="admin-duration">
                        <i class="fas fa-calendar-days"></i> 
                        <?php echo htmlspecialchars($plan['duration']); ?> days
                    </div>
                    <div class="admin-created">
                        <?php echo date('M d, Y', strtotime($plan['created_at'])); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <?php foreach ($trading_plans as $plan): ?>
            <div class="admin-details" id="details-<?php echo $plan['id']; ?>">
                <h3>Edit Trading Plan: <?php echo htmlspecialchars($plan['package_title']); ?></h3>
                
                <button class="btn btn-danger delete-btn" data-id="<?php echo $plan['id']; ?>">Delete This Plan</button>
                
                <form action="" method="POST" class="edit-form">
                    <input type="hidden" name="plan_id" value="<?php echo $plan['id']; ?>">
                    
                    <div class="form-group">
                        <label for="package_title-<?php echo $plan['id']; ?>">Plan Title</label>
                        <input type="text" name="package_title" id="package_title-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['package_title']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="minimum_price-<?php echo $plan['id']; ?>">Minimum Price ($)</label>
                        <input type="number" step="0.01" name="minimum_price" id="minimum_price-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['minimum_price']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="is_unlimited-<?php echo $plan['id']; ?>">Unlimited Maximum</label>
                        <input type="checkbox" name="is_unlimited" id="is_unlimited-<?php echo $plan['id']; ?>" 
                            <?php echo $plan['is_unlimited'] ? 'checked' : ''; ?> 
                            onchange="toggleMaxPrice(this, '<?php echo $plan['id']; ?>')">
                    </div>
                    
                    <div class="form-group" id="max-price-group-<?php echo $plan['id']; ?>" <?php echo $plan['is_unlimited'] ? 'style="display:none;"' : ''; ?>>
                        <label for="maximum_price-<?php echo $plan['id']; ?>">Maximum Price ($)</label>
                        <input type="number" step="0.01" name="maximum_price" id="maximum_price-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['maximum_price'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="duration-<?php echo $plan['id']; ?>">Duration (days)</label>
                        <input type="number" name="duration" id="duration-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['duration']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="daily_return_percent-<?php echo $plan['id']; ?>">Daily Return (%)</label>
                        <input type="number" step="0.01" name="daily_return_percent" id="daily_return_percent-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['daily_return_percent']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="asset_type-<?php echo $plan['id']; ?>">Asset Type/Description</label>
                        <textarea name="asset_type" id="asset_type-<?php echo $plan['id']; ?>" class="form-control" required><?php echo htmlspecialchars($plan['asset_type']); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="icon-<?php echo $plan['id']; ?>">Icon (Font Awesome Class)</label>
                        <input type="text" name="icon" id="icon-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['icon'] ?? 'fa-chart-line'); ?>">
                        <p class="note">Example: fa-chart-line, fa-bitcoin, fa-money-bill-wave</p>
                    </div>
                    
                    <div class="form-group submit-row">
                        <button type="submit" name="update_plan" class="btn btn-primary">Update Plan</button>
                    </div>
                </form>
            </div>
        <?php endforeach; ?>
        
        <!-- Delete Confirmation Modal -->
        <div class="modal" id="deleteModal">
            <div class="modal-content">
                <div class="warning-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <h3 class="modal-title">Delete Trading Plan</h3>
                <p class="modal-text">Are you sure you want to delete this trading plan from database?</p>
                <div class="modal-actions">
                    <form id="deleteForm" action="" method="POST">
                        <input type="hidden" name="plan_id" id="deletePlanId">
                        <button type="submit" name="delete_plan" class="btn btn-danger">Yes, Delete</button>
                    </form>
                    <button class="btn btn-primary" id="cancelDelete">Cancel</button>
                </div>
            </div>
        </div>
        
        <!-- New Plan Modal -->
        <div class="modal" id="newPlanModal">
            <div class="modal-content">
                <div class="new-admin-form">
                    <h3>Add New Trading Plan</h3>
                    <form action="" method="POST" class="edit-form">
                        <div class="form-group">
                            <label for="new-package_title">Plan Title</label>
                            <input type="text" name="package_title" id="new-package_title" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-minimum_price">Minimum Price ($)</label>
                            <input type="number" step="0.01" name="minimum_price" id="new-minimum_price" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-is_unlimited">Unlimited Maximum</label>
                            <input type="checkbox" name="is_unlimited" id="new-is_unlimited" onchange="toggleNewMaxPrice(this)">
                        </div>
                        
                        <div class="form-group" id="new-max-price-group">
                            <label for="new-maximum_price">Maximum Price ($)</label>
                            <input type="number" step="0.01" name="maximum_price" id="new-maximum_price" class="form-control">
                        </div>

                        <div class="form-group">
                            <label for="new-duration">Duration (days)</label>
                            <input type="number" name="duration" id="new-duration" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-daily_return_percent">Daily Return (%)</label>
                            <input type="number" step="0.01" name="daily_return_percent" id="new-daily_return_percent" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-asset_type">Asset Type/Description</label>
                            <textarea name="asset_type" id="new-asset_type" class="form-control" required></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-icon">Icon (Font Awesome Class)</label>
                            <input type="text" name="icon" id="new-icon" class="form-control" value="fa-chart-line">
                            <p class="note">Example: fa-chart-line, fa-bitcoin, fa-money-bill-wave</p>
                        </div>
                        
                        <div class="form-group submit-row">
                            <button type="submit" name="create_plan" class="btn btn-success">Create Plan</button>
                            <button type="button" class="btn btn-danger" id="cancelAddPlan">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Plan card click handler
            const planCards = document.querySelectorAll('.admin-card');
            planCards.forEach(card => {
                card.addEventListener('click', function() {
                    const planId = this.getAttribute('data-id');
                    
                    // Hide all details sections
                    document.querySelectorAll('.admin-details').forEach(detail => {
                        detail.classList.remove('active');
                    });
                    
                    // Remove active class from all cards
                    planCards.forEach(c => {
                        c.classList.remove('active');
                    });
                    
                    // Show the clicked plan's details
                    document.getElementById('details-' + planId).classList.add('active');
                    
                    // Add active class to the clicked card
                    this.classList.add('active');
                    
                    // Scroll to the details section
                    document.getElementById('details-' + planId).scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                });
            });
            
            // Delete button click handler
            const deleteButtons = document.querySelectorAll('.delete-btn');
            const deleteModal = document.getElementById('deleteModal');
            const deleteForm = document.getElementById('deleteForm');
            const deletePlanId = document.getElementById('deletePlanId');
            const cancelDelete = document.getElementById('cancelDelete');
            
            deleteButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const planId = this.getAttribute('data-id');
                    deletePlanId.value = planId;
                    deleteModal.style.display = 'flex';
                });
            });
            
            // Cancel delete button
            cancelDelete.addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            // Add new plan button
            const addPlanBtn = document.getElementById('addPlanBtn');
            const newPlanModal = document.getElementById('newPlanModal');
            const cancelAddPlan = document.getElementById('cancelAddPlan');
            
            addPlanBtn.addEventListener('click', function() {
                newPlanModal.style.display = 'flex';
            });
            
            // Cancel add plan button
            cancelAddPlan.addEventListener('click', function() {
                newPlanModal.style.display = 'none';
            });
            
            // Close modals if clicked outside
            window.addEventListener('click', function(e) {
                if (e.target === deleteModal) {
                    deleteModal.style.display = 'none';
                }
                if (e.target === newPlanModal) {
                    newPlanModal.style.display = 'none';
                }
            });
            
            // Close alerts
            const closeAlerts = document.querySelectorAll('.close-alert');
            closeAlerts.forEach(btn => {
                btn.addEventListener('click', function() {
                    this.parentElement.style.display = 'none';
                });
            });
        });
        
        // Function to toggle maximum price field visibility
        function toggleMaxPrice(checkbox, id) {
            const maxPriceGroup = document.getElementById('max-price-group-' + id);
            if (checkbox.checked) {
                maxPriceGroup.style.display = 'none';
            } else {
                maxPriceGroup.style.display = 'block';
            }
        }
        
        // Function to toggle maximum price field visibility in new plan form
        function toggleNewMaxPrice(checkbox) {
            const maxPriceGroup = document.getElementById('new-max-price-group');
            if (checkbox.checked) {
                maxPriceGroup.style.display = 'none';
            } else {
                maxPriceGroup.style.display = 'block';
            }
        }
    </script>
</body>
</html>