<?php
// CRITICAL: Must be the very first line
session_start();

// PHP code to display products from the database

$servername = "localhost";
$username = "wintelsoft_vinod";
$password = "vinodbhaskar69*";
$dbname = "wintelsoft_svf";

// --- START: USER RIGHTS CHECK ---

// Get the user rights from the session set during login
$current_user_id = $_SESSION['user_id'] ?? 0;
$user_rights = $_SESSION['user_rights'] ?? 'Guest';

// Check if the current user has 'Super_user' rights (case-insensitive check)
$is_super_user = (strtolower($user_rights) === 'super_user');

// --- END: USER RIGHTS CHECK ---
// --------------------------------------------------------------------------------

// Establish connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Handle delete action
if (isset($_GET['delete_id'])) {
    if ($is_super_user) {
        $id = (int)$_GET['delete_id'];
        $sql_delete = "DELETE FROM products WHERE id = '$id'"; 
        if ($conn->query($sql_delete) === TRUE) {
            header("Location: view_products.php");
            exit();
        } else {
            echo "Error deleting record: " . $conn->error;
        }
    } else {
        echo "<script>alert('Permission denied. Only Super users can delete records.'); window.location.href='view_products.php';</script>";
        exit();
    }
}

// Handle filtering and sorting (unchanged)
$filter_status = isset($_GET['status']) ? $_GET['status'] : 'all';
$sql_filter = "SELECT * FROM products";
if ($filter_status == 'Yes') {
    $sql_filter .= " WHERE despatched_status = 'Yes'";
} elseif ($filter_status == 'No') {
    $sql_filter .= " WHERE despatched_status = 'No'";
}
$sql_filter .= " ORDER BY product_code ASC"; 

$result = $conn->query($sql_filter);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Products</title>
    <style>
        /* (Your CSS styles here) */
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
        
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f0f2f5;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 40px auto;
            background-color: #ffffff;
            padding: 40px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            overflow-x: auto;
        }

        h2 {
            text-align: center;
            color: #ffffff;
            background-color: #3498db;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            font-weight: 700;
            letter-spacing: 1px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            min-width: 1300px; 
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #34495e;
            color: white;
            font-weight: bold;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        tr:hover {
            background-color: #e9e9e9;
        }

        .action-links a {
            color: #3498db;
            text-decoration: none;
            margin-right: 5px;
            font-weight: bold;
        }
        
        .action-links a.delete-link {
            color: #e74c3c;
        }
        
        .action-links span.delete-placeholder {
            color: #aaa;
            margin-left: 5px;
            margin-right: 10px;
        }

        .action-links a:hover {
            text-decoration: underline;
        }

        .add-link-container {
            text-align: center;
            margin-bottom: 20px;
        }

        .add-link-container a {
            background-color: #2ecc71;
            color: white;
            padding: 12px 25px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: bold;
            transition: background-color 0.3s, transform 0.2s;
        }

        .add-link-container a:hover {
            background-color: #27ae60;
            transform: translateY(-2px);
        }

        .product-image {
            max-width: 100px;
            height: auto;
            border-radius: 4px;
            cursor: pointer; 
            transition: transform 0.2s;
        }

        .product-image:hover {
            transform: scale(1.05);
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            padding-top: 50px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.9);
        }

        .modal-content {
            margin: auto;
            display: block;
            width: 80%;
            max-width: 700px;
        }

        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            transition: 0.3s;
        }

        .close:hover,
        .close:focus {
            color: #bbb;
            text-decoration: none;
            cursor: pointer;
        }

    </style>
