<?php
require_once '../../../config/database.php';
require_once '../../../config/auth.php';
require_once '../../../includes/header.php';
require_once '../../../includes/sidebar.php';
requireRole(['admin', 'super_admin']);

$db = getDB();

$limit = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $limit;
$search = isset($_GET['search']) ? $_GET['search'] : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';

$allowed_sort = ['id', 'name', 'price', 'compatibility', 'age', 'socket_name', 'ram_type_name', 'has_nvme'];
$allowed_order = ['ASC', 'DESC'];

$sort = in_array($sort, $allowed_sort) ? $sort : 'id';
$order = in_array($order, $allowed_order) ? $order : 'DESC';

if (!empty($search)) {
    $motherboards = $db->query("
        SELECT 
            m.*,
            s.name as socket_name,
            s.manufacturer as socket_manufacturer,
            r.name as ram_type_name,
            ms.has_nvme,
            ms.max_ram_size,
            ms.max_ram_slots
        FROM motherboards m
        LEFT JOIN motherboard_supports ms ON ms.motherboard_id = m.id
        LEFT JOIN socket_types s ON s.id = ms.socket_id
        LEFT JOIN ram_types r ON r.id = ms.ram_type_id
        WHERE m.name LIKE '%$search%'
        ORDER BY " . ($sort == 'socket_name' ? 's.name' : ($sort == 'ram_type_name' ? 'r.name' : ($sort == 'has_nvme' ? 'ms.has_nvme' : 'm.' . $sort))) . " $order
        LIMIT $start, $limit    
    ")->fetchAll();
    
    $total_data = $db->query("
        SELECT COUNT(*) AS total 
        FROM motherboards m
        WHERE m.name LIKE '%$search%'
    ")->fetch()['total'];
} else {
    $motherboards = $db->query("
        SELECT 
            m.*,
            s.name as socket_name,
            s.manufacturer as socket_manufacturer,
            r.name as ram_type_name,
            ms.has_nvme,
            ms.max_ram_size,
            ms.max_ram_slots
        FROM motherboards m
        LEFT JOIN motherboard_supports ms ON ms.motherboard_id = m.id
        LEFT JOIN socket_types s ON s.id = ms.socket_id
        LEFT JOIN ram_types r ON r.id = ms.ram_type_id
        ORDER BY " . ($sort == 'socket_name' ? 's.name' : ($sort == 'ram_type_name' ? 'r.name' : ($sort == 'has_nvme' ? 'ms.has_nvme' : 'm.' . $sort))) . " $order
        LIMIT $start, $limit
    ")->fetchAll();
    
    $total_data = $db->query("SELECT COUNT(*) AS total FROM motherboards")->fetch()['total'];
}

$total_pages = ceil($total_data / $limit);
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Data Motherboard</h1>
                </div>
            </div>
        </div>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">Daftar Motherboard</h3>
                    <div class="card-tools">
                        <a href="add.php" class="btn btn-primary btn-sm">
                            <i class="fas fa-plus"></i> Tambah Motherboard
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <?php 
                            echo $_SESSION['success'];
                            unset($_SESSION['success']);
                            ?>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            <?php 
                            echo $_SESSION['error'];
                            unset($_SESSION['error']);
                            ?>
                        </div>
                    <?php endif; ?>

                    <form action="" method="GET">
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" placeholder="Cari Motherboard" name="search" value="<?php echo $search; ?>">
                            <div class="input-group-append">
                                <button class="btn btn-primary" type="submit">Cari</button>
                            </div>
                        </div>
                    </form>

                    <table class="table table-bordered table-striped table-hover">
                        <thead>
                            <tr>
                                <th width="5%">
                                    <a href="?sort=id&order=<?php echo $sort == 'id' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        No. <?php echo $sort == 'id' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="?sort=name&order=<?php echo $sort == 'name' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        Nama Motherboard <?php echo $sort == 'name' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="?sort=socket_name&order=<?php echo $sort == 'socket_name' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        Socket <?php echo $sort == 'socket_name' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="?sort=ram_type_name&order=<?php echo $sort == 'ram_type_name' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        RAM Support <?php echo $sort == 'ram_type_name' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th>
    <a href="?sort=has_nvme&order=<?php echo $sort == 'has_nvme' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
        Storage <?php echo $sort == 'has_nvme' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
    </a>
</th>
                                <th>
                                    <a href="?sort=price&order=<?php echo $sort == 'price' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        Harga <?php echo $sort == 'price' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="?sort=compatibility&order=<?php echo $sort == 'compatibility' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        Compatibility <?php echo $sort == 'compatibility' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th>
                                    <a href="?sort=age&order=<?php echo $sort == 'age' && $order == 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo $search; ?>&page=<?php echo $page; ?>">
                                        Age <?php echo $sort == 'age' ? '<i class="fas fa-sort-' . strtolower($order) . '"></i>' : ''; ?>
                                    </a>
                                </th>
                                <th width="15%">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($motherboards as $index => $mobo): ?>
                            <tr>
                                <td><?php echo ($limit * ($page - 1)) + $index + 1; ?></td>
                                <td><?php echo htmlspecialchars($mobo['name']); ?></td>
                                <td>
                                    <?php if ($mobo['socket_name']): ?>
                                        <?php echo htmlspecialchars($mobo['socket_name']) . 
                                              ' (' . htmlspecialchars($mobo['socket_manufacturer']) . ')'; ?>
                                    <?php else: ?>
                                        <span class="badge badge-warning">No Socket</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($mobo['ram_type_name']): ?>
                                        <?php echo htmlspecialchars($mobo['ram_type_name']); ?><br>
                                        <small>
                                            Max: <?php echo htmlspecialchars($mobo['max_ram_size']); ?>GB 
                                            (<?php echo htmlspecialchars($mobo['max_ram_slots']); ?> slots)
                                        </small>
                                    <?php else: ?>
                                        <span class="badge badge-warning">No RAM Info</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($mobo['has_nvme']): ?>
                                        <span class="badge badge-success">NVMe Support</span>
                                    <?php else: ?>
                                        <span class="badge badge-secondary">SATA Only</span>
                                    <?php endif; ?>
                                </td>
                                <td>Rp <?php echo number_format($mobo['price'], 0, ',', '.'); ?></td>
                                <td>
                                    <div class="progress">
                                        <?php
                                        $compatibility = $mobo['compatibility'];
                                        $compatibilityClass = '';
                                        if ($compatibility >= 7) {
                                            $compatibilityClass = 'bg-success';
                                        } elseif ($compatibility >= 4) {
                                            $compatibilityClass = 'bg-primary';
                                        } else {
                                            $compatibilityClass = 'bg-warning';
                                        }
                                        ?>
                                        <div class="progress-bar <?php echo $compatibilityClass; ?>" 
                                             role="progressbar" 
                                             style="width: <?php echo ($compatibility * 10); ?>%">
                                            <?php echo $compatibility; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="progress">
                                        <?php
                                        $age = $mobo['age'];
                                        $ageClass = '';
                                        if ($age <= 1) {
                                            $ageClass = 'bg-success';
                                        } elseif ($age <= 3) {
                                            $ageClass = 'bg-warning';
                                        } else {
                                            $ageClass = 'bg-danger';
                                        }
                                        ?>
                                        <div class="progress-bar <?php echo $ageClass; ?>" 
                                             role="progressbar" 
                                             style="width: <?php echo ($age * 20); ?>%">
                                            <?php echo $age; ?>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center">
                                    <a href="edit.php?id=<?php echo $mobo['id']; ?>" 
                                       class="btn btn-info btn-sm" 
                                       data-toggle="tooltip" 
                                       title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="delete.php?id=<?php echo $mobo['id']; ?>" 
                                       class="btn btn-danger btn-sm" 
                                       onclick="return confirm('Apakah Anda yakin ingin menghapus motherboard ini?');"
                                       data-toggle="tooltip" 
                                       title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php if ($page > 1): ?>
                                <li class="page-item"><a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo $search; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">Previous</a></li>
                            <?php endif; ?>

                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>"><a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo $search; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>"><?php echo $i; ?></a></li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item"><a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo $search; ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">Next</a></li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </section>
</div>

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

<script>
$(function () {
    $('[data-toggle="tooltip"]').tooltip();
});
</script>