<?php
ob_start();
include 'includes.php';
include 'connection.php';
session_start();

if (!isset($_SESSION['admin'])) {
    header('Location: index.php');
    exit;
}

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// 1. Bulk Delete Logic
if (isset($_POST['bulk_delete']) && isset($_POST['selected_items']) && !empty($_POST['selected_items'])) {
    $selectedIds = $_POST['selected_items'];
    foreach ($selectedIds as $id) {
        $id = (int)$id;
        // Fetch image to delete from folder
        $res = $conn->query("SELECT image FROM products WHERE id=$id");
        if ($res->num_rows > 0) {
            $row = $res->fetch_assoc();
            if (file_exists("../" . $row['image'])) {
                unlink("../" . $row['image']);
            }
        }
        // Delete from database
        $conn->query("DELETE FROM products WHERE id=$id");
    }
    header("Location: manage_products.php?page=" . $page);
    exit;
}

// Single Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $res = $conn->query("SELECT image FROM products WHERE id=$id");
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        if (file_exists("../" . $row['image'])) unlink("../" . $row['image']);
    }
    $conn->query("DELETE FROM products WHERE id=$id");
    header("Location: manage_products.php?page=" . ($page));
    exit;
}

// Toggle Status
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $conn->query("UPDATE products SET status = 1-status WHERE id=$id");
    header("Location: manage_products.php?page=" . ($page));
    exit;
}

// Add/Edit Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['bulk_delete'])) {
    $category_id = (int)$_POST['category_id'];
    $title = $conn->real_escape_string($_POST['title']);
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title), '-'));
    $description = $conn->real_escape_string($_POST['description']);

    $targetDir = "../assets/products/";
    if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);

    if (isset($_POST['edit_id']) && !empty($_POST['edit_id'])) {
        $id = (int)$_POST['edit_id'];
        $image_sql = '';
        if (!empty($_FILES['image']['name'])) {
            $fileName = time() . "_" . basename($_FILES['image']['name']);
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $fileName)) {
                $image_sql = ", image='assets/products/$fileName'";
                $old = $conn->query("SELECT image FROM products WHERE id=$id")->fetch_assoc();
                if ($old && file_exists("../" . $old['image'])) unlink("../" . $old['image']);
            }
        }
        $conn->query("UPDATE products SET category_id=$category_id, title='$title', slug='$slug', description='$description' $image_sql WHERE id=$id");
    } else {
        $imagePath = "";
        if (!empty($_FILES['image']['name'])) {
            $fileName = time() . "_" . basename($_FILES['image']['name']);
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $fileName)) $imagePath = "assets/products/$fileName";
        }
        $conn->query("INSERT INTO products (category_id, title, slug, image, description, status) VALUES ($category_id, '$title', '$slug', '$imagePath', '$description', 1)");
    }
    header("Location: manage_products.php");
    exit;
}

