<?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 traders from the database
$query = "SELECT * FROM traders ORDER BY id DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$trading_plans = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle trader deletion
if (isset($_POST['delete_plan']) && isset($_POST['plan_id'])) {
    $plan_id = intval($_POST['plan_id']);
    
    try {
        $delete_query = "DELETE FROM traders 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'] = "Trader deleted successfully";
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error deleting trader: " . $e->getMessage();
    }
}

// Handle trader 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 = [];
    
    foreach ($_POST as $key => $value) {
        if ($key !== 'plan_id' && $key !== 'update_plan') {
            $updateFields[] = "$key = :$key";
            $params[":$key"] = $value;
        }
    }
    
    if (!empty($updateFields)) {
        try {
            $update_query = "UPDATE traders 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'] = "Trader updated successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating trader: " . $e->getMessage();
        }
    }
}

// Handle new trader creation
if (isset($_POST['create_plan'])) {
    // Required fields validation
    if (empty($_POST['name']) || empty($_POST['title']) || 
        empty($_POST['star_rating']) || empty($_POST['market_value']) || 
        empty($_POST['status']) || empty($_POST['image_path'])) {
        $_SESSION['error_message'] = "All fields are required.";
    } else {
        $name = $_POST['name'];
        $title = $_POST['title'];
        $star_rating = $_POST['star_rating'];
        $market_value = $_POST['market_value'];
        $status = $_POST['status'];
        $image_path = $_POST['image_path'];
        
        try {
            $insert_query = "INSERT INTO traders (name, title, star_rating, market_value, status, image_path) 
                           VALUES (:name, :title, :star_rating, :market_value, :status, :image_path)";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bindParam(':name', $name);
            $insert_stmt->bindParam(':title', $title);
            $insert_stmt->bindParam(':star_rating', $star_rating);
            $insert_stmt->bindParam(':market_value', $market_value);
            $insert_stmt->bindParam(':status', $status);
            $insert_stmt->bindParam(':image_path', $image_path);
            $insert_stmt->execute();
            
            $_SESSION['success_message'] = "New trader created successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $_SESSION['error_message'] = "Trader name already exists.";
            } else {
                $_SESSION['error_message'] = "Error creating trader: " . $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>Traders 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 Traders</h2>
            <button class="btn btn-success" id="addPlanBtn">
                <i class="fas fa-plus"></i> Add New Trader
            </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">
                        <img src="<?php echo htmlspecialchars($plan['image_path']); ?>" alt="<?php echo htmlspecialchars($plan['name']); ?>" style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover;">
                    </div>
                    <div class="admin-name">
                        <?php echo htmlspecialchars($plan['name']); ?>
                    </div>
                    <div class="admin-minimum_price">
                        <i class="fas fa-chart-line"></i> 
                        <?php echo htmlspecialchars($plan['title']); ?>
                    </div>
                    <div class="admin-duration">
                        <i class="fas fa-star"></i> 
                        <?php echo number_format($plan['star_rating'], 1); ?> rating
                    </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 Trader: <?php echo htmlspecialchars($plan['name']); ?></h3>
                
                <button class="btn btn-danger delete-btn" data-id="<?php echo $plan['id']; ?>">Delete This Trader</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="name-<?php echo $plan['id']; ?>">Trader Name</label>
                        <input type="text" name="name" id="name-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['name']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="title-<?php echo $plan['id']; ?>">Title/Position</label>
                        <input type="text" name="title" id="title-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['title']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="star_rating-<?php echo $plan['id']; ?>">Star Rating (1-5)</label>
                        <input type="number" step="0.1" min="1" max="5" name="star_rating" id="star_rating-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['star_rating']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="market_value-<?php echo $plan['id']; ?>">Market Value ($)</label>
                        <input type="number" step="0.01" name="market_value" id="market_value-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['market_value']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="status-<?php echo $plan['id']; ?>">Status</label>
                        <select name="status" id="status-<?php echo $plan['id']; ?>" class="form-control" required>
                            <option value="live" <?php echo $plan['status'] === 'live' ? 'selected' : ''; ?>>Live</option>
                            <option value="offline" <?php echo $plan['status'] === 'offline' ? 'selected' : ''; ?>>Offline</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="image_path-<?php echo $plan['id']; ?>">Image Path/URL</label>
                        <input type="text" name="image_path" id="image_path-<?php echo $plan['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($plan['image_path']); ?>" required>
                        <p class="note">Enter the full path or URL to the trader's image</p>
                    </div>
                    
                    <div class="form-group submit-row">
                        <button type="submit" name="update_plan" class="btn btn-primary">Update Trader</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 Trader</h3>
                <p class="modal-text">Are you sure you want to delete this trader 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 Trader Modal -->
        <div class="modal" id="newPlanModal">
            <div class="modal-content">
                <div class="new-admin-form">
                    <h3>Add New Trader</h3>
                    <form action="" method="POST" class="edit-form">
                        <div class="form-group">
                            <label for="new-name">Trader Name</label>
                            <input type="text" name="name" id="new-name" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-title">Title/Position</label>
                            <input type="text" name="title" id="new-title" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-star_rating">Star Rating (1-5)</label>
                            <input type="number" step="0.1" min="1" max="5" name="star_rating" id="new-star_rating" class="form-control" value="3.5" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-market_value">Market Value ($)</label>
                            <input type="number" step="0.01" name="market_value" id="new-market_value" class="form-control" required>
                        </div>

                        <div class="form-group">
                            <label for="new-status">Status</label>
                            <select name="status" id="new-status" class="form-control" required>
                                <option value="live">Live</option>
                                <option value="offline">Offline</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-image_path">Image Path/URL</label>
                            <input type="text" name="image_path" id="new-image_path" class="form-control" required>
                            <p class="note">Enter the full path or URL to the trader's image</p>
                        </div>
                        
                        <div class="form-group submit-row">
                            <button type="submit" name="create_plan" class="btn btn-success">Create Trader</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 trader'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 trader 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 trader 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';
                });
            });
        });
    </script>
</body>
</html>