<?php
require_once '../../controller/process.php';

// Get search term from URL if it exists
$searchTerm = isset($_GET['search']) ? trim($_GET['search']) : '';

// Pagination logic
$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$per_page = 10;

$processor = new UserProcessor();
$result = $processor->getPaginatedUsers($current_page, $per_page, $searchTerm);
$users = $result['data'];
$total_users = $result['total'];
$total_pages = ceil($total_users / $per_page);



$genderStats = $processor->getGenderStatistics();
$statusStats = $processor->getStatusStatistics();
$action = (isset($_GET['action']) && $_GET['action'] != '') ? $_GET['action'] : '';
$femaleTotal = $genderStats['female'];
$maleTotal = $genderStats['male'];
$othersTotal = $genderStats['others'];
$pwdTotal = $statusStats['pwd'];
$regularTotal = $statusStats['regular'];

$processor->close();
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link rel="stylesheet" href="dashboard.css">
    <link href='https://fonts.googleapis.com/css?family=Ramabhadra' rel='stylesheet'>
    <link href="https://fonts.googleapis.com/css2?family=Assistant&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Days+One&family=Lexend:wght@100..900&family=Teko:wght@300..700&display=swap');
    </style>
</head>

<body>

    <nav class="navbar">
        <div class="navbar-container">
            <a href="#" class="navbar-brand">
                <img src="logo.png" alt="PharmaEase Logo">
                <span>PharmaEase</span> </a>
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a href="home.php" class="nav-link">Home</a>
                </li>
                <li class="nav-item">
                    <a href="dashboard.php" class="nav-link">Dashboard</a>
                </li>
                <li class="nav-item">
                    <a href="user-profile.php" class="nav-link">Profile</a>
                </li>
                <li class="nav-item">
                    <a href="index.php" class="nav-link">Logout</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="header">Dashboard</div>

    <div class="container">
        <h1>User Management</h1>

        <div class="filter-container">
            <form method="GET" action="" class="search-form">
                <input type="text" name="search" class="search-bar" placeholder="Search users..."
                    value="<?php echo htmlspecialchars($searchTerm); ?>">
                <button type="submit" class="search-button">Search</button>
                <?php if (!empty($searchTerm)): ?>
                    <a href="dashboard.php" class="clear-search">Clear</a>
                <?php endif; ?>
            </form>
            <select class="time-filter" id="timeFilter">
                <option value="daily">Daily</option>
                <option value="weekly">Weekly</option>
                <option value="monthly">Monthly</option>
                <option value="yearly">Yearly</option>
            </select>
        </div>
        <div class="chart-container">


            <canvas id="myChart"></canvas>
        </div>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Gender</th>
                    <th>Status</th>
                    <th colspan="3">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($users && $users->num_rows > 0) {
                    while ($row = $users->fetch_assoc()) {
                        echo "<tr>";
                        echo "<td>" . htmlspecialchars($row['ID']) . "</td>";
                        echo "<td>" . htmlspecialchars($row['Name']) . "</td>";
                        echo "<td>" . htmlspecialchars($row['Email']) . "</td>";
                        echo "<td>" . htmlspecialchars($row['Gender']) . "</td>";
                        echo "<td class='Status-" . strtolower($row['Status']) . "'>" . htmlspecialchars($row['Status']) . "</td>";
                        echo "<td class='action-buttons'>";
                        echo '<a href="../../model/edit.php?id=' . $row['ID'] . '" class="edit-btn">Edit</a>';
                        echo '<a href="add.php?id=' . $row['ID'] . '" class="edit-btn">Add</a>';
                        echo '<a href="../../model/delete.php?id=' . $row['ID'] . '" class="edit-btn" onclick="return confirm(\'Are you sure you want to delete this user?\')">Delete</a>';
                        echo "</td>";
                        echo "</tr>";
                    }
                } else {
                    echo "<tr><td colspan='8'>No users found</td></tr>";
                }
                ?>
            </tbody>
        </table>
        <div class="pagination" style="text-align: center;">
            <?php if ($current_page > 1): ?>
                <a href="?page=<?= $current_page - 1 ?><?= !empty($searchTerm) ? '&search=' . urlencode($searchTerm) : '' ?>"
                    class="prev-btn">&laquo;</a>
            <?php endif; ?>

            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?page=<?= $i ?><?= !empty($searchTerm) ? '&search=' . urlencode($searchTerm) : '' ?>"
                    class="<?= ($i == $current_page) ? 'active' : '' ?>"><?= $i ?></a>
            <?php endfor; ?>

            <?php if ($current_page < $total_pages): ?>
                <a href="?page=<?= $current_page + 1 ?><?= !empty($searchTerm) ? '&search=' . urlencode($searchTerm) : '' ?>"
                    class="next-btn">&raquo;</a>
            <?php endif; ?>
        </div>
        <form method="POST" action="../../controller/generatePDF.php" id="pdfForm">
            <input type="submit" value="Generate PDF" id="pdfButton">
        </form>
        <a href="../../model/add.php?id=' . $row['ID'] . '" class="edit-btn"
            onclick="return confirm(\'Are you sure you want to delete this user?\')">Add</a>

    </div>
</body>

</html>
<script>
    var femaleTotal = <?php echo $femaleTotal; ?>;
    var maleTotal = <?php echo $maleTotal; ?>;
    var othersTotal = <?php echo $othersTotal; ?>;
    var pwdTotal = <?php echo $pwdTotal; ?>;
    var regularTotal = <?php echo $regularTotal; ?>;

    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Male', 'Female', 'Others', 'PWD', 'Regular'],
            datasets: [{
                label: 'Total Users',
                data: [maleTotal, femaleTotal, othersTotal, pwdTotal, regularTotal],
                backgroundColor: [
                    'rgba(0, 0, 235, 0.2)',
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(0, 255, 255, 0.2)',
                    'rgba(0, 0, 0, 0.8)',
                    'rgba(128, 0, 32, 0.6)'
                ],
                borderColor: [
                    'rgb(255, 255, 255)',
                    'rgb(255, 255, 255)',
                    'rgb(255, 255, 255)',
                    'rgb(255, 255, 255)',
                    'rgb(255, 255, 255)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                }
            },
            scales: {
                display: false
            }
        }
    });
    /*
            // Time filter functionality
            document.getElementById('timeFilter').addEventListener('change', function() {
            const selectedValue = this.value;
            // Here you would typically make an AJAX call to filter data
            // For now, we'll just log the selection
            console.log('Filtering by:', selectedValue);
            
            // In a real implementation, you would:
            // 1. Make an AJAX request to your PHP backend
            // 2. Pass the selected time period
            // 3. Update the table and chart with filtered data
        });
        */
</script>