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

<?php 
// Cek apakah user adalah supervisor, developer, atau superadmin
if ($_SESSION['role'] !== 'supervisor' && $_SESSION['role'] !== 'developer' && $_SESSION['role'] !== 'superadmin') {
    header("Location: dashboard.php");
    exit();
}

// Ambil daftar marketing
try {
    $db_auth->exec("USE " . DB_AUTH_NAME);
    
    // Query berbeda untuk setiap role
    if ($_SESSION['role'] === 'supervisor') {
        // Supervisor hanya bisa lihat marketing yang dia buat
        $stmt = $db_auth->prepare("
            SELECT id, username, nama_lengkap, email 
            FROM marketing 
            WHERE supervisor_id = ? 
            ORDER BY created_at DESC
        ");
        $stmt->execute([$_SESSION['user_id']]);
    } else {
        // Developer dan Superadmin bisa lihat semua marketing
        $stmt = $db_auth->prepare("
            SELECT m.id, m.username, m.nama_lengkap, m.email, 
                   s.username as supervisor_name,
                   m.created_at,
                   CASE 
                       WHEN m.supervisor_id IS NULL THEN 'Unassigned'
                       ELSE s.username 
                   END as supervisor_name
            FROM marketing m
            LEFT JOIN supervisor s ON m.supervisor_id = s.id
            ORDER BY m.created_at DESC
        ");
        $stmt->execute();
    }
    $marketing_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching marketing data: " . $e->getMessage());
    $marketing_list = [];
}

// Handle form submission untuk edit admin
if (isset($_POST['update'])) {
    // Verifikasi CSRF token
    if (!verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Invalid security token!";
        header("Location: users.php");
        exit();
    }

    $username = sanitize_input($_POST['username']);
    $password = $_POST['password'];
    $password_confirmation = $_POST['password_confirmation'];
    
    try {
        $db_auth->exec("USE " . DB_AUTH_NAME);
        
        // Validasi
        if ($password !== '') {
            if (strlen($password) < 6) {
                throw new Exception("Password must be at least 6 characters long");
            }
            if ($password !== $password_confirmation) {
                throw new Exception("Password confirmation does not match");
            }
            
            // Update username dan password
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $db_auth->prepare("
                UPDATE supervisor 
                SET username = ?, password = ? 
                WHERE id = ?
            ");
            $stmt->execute([$username, $hash, $_SESSION['user_id']]);
            
        } else {
            // Update username saja
            $stmt = $db_auth->prepare("
                UPDATE supervisor 
                SET username = ? 
                WHERE id = ?
            ");
            $stmt->execute([$username, $_SESSION['user_id']]);
        }
        
        $_SESSION['success'] = "Profile updated successfully!";
        header("Location: users.php");
        exit();
        
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
        header("Location: users.php");
        exit();
    }
}

// Ambil data supervisor untuk ditampilkan di form
try {
    $db_auth->exec("USE " . DB_AUTH_NAME);
    $stmt = $db_auth->prepare("SELECT username FROM supervisor WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching supervisor data: " . $e->getMessage());
    $admin = ['username' => ''];
}
?>

<div class="content" id="content">
    <div class="container-fluid">
        <h1 class="h3 mb-4">Users</h1>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger">
                <?php 
                echo $_SESSION['error'];
                unset($_SESSION['error']);
                ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success">
                <?php 
                echo $_SESSION['success'];
                unset($_SESSION['success']);
                ?>
            </div>
        <?php endif; ?>
        
        <!-- Admin Edit Card -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Admin Edit</h5>
            </div>
            <div class="card-body p-4">
                <form method="POST" action="">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    
                    <div class="mb-4">
                        <div class="input-group">
                            <span class="input-group-text bg-light">
                                <i class="fas fa-user text-primary"></i>
                            </span>
                            <input type="text" class="form-control" id="username" name="username" 
                                value="<?php echo htmlspecialchars($admin['username']); ?>" required>
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <div class="input-group">
                            <span class="input-group-text bg-light">
                                <i class="fas fa-key text-primary"></i>
                            </span>
                            <input type="password" class="form-control" id="password" name="password" 
                                placeholder="Enter new password">
                        </div>
                        <small class="text-muted">Leave blank if you don't want to change the password</small>
                    </div>

                    <div class="mb-4">
                        <div class="input-group">
                            <span class="input-group-text bg-light">
                                <i class="fas fa-lock text-primary"></i>
                            </span>
                            <input type="password" class="form-control" id="password_confirmation" 
                                name="password_confirmation" placeholder="Confirm new password">
                        </div>
                    </div>

                    <div class="d-grid">
                        <button type="submit" name="update" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>UPDATE
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Marketing Table -->
        <h5 class="mb-3">Marketing</h5>
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div class="input-group input-group-sm" style="width: 250px;">
                <span class="input-group-text bg-light">
                    <i class="fas fa-search text-primary"></i>
                </span>
                <input type="text" class="form-control" id="searchInput" placeholder="Search username...">
            </div>
            <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addMarketingModal">
                <i class="fas fa-plus me-1"></i>Add Marketing
            </button>
        </div>

        <div class="card">
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th width="5%">No.</th>
                            <th>Username</th>
                            <?php if ($_SESSION['role'] !== 'supervisor'): ?>
                            <th>Supervisor</th>
                            <th>Created At</th>
                            <?php endif; ?>
                            <th width="20%" class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody id="marketingTable">
                        <?php foreach ($marketing_list as $index => $marketing): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><?php echo htmlspecialchars($marketing['username']); ?></td>
                                <?php if ($_SESSION['role'] !== 'supervisor'): ?>
                                <td><?php echo htmlspecialchars($marketing['supervisor_name']); ?></td>
                                <td><?php echo date('d M Y H:i', strtotime($marketing['created_at'])); ?></td>
                                <?php endif; ?>
                                <td class="text-end">
                                    <?php if ($_SESSION['role'] === 'supervisor'): ?>
                                        <!-- Tombol edit & delete untuk supervisor -->
                                        <button class="btn btn-sm btn-warning me-1" data-bs-toggle="modal" data-bs-target="#editMarketingModal" 
                                            data-id="<?php echo $marketing['id']; ?>"
                                            data-username="<?php echo htmlspecialchars($marketing['username']); ?>"
                                            data-nama_lengkap="<?php echo htmlspecialchars($marketing['nama_lengkap']); ?>"
                                            data-email="<?php echo htmlspecialchars($marketing['email']); ?>">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#deleteMarketingModal"
                                            data-id="<?php echo $marketing['id']; ?>">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    <?php else: ?>
                                        <!-- Tombol view detail untuk developer dan superadmin -->
                                        <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#viewMarketingModal"
                                            data-id="<?php echo $marketing['id']; ?>"
                                            data-username="<?php echo htmlspecialchars($marketing['username']); ?>"
                                            data-nama_lengkap="<?php echo htmlspecialchars($marketing['nama_lengkap']); ?>"
                                            data-email="<?php echo htmlspecialchars($marketing['email']); ?>"
                                            data-supervisor="<?php echo htmlspecialchars($marketing['supervisor_name']); ?>"
                                            data-created="<?php echo date('d M Y H:i', strtotime($marketing['created_at'])); ?>">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Marketing Modal -->
<div class="modal fade" id="addMarketingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Marketing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addMarketingForm" method="POST" action="add_marketing.php">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="nama_lengkap" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirm Password</label>
                        <input type="password" name="password_confirmation" class="form-control" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" form="addMarketingForm" class="btn btn-primary btn-sm">Add</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Marketing Modal -->
<div class="modal fade" id="editMarketingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Marketing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="editMarketingForm" method="POST" action="edit_marketing.php">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <input type="hidden" name="marketing_id" id="edit_marketing_id">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" name="username" id="edit_username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="nama_lengkap" id="edit_nama_lengkap" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" id="edit_email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">New Password</label>
                        <input type="password" name="password" class="form-control" placeholder="Enter new password">
                        <small class="text-muted">Leave blank if you don't want to change the password</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirm New Password</label>
                        <input type="password" name="password_confirmation" class="form-control" placeholder="Confirm new password">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" form="editMarketingForm" class="btn btn-primary btn-sm">Update</button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Marketing Modal -->
<div class="modal fade" id="deleteMarketingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Marketing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="deleteMarketingForm" method="POST" action="delete_marketing.php">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <input type="hidden" name="marketing_id" id="delete_marketing_id">
                    <p>Are you sure you want to delete this marketing account?</p>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" form="deleteMarketingForm" class="btn btn-danger btn-sm">Delete</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal View Detail untuk developer dan superadmin -->
<div class="modal fade" id="viewMarketingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Marketing Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Username</label>
                    <input type="text" id="view_username" class="form-control" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">Full Name</label>
                    <input type="text" id="view_nama_lengkap" class="form-control" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">Email</label>
                    <input type="email" id="view_email" class="form-control" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">Supervisor</label>
                    <input type="text" id="view_supervisor" class="form-control" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">Created At</label>
                    <input type="text" id="view_created" class="form-control" readonly>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('searchInput').addEventListener('keyup', function() {
    let searchQuery = this.value.toLowerCase();
    let tableBody = document.getElementById('marketingTable');
    let rows = tableBody.getElementsByTagName('tr');

    for (let row of rows) {
        let username = row.getElementsByTagName('td')[1].textContent.toLowerCase();
        if (username.includes(searchQuery)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    }
});

// Script untuk Edit Modal
document.querySelectorAll('[data-bs-target="#editMarketingModal"]').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const username = this.getAttribute('data-username');
        const nama_lengkap = this.getAttribute('data-nama_lengkap');
        const email = this.getAttribute('data-email');
        
        document.getElementById('edit_marketing_id').value = id;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_nama_lengkap').value = nama_lengkap;
        document.getElementById('edit_email').value = email;
    });
});

// Script untuk Delete Modal
document.querySelectorAll('[data-bs-target="#deleteMarketingModal"]').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        document.getElementById('delete_marketing_id').value = id;
    });
});

// Script untuk View Modal
document.querySelectorAll('[data-bs-target="#viewMarketingModal"]').forEach(button => {
    button.addEventListener('click', function() {
        const username = this.getAttribute('data-username');
        const nama_lengkap = this.getAttribute('data-nama_lengkap');
        const email = this.getAttribute('data-email');
        const supervisor = this.getAttribute('data-supervisor');
        const created = this.getAttribute('data-created');
        
        document.getElementById('view_username').value = username;
        document.getElementById('view_nama_lengkap').value = nama_lengkap;
        document.getElementById('view_email').value = email;
        document.getElementById('view_supervisor').value = supervisor;
        document.getElementById('view_created').value = created;
    });
});
</script>

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