</head>
<body>
    <div class="container">
        <p style="text-align: right; font-weight: bold;">Logged in as: <?php echo htmlspecialchars($user_rights); ?> (ID: <?php echo htmlspecialchars($current_user_id); ?>)</p>
        
        <h2>View Products</h2>

        <div class="filter-container">
            <form method="get" action="view_products.php">
                <label for="status">Filter by Despatch Status:</label>
                <select name="status" id="status" onchange="this.form.submit()">
                    <option value="all" <?php echo ($filter_status == 'all') ? 'selected' : ''; ?>>All</option>
                    <option value="Yes" <?php echo ($filter_status == 'Yes') ? 'selected' : ''; ?>>Yes</option>
                    <option value="No" <?php echo ($filter_status == 'No') ? 'selected' : ''; ?>>No</option>
                </select>
            </form>
        </div>

        <div class="add-link-container">
            <a href="add.php">Add New Product</a>
        </div>
        <a href="login.php">Log In</a> | <a href="logout.php">Log Out</a> 

        <table>
            <thead>
                <tr>
                    <th>User ID</th>
                    <th>Product Code</th>
                    <th>Date of Order</th>
                    <th>Scheduled Date of Delivery</th>
                    <th>Product Image 1</th>
                    <th>Product Image 2</th>
                    <th>Product Image 3</th>
                    <th>Despatched Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($result->num_rows > 0) {
                    while($row = $result->fetch_assoc()) {
                        
                        $scheduled_date = !empty($row["scheduled_date_of_delivery"]) ? date('d/m/Y', strtotime($row["scheduled_date_of_delivery"])) : '';
                        
                        echo "<tr>";
                        echo "<td>" . htmlspecialchars($row["user_id"]) . "</td>";
                        echo "<td>" . htmlspecialchars($row["product_code"]) . "</td>";
                        echo "<td>" . date('d/m/Y', strtotime($row["date_of_order"])) . "</td>";
                        // ... other data rows ...
                        echo "<td>" . htmlspecialchars($row["customer_name"]) . "</td>";
                        echo "<td>" . nl2br(htmlspecialchars($row["address"])) . "</td>";
                        echo "<td>" . htmlspecialchars($row["mobile_no"]) . "</td>";
                        echo "<td>" . htmlspecialchars($row["item_description"]) . "</td>";
                        echo "<td>" . htmlspecialchars($row["measurements_and_specification"]) . "</td>";
                        echo "<td>" . htmlspecialchars($row["type_of_wood"]) . "</td>";
                        echo "<td>" . htmlspecialchars($row["quantity"]) . "</td>";
                        echo "<td>" . htmlspecialchars($scheduled_date) . "</td>";
                        
                        // Image display (shortened for clarity)
                        echo "<td>" . (!empty($row["product_image"]) ? "<img src='uploads/" . htmlspecialchars($row["product_image"]) . "' alt='Image 1' class='product-image' onclick='openModal(this.src)'>" : "No Image") . "</td>";
                        echo "<td>" . (!empty($row["product_image2"]) ? "<img src='uploads/" . htmlspecialchars($row["product_image2"]) . "' alt='Image 2' class='product-image' onclick='openModal(this.src)'>" : "No Image") . "</td>";
                        echo "<td>" . (!empty($row["product_image3"]) ? "<img src='uploads/" . htmlspecialchars($row["product_image3"]) . "' alt='Image 3' class='product-image' onclick='openModal(this.src)'>" : "No Image") . "</td>";
                        
                        echo "<td>" . htmlspecialchars($row["despatched_status"]) . "</td>";
                        
                        // --- CONDITIONAL DELETE OPTION ---
                        echo "<td class='action-links'>";
                        echo "<a href='edit_product.php?id=" . htmlspecialchars($row["id"]) . "'>Edit</a>";
                        
                        if ($is_super_user) {
                            echo " | <a href='view_products.php?delete_id=" . htmlspecialchars($row["id"]) . "' onclick='return confirm(\"Are you sure you want to delete this product?\");' class='delete-link'>Delete</a>";
                        } else {
                            echo " | <span class='delete-placeholder'>Delete</span>";
                        }
                        echo "</td>";
                        // --- END CONDITIONAL DELETE OPTION ---
                        
                        echo "</tr>";
                    }
                } else {
                    echo "<tr><td colspan='16'>No products found.</td></tr>";
                }
                $conn->close();
                ?>
            </tbody>
        </table>
    </div>

    <div id="imageModal" class="modal" onclick="closeModal()">
        <span class="close">&times;</span>
        <img class="modal-content" id="modalImage">
    </div>

    <script>
        function openModal(imgSrc) {
            var modal = document.getElementById("imageModal");
            var modalImg = document.getElementById("modalImage");
            modal.style.display = "block";
            modalImg.src = imgSrc;
        }

        function closeModal() {
            var modal = document.getElementById("imageModal");
            modal.style.display = "none";
        }
    </script>
</body>
</html>