// Fetch Data
$result = $conn->query("SELECT p.*, pc.name as cat_name FROM products p LEFT JOIN product_categories pc ON p.category_id = pc.id ORDER BY p.id DESC LIMIT $per_page OFFSET $offset");
$total = $conn->query("SELECT COUNT(*) as total FROM products")->fetch_assoc()['total'];
$total_pages = ceil($total / $per_page);
$categories = $conn->query("SELECT id, name FROM product_categories WHERE status=1");
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Manage Products</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <style>
        body {
            background-image: url('../assets/images/footer-bg.png');
            background-position: center;
            background-size: cover;
            font-family: sans-serif;
            margin: 0;
            padding: 0;
        }

        .spac-content {
            padding: 15px;
            min-height: 100vh;
            background-image: url('../assets/images/footer-bg.png');
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
        }

        .spac-management-container {
            max-width: 1200px;
            margin: auto;
        }

        .spac-management-title {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: white;
        }

        .spac-upload-form {
            background: rgba(255, 255, 255, 0.9);
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .spac-upload-btn {
            padding: 8px 15px;
            background: brown;
            color: #fff;
            border: 1px solid white;
            border-radius: 4px;
            cursor: pointer;
        }

        .spac-bulk-btn {
            padding: 8px 15px;
            background: #dc3545;
            color: #fff;
            border: 1px solid #dc3545;
            border-radius: 4px;
            cursor: pointer;
        }

        .spac-table-container {
            overflow-x: auto;
        }

        .spac-management-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
            background: white;
        }

        .spac-management-table th {
            background: brown;
            color: white;
            padding: 10px 6px;
            text-align: left;
        }

        .spac-management-table td {
            padding: 10px 6px;
            border-bottom: 1px solid #eee;
            color: brown;
            vertical-align: middle;
        }

        /* Checkbox styling */
        .checkbox-item {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

        .spac-btn {
            width: 28px;
            height: 28px;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            text-decoration: none;
            margin-right: 5px;
            border: none;
            cursor: pointer;
        }

        .spac-toggle-btn {
            background-color: #17a2b8;
        }

        .spac-delete-btn {
            background-color: #dc3545;
        }

        .spac-edit-btn {
            background-color: #ffc107;
            color: #212529;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }

        .pagination a,
        .pagination span {
            padding: 8px 12px;
            background: white;
            color: brown;
            text-decoration: none;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        .pagination a:hover {
            background: brown;
            color: white;
        }

        .pagination .current {
            background: brown;
            color: white;
            font-weight: bold;
        }

        /* Modal Styles - Small & Scrollable */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            /* Prevent body scroll */
            background-color: rgba(0, 0, 0, 0.6);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            /* 5% from top */
            padding: 20px;
            border: 1px solid #888;
            width: 90%;
            max-width: 600px;
            /* Smaller width */
            height: 70vh;
            /* Fixed height */
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 1.1rem;
            color: brown;
        }

        .modal-body {
            overflow-y: auto;
            /* Scrollbar inside modal */
            flex-grow: 1;
            padding-right: 10px;
            /* Space for scrollbar */
        }

        .close {
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: #aaa;
        }

        .close:hover {
            color: black;
        }

        .form-group {
            margin-bottom: 12px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            font-size: 0.9rem;
        }

        .form-control {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 0.85rem;
        }

        /* Scrollbar styling */
        .modal-body::-webkit-scrollbar {
            width: 6px;
        }

        .modal-body::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .modal-body::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 3px;
        }
    </style>
</head>

<body>
    <div class="spac-content">
        <div class="spac-management-container">
            <h1 class="spac-management-title">Manage Products</h1>

            <!-- Top Bar with Add and Bulk Delete -->
            <form method="POST" id="bulkForm" onsubmit="return confirm('Are you sure you want to delete selected items?')">
                <input type="hidden" name="bulk_delete" value="1">
                <div class="spac-upload-form">
                    <button type="button" class="spac-upload-btn" onclick="openModal()"><i class="fas fa-plus"></i> Add Product</button>

                    <button type="submit" class="spac-bulk-btn" id="bulkDeleteBtn" style="display:none;">
                        <i class="fas fa-trash-alt"></i> Delete Selected
                    </button>
                </div>

                <div class="spac-table-container">
                    <table class="spac-management-table">
                        <thead>
                            <tr>
                                <th style="width: 30px;">
                                    <input type="checkbox" id="selectAll" class="checkbox-item">
                                </th>
                                <th>S.No</th>
                                <th>Image</th>
                                <th>Product Name</th>
                                <th>Category</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = $offset + 1;
                            while ($row = $result->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <input type="checkbox" name="selected_items[]" value="<?= $row['id'] ?>" class="checkbox-item item-checkbox">
                                    </td>
                                    <td><?= $i++ ?></td>
                                    <td><img src="../<?= $row['image'] ?>" width="50" onerror="this.src='https://via.placeholder.com/50'"></td>
                                    <td><?= htmlspecialchars($row['title']) ?></td>
                                    <td><?= htmlspecialchars($row['cat_name']) ?></td>
                                    <td>
                                        <span style="padding:3px 8px; border-radius:12px; font-size:0.75rem; background:<?= $row['status'] ? '#d4edda;color:#155724' : '#fff3cd;color:#856404' ?>">
                                            <?= $row['status'] ? 'Active' : 'Inactive' ?>
                                        </span>
                                    </td>
                                    <td>
                                        <button type="button" class="spac-btn spac-edit-btn" onclick='edit(<?= json_encode($row) ?>)'><i class="fas fa-edit"></i></button>
                                        <a href="?page=<?= $page ?>&toggle=<?= $row['id'] ?>" class="spac-btn spac-toggle-btn"><i class="fas fa-retweet"></i></a>
                                        <a href="?page=<?= $page ?>&delete=<?= $row['id'] ?>" onclick="return confirm('Delete?')" class="spac-btn spac-delete-btn"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </form>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="pagination">
                    <?php if ($page > 1): ?>
                        <a href="?page=1">First</a>
                        <a href="?page=<?= $page - 1 ?>">Prev</a>
                    <?php else: ?>
                        <span class="disabled">First</span>
                        <span class="disabled">Prev</span>
                    <?php endif; ?>

                    <?php
                    $start_page = max(1, $page - 2);
                    $end_page = min($total_pages, $page + 2);
                    for ($p = $start_page; $p <= $end_page; $p++):
                    ?>
                        <?php if ($p == $page): ?>
                            <span class="current"><?= $p ?></span>
                        <?php else: ?>
                            <a href="?page=<?= $p ?>"><?= $p ?></a>
                        <?php endif; ?>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                        <a href="?page=<?= $page + 1 ?>">Next</a>
                        <a href="?page=<?= $total_pages ?>">Last</a>
                    <?php else: ?>
                        <span class="disabled">Next</span>
                        <span class="disabled">Last</span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
    </div><br><br><br><br>

    <!-- Modal -->
    <div id="myModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal-title">Add Product</h2>
                <span class="close" onclick="closeModal()">&times;</span>
            </div>

            <!-- Scrollable Body -->
            <div class="modal-body">
                <form method="POST" enctype="multipart/form-data" id="productForm">
                    <input type="hidden" name="edit_id" id="edit_id">

                    <div class="form-group">
                        <label>Category *</label>
                        <select name="category_id" id="category_id" class="form-control" required>
                            <option value="">Select Category</option>
                            <?php
                            // Reset pointer for dropdown
                            $categories->data_seek(0);
                            while ($cat = $categories->fetch_assoc()): ?>
                                <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Product Name *</label>
                        <input type="text" name="title" id="title" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Image</label>
                        <input type="file" name="image" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Description</label>
                        <textarea name="description" id="description" rows="3" class="form-control"></textarea>
                    </div>
                    <button type="submit" class="spac-upload-btn" style="width:100%; padding:10px;">Save Product</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        let editor;
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize CKEditor
            editor = CKEDITOR.replace('description');

            // Select All Logic
            document.getElementById('selectAll').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.item-checkbox');
                checkboxes.forEach(cb => cb.checked = this.checked);
                toggleBulkButton();
            });

            // Individual Checkbox Logic
            document.querySelectorAll('.item-checkbox').forEach(cb => {
                cb.addEventListener('change', toggleBulkButton);
            });
        });

        function toggleBulkButton() {
            const checked = document.querySelectorAll('.item-checkbox:checked').length;
            const btn = document.getElementById('bulkDeleteBtn');
            btn.style.display = checked > 0 ? 'inline-block' : 'none';
        }

        function openModal() {
            document.getElementById('modal-title').innerText = "Add Product";
            document.getElementById('productForm').reset();
            document.getElementById('edit_id').value = '';
            if (editor) editor.setData('');
            document.getElementById('myModal').style.display = 'block';
        }

        function edit(data) {
            document.getElementById('modal-title').innerText = "Edit Product";
            document.getElementById('edit_id').value = data.id;
            document.getElementById('category_id').value = data.category_id;
            document.getElementById('title').value = data.title;
            setTimeout(() => {
                if (editor) editor.setData(data.description || '');
            }, 200);
            document.getElementById('myModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('myModal').style.display = 'none';
        }

        window.onclick = function(event) {
            const modal = document.getElementById('myModal');
            if (event.target == modal) closeModal();
        }
    </script>
</body>

</html>
<?php ob_end_flush(); ?>