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

// Handle admin deletion
if (isset($_POST['delete_admin']) && isset($_POST['admin_id'])) {
    $admin_id = intval($_POST['admin_id']);
    
    // Prevent deleting yourself
    if ($admin_id == $_SESSION['admin_id']) {
        $_SESSION['error_message'] = "You cannot delete your own account.";
    } else {
        try {
            $delete_query = "DELETE FROM admins WHERE id = :admin_id";
            $delete_stmt = $conn->prepare($delete_query);
            $delete_stmt->bindParam(':admin_id', $admin_id, PDO::PARAM_INT);
            $delete_stmt->execute();
            
            // Set success message
            $_SESSION['success_message'] = "Admin deleted successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error deleting admin: " . $e->getMessage();
        }
    }
}

// Handle admin data update
if (isset($_POST['update_admin']) && isset($_POST['admin_id'])) {
    $admin_id = intval($_POST['admin_id']);
    
    // Get all fields from the form excluding admin_id, update_admin and password if empty
    $updateFields = [];
    $params = [];
    
    foreach ($_POST as $key => $value) {
        if ($key !== 'admin_id' && $key !== 'update_admin') {
            // Skip empty password (don't update password if not provided)
            if ($key === 'password' && empty($value)) {
                continue;
            }
            
            // Hash password if provided
            if ($key === 'password' && !empty($value)) {
                $value = password_hash($value, PASSWORD_DEFAULT);
            }
            
            $updateFields[] = "$key = :$key";
            $params[":$key"] = $value;
        }
    }
    
    if (!empty($updateFields)) {
        try {
            $update_query = "UPDATE admins SET " . implode(", ", $updateFields) . " WHERE id = :admin_id";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bindParam(':admin_id', $admin_id, PDO::PARAM_INT);
            
            foreach ($params as $param => $value) {
                $update_stmt->bindValue($param, $value);
            }
            
            $update_stmt->execute();
            
            // Set success message
            $_SESSION['success_message'] = "Admin updated successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error updating admin: " . $e->getMessage();
        }
    }
}

// Handle new admin creation
if (isset($_POST['create_admin'])) {
    // Required fields validation
    if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
        $_SESSION['error_message'] = "Username, email, and password are required fields.";
    } else {
        $username = $_POST['username'];
        $email = $_POST['email'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $role = isset($_POST['role']) ? $_POST['role'] : 'admin';
        
        try {
            $insert_query = "INSERT INTO admins (username, email, password, role) VALUES (:username, :email, :password, :role)";
            $insert_stmt = $conn->prepare($insert_query);
            $insert_stmt->bindParam(':username', $username);
            $insert_stmt->bindParam(':email', $email);
            $insert_stmt->bindParam(':password', $password);
            $insert_stmt->bindParam(':role', $role);
            $insert_stmt->execute();
            
            $_SESSION['success_message'] = "New admin created successfully";
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit();
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                $_SESSION['error_message'] = "Username or email already exists.";
            } else {
                $_SESSION['error_message'] = "Error creating admin: " . $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>Admin 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">
    <style>
        :root {
            --primary-color: #6c5ce7;
            --secondary-color: #8e44ad;
            --success-color: #27ae60;
            --danger-color: #e74c3c;
            --light-color: #f5f6fa;
            --dark-color: #2c3e50;
            --border-color: #dcdde1;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        .containeer {
            padding: 20px;
            width: 100%;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .page-title {
            color: var(--dark-color);
            font-size: 1.8rem;
        }
        
        .admin-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .admin-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            position: relative;
            border-left: 4px solid var(--secondary-color);
        }
        
        .admin-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
        }
        
        .admin-card.active {
            border-color: var(--primary-color);
            background-color: rgba(142, 68, 173, 0.05);
        }
        
        .admin-icon {
            width: 50px;
            height: 50px;
            background-color: var(--secondary-color);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            float: left;
            margin-right: 15px;
            font-size: 24px;
        }
        
        .admin-name {
            font-weight: bold;
            font-size: 18px;
            margin-bottom: 5px;
            color: var(--dark-color);
        }
        
        .admin-email {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
            word-break: break-all;
        }
        
        .admin-role {
            color: var(--primary-color);
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 5px;
        }
        
        .admin-created {
            color: #999;
            font-size: 12px;
            position: absolute;
            bottom: 10px;
            right: 15px;
        }
        
        .admin-details {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 3px 15px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
            margin-bottom: 40px;
            padding: 20px;
            position: relative;
            display: none;
        }
        
        .admin-details.active {
            display: block;
        }
        
        .admin-details h3 {
            color: var(--secondary-color);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }
        
        .edit-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        @media (max-width: 768px) {
            .edit-form {
                grid-template-columns: 1fr;
            }
            
            .admin-grid {
                grid-template-columns: 1fr;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: var(--dark-color);
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
        }
        
        textarea.form-control {
            min-height: 100px;
            resize: vertical;
        }
        
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-color);
        }
        
        .btn-success {
            background-color: var(--success-color);
            color: white;
        }
        
        .btn-success:hover {
            background-color: #219653;
        }
        
        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #c0392b;
        }
        
        .delete-btn {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: white;
            border-radius: 8px;
            width: 90%;
            max-width: 500px;
            padding: 20px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
        }
        
        .warning-icon {
            font-size: 48px;
            color: #f39c12;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .modal-title {
            font-size: 20px;
            margin-bottom: 15px;
            color: var(--dark-color);
            text-align: center;
        }
        
        .modal-text {
            margin-bottom: 20px;
            color: #555;
            text-align: center;
        }
        
        .modal-actions {
            display: flex;
            justify-content: center;
            gap: 10px;
        }
        
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            color: white;
            position: relative;
        }
        
        .alert-success {
            background-color: var(--success-color);
        }
        
        .alert-danger {
            background-color: var(--danger-color);
        }
        
        .close-alert {
            position: absolute;
            top: 15px;
            right: 15px;
            cursor: pointer;
            font-weight: bold;
        }
        
        .submit-row {
            grid-column: 1 / -1;
            margin-top: 15px;
        }
        
        .new-admin-form h3 {
            color: var(--success-color);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }
        
        #newAdminModal .modal-content {
            max-width: 600px;
        }
        
        .note {
            color: #666;
            font-size: 13px;
            margin-top: 5px;
            font-style: italic;
        }
        
        .self-tag {
            display: inline-block;
            padding: 3px 8px;
            background-color: var(--primary-color);
            color: white;
            border-radius: 12px;
            font-size: 11px;
            margin-left: 10px;
        }
    </style>
</head>
<body>

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

    <div class="pc">
    <div class="containeer">
        <div class="page-header">
            <h2 class="page-title">Admin Management</h2>
            <button class="btn btn-success" id="addAdminBtn">
                <i class="fas fa-plus"></i> Add New Admin
            </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 ($admins as $admin): ?>
                <div class="admin-card" data-id="<?php echo $admin['id']; ?>">
                    <div class="admin-icon">
                        <i class="fas fa-user-shield"></i>
                    </div>
                    <div class="admin-name">
                        <?php echo htmlspecialchars($admin['username']); ?>
                        <?php if ($admin['id'] == $_SESSION['admin_id']): ?>
                            <span class="self-tag">You</span>
                        <?php endif; ?>
                    </div>
                    <div class="admin-email"><?php echo htmlspecialchars($admin['email']); ?></div>
                    <div class="admin-role"><?php echo ucfirst(htmlspecialchars($admin['role'])); ?></div>
                    <div class="admin-created">
                        <?php echo date('M d, Y', strtotime($admin['created_at'])); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <?php foreach ($admins as $admin): ?>
            <div class="admin-details" id="details-<?php echo $admin['id']; ?>">
                <h3>Edit Admin: <?php echo htmlspecialchars($admin['username']); ?></h3>
                
                <?php if ($admin['id'] != $_SESSION['admin_id']): ?>
                    <button class="btn btn-danger delete-btn" data-id="<?php echo $admin['id']; ?>">Delete Admin</button>
                <?php endif; ?>
                
                <form action="" method="POST" class="edit-form">
                    <input type="hidden" name="admin_id" value="<?php echo $admin['id']; ?>">
                    
                    <div class="form-group">
                        <label for="username-<?php echo $admin['id']; ?>">Username</label>
                        <input type="text" name="username" id="username-<?php echo $admin['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($admin['username']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="email-<?php echo $admin['id']; ?>">Email</label>
                        <input type="email" name="email" id="email-<?php echo $admin['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($admin['email']); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="password-<?php echo $admin['id']; ?>">Password</label>
                        <input type="password" name="password" id="password-<?php echo $admin['id']; ?>" class="form-control" placeholder="Leave blank to keep current password">
                        <p class="note">Leave blank to keep current password</p>
                    </div>
                    
                    <div class="form-group">
                        <label for="role-<?php echo $admin['id']; ?>">Role</label>
                        <select name="role" id="role-<?php echo $admin['id']; ?>" class="form-control">
                            <option value="admin" <?php echo $admin['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                            <option value="super_admin" <?php echo $admin['role'] == 'super_admin' ? 'selected' : ''; ?>>Super Admin</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="company_name-<?php echo $admin['id']; ?>">Company Name</label>
                        <input type="text" name="company_name" id="company_name-<?php echo $admin['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($admin['company_name'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="company_email-<?php echo $admin['id']; ?>">Company Email</label>
                        <input type="email" name="company_email" id="company_email-<?php echo $admin['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($admin['company_email'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="company_phonenumber-<?php echo $admin['id']; ?>">Company Phone</label>
                        <input type="text" name="company_phonenumber" id="company_phonenumber-<?php echo $admin['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($admin['company_phonenumber'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="company_monthly_revenue-<?php echo $admin['id']; ?>">Monthly Revenue</label>
                        <input type="number" step="0.01" name="company_monthly_revenue" id="company_monthly_revenue-<?php echo $admin['id']; ?>" class="form-control" value="<?php echo htmlspecialchars($admin['company_monthly_revenue'] ?? '0.00'); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="company_address-<?php echo $admin['id']; ?>">Company Address</label>
                        <textarea name="company_address" id="company_address-<?php echo $admin['id']; ?>" class="form-control"><?php echo htmlspecialchars($admin['company_address'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="company_purpose-<?php echo $admin['id']; ?>">Company Purpose</label>
                        <textarea name="company_purpose" id="company_purpose-<?php echo $admin['id']; ?>" class="form-control"><?php echo htmlspecialchars($admin['company_purpose'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="company_description-<?php echo $admin['id']; ?>">Company Description</label>
                        <textarea name="company_description" id="company_description-<?php echo $admin['id']; ?>" class="form-control"><?php echo htmlspecialchars($admin['company_description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group submit-row">
                        <button type="submit" name="update_admin" class="btn btn-primary">Update Admin</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 Admin</h3>
                <p class="modal-text">Are you sure you want to delete this admin from database?</p>
                <div class="modal-actions">
                    <form id="deleteForm" action="" method="POST">
                        <input type="hidden" name="admin_id" id="deleteAdminId">
                        <button type="submit" name="delete_admin" class="btn btn-danger">Yes, Delete</button>
                    </form>
                    <button class="btn btn-primary" id="cancelDelete">Cancel</button>
                </div>
            </div>
        </div>
        
        <!-- New Admin Modal -->
        <div class="modal" id="newAdminModal">
            <div class="modal-content">
                <div class="new-admin-form">
                    <h3>Add New Admin</h3>
                    <form action="" method="POST" class="edit-form">
                        <div class="form-group">
                            <label for="new-username">Username</label>
                            <input type="text" name="username" id="new-username" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-email">Email</label>
                            <input type="email" name="email" id="new-email" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-password">Password</label>
                            <input type="password" name="password" id="new-password" class="form-control" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-role">Role</label>
                            <select name="role" id="new-role" class="form-control">
                                <option value="admin">Admin</option>
                                <option value="super_admin">Super Admin</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="new-company-name">Company Name</label>
                            <input type="text" name="company_name" id="new-company-name" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label for="new-company-email">Company Email</label>
                            <input type="email" name="company_email" id="new-company-email" class="form-control">
                        </div>
                        
                        <div class="form-group submit-row">
                            <button type="submit" name="create_admin" class="btn btn-success">Create Admin</button>
                            <button type="button" class="btn btn-danger" id="cancelAddAdmin">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Admin card click handler
            const adminCards = document.querySelectorAll('.admin-card');
            adminCards.forEach(card => {
                card.addEventListener('click', function() {
                    const adminId = this.getAttribute('data-id');
                    
                    // Hide all details sections
                    document.querySelectorAll('.admin-details').forEach(detail => {
                        detail.classList.remove('active');
                    });
                    
                    // Remove active class from all cards
                    adminCards.forEach(c => {
                        c.classList.remove('active');
                    });
                    
                    // Show the clicked admin's details
                    document.getElementById('details-' + adminId).classList.add('active');
                    
                    // Add active class to the clicked card
                    this.classList.add('active');
                    
                    // Scroll to the details section
                    document.getElementById('details-' + adminId).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 deleteAdminId = document.getElementById('deleteAdminId');
            const cancelDelete = document.getElementById('cancelDelete');
            
            deleteButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    const adminId = this.getAttribute('data-id');
                    deleteAdminId.value = adminId;
                    deleteModal.style.display = 'flex';
                });
            });
            
            // Cancel delete button
            cancelDelete.addEventListener('click', function() {
                deleteModal.style.display = 'none';
            });
            
            // Add new admin button
            const addAdminBtn = document.getElementById('addAdminBtn');
            const newAdminModal = document.getElementById('newAdminModal');
            const cancelAddAdmin = document.getElementById('cancelAddAdmin');
            
            addAdminBtn.addEventListener('click', function() {
                newAdminModal.style.display = 'flex';
            });
            
            // Cancel add admin button
            cancelAddAdmin.addEventListener('click', function() {
                newAdminModal.style.display = 'none';
            });
            
            // Close modals if clicked outside
            window.addEventListener('click', function(e) {
                if (e.target === deleteModal) {
                    deleteModal.style.display = 'none';
                }
                if (e.target === newAdminModal) {
                    newAdminModal.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>