<?php
// CRITICAL: Must be the absolute first line before any output
session_start();

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

// --- START: SESSION AND USER RIGHTS VALIDATION ---

// 1. Check if the user is logged in at all
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$current_user_id = $_SESSION['user_id'];
$user_rights = 'Guest';
$is_super_user = false;

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

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

// 2. Fetch User Rights from the 'users' table using the session user_id
// This is required to determine edit/delete permissions based on user role.
$stmt_rights = $conn->prepare("SELECT user_rights FROM users WHERE user_id = ?");

if ($stmt_rights) {
    $stmt_rights->bind_param("s", $current_user_id);
    $stmt_rights->execute();
    $result_rights = $stmt_rights->get_result();

    if ($result_rights->num_rows === 1) {
        $row_rights = $result_rights->fetch_assoc();
        $user_rights = trim($row_rights['user_rights']);
        $is_super_user = (strtolower($user_rights) === 'super_user');
    }
    $stmt_rights->close();
}
// --- END: SESSION AND USER RIGHTS VALIDATION ---
// --------------------------------------------------------------------------------

// --- START: FILTER PARAMETER HANDLING ---

// user_filter now holds the salesman name string
$user_filter = $_GET['user_filter'] ?? 'all'; 
$start_date = $_GET['start_date'] ?? null;
$end_date = $_GET['end_date'] ?? null;
$filter_status = $_GET['status'] ?? 'all'; // Status filter is kept for continuity

// Build the dynamic WHERE clause and parameters for the prepared statement
$where_clauses = [];
$param_types = '';
$param_values = [];

// 1. Salesman Filter (p.salesman is the column name in products)
if ($user_filter !== 'all' && !empty($user_filter)) {
    // MODIFIED: Filter condition now uses the 'salesman' column directly
    $where_clauses[] = "p.salesman = ?";
    $param_types .= 's';
    $param_values[] = $user_filter;
}

// 2. Despatch Status Filter
if ($filter_status == 'Yes') {
    $where_clauses[] = "p.despatched_status = 'Yes'";
} elseif ($filter_status == 'No') {
    $where_clauses[] = "p.despatched_status = 'No'";
}

// 3. Date Range Filter (scheduled_date_of_delivery)
if (!empty($start_date) && !empty($end_date)) {
    $where_clauses[] = "p.scheduled_date_of_delivery BETWEEN ? AND ?";
    $param_types .= 'ss';
    $param_values[] = $start_date;
    $param_values[] = $end_date;
}

// Construct the full query (No JOIN required, as salesman name is in the products table)
$sql_base = "
    SELECT p.*
    FROM products p
";
if (!empty($where_clauses)) {
    $sql_base .= " WHERE " . implode(' AND ', $where_clauses);
}
$sql_base .= " ORDER BY p.product_code ASC"; 

// --- END: FILTER PARAMETER HANDLING ---
// --------------------------------------------------------------------------------

// Handle delete action (Security check remains $is_super_user)
if (isset($_GET['delete_id'])) {
    if ($is_super_user) {
        // NOTE: The DELETE operation is only on the products table
        $stmt_delete = $conn->prepare("DELETE FROM products WHERE id = ?");
        $stmt_delete->bind_param("i", $_GET['delete_id']);

        if ($stmt_delete->execute()) {
            $stmt_delete->close();
            // Re-use current filters for redirection to maintain context
            $redirect_url = "view_products_selected.php?user_filter=" . urlencode($user_filter) . "&start_date=" . urlencode($start_date) . "&end_date=" . urlencode($end_date) . "&status=" . urlencode($filter_status);
            $conn->close();
            header("Location: " . $redirect_url);
            exit();
        } else {
            // Error handling
            echo "<script>console.error('Error deleting record: " . $stmt_delete->error . "');</script>";
        }
    } else {
        echo "<script>alert('Permission denied. Only Super users can delete records.'); window.location.href='view_products_selected.php';</script>";
        $conn->close();
        exit();
    }
}

// Execute the main data query using prepared statement
$result = false;
$stmt_main = $conn->prepare($sql_base);

if ($stmt_main) {
    if (!empty($param_values)) {
        // Use call_user_func_array to bind parameters dynamically
        $stmt_main->bind_param($param_types, ...$param_values);
    }
    $stmt_main->execute();
    $result = $stmt_main->get_result();
    $stmt_main->close();
} else {
    // Error handling for the main query preparation
    echo "<script>console.error('Error preparing query: " . $conn->error . "');</script>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Filtered Products</title>
    <style>
        @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;
        }
        
        .filter-container {
            background-color: #ecf0f1;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        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;
        }

        .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">
        
        <h2>Filtered Product List</h2>
        
        <!-- Inline Status Filter and Action Buttons -->
        <div class="filter-container">
            <form method="get" action="view_products_selected.php">
                <!-- Hidden fields to maintain Salesman and Date filters when changing Status -->
                <input type="hidden" name="user_filter" value="<?php echo htmlspecialchars($user_filter); ?>">
                <input type="hidden" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                <input type="hidden" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">

                <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 class="add-link-container" style="margin: 0;">
                <a href="add.php">Add New Product</a>
            </div>
        </div>
        
        
        <table>
            <thead>
                <tr>
                    <th>Product Code</th>
                    <th>Date of Order</th>
                    <th>Customer Name</th>
                    <th>Address</th>
                    <th>Mobile No</th>
                    <th>Item Description</th>
                    <th>Measurements & Specification</th>
                    <th>Type of Wood</th>
                    <th>Quantity</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>Salesman</th> 
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($result && $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["product_code"]) . "</td>";
                        echo "<td>" . date('d/m/Y', strtotime($row["date_of_order"])) . "</td>";
                        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 
                        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>";
                        
                        // Display salesman name directly from the 'salesman' column
                        echo "<td>" . htmlspecialchars($row["salesman"]) . "</td>";
                        
                        // --- CONDITIONAL DELETE OPTION (Actions) ---
                        echo "<td class='action-links'>";
                        // The Edit link must also pass the current filters back so that the user returns to the filtered list
                        $edit_url_params = http_build_query([
                            'id' => $row["id"],
                            'user_filter' => $user_filter,
                            'start_date' => $start_date,
                            'end_date' => $end_date,
                            'status' => $filter_status
                        ]);
                        echo "<a href='edit_product.php?" . $edit_url_params . "'>Edit</a>";
                        
                        if ($is_super_user) {
                            // Delete link is enabled for Super_users
                            echo " | <a href='view_products_selected.php?delete_id=" . htmlspecialchars($row["id"]) . "&user_filter=" . urlencode($user_filter) . "&start_date=" . urlencode($start_date) . "&end_date=" . urlencode($end_date) . "&status=" . urlencode($filter_status) . "' onclick='return confirm(\"Are you sure you want to delete this product?\");' class='delete-link'>Delete</a>";
                        } else {
                            // Placeholder is shown for non-Super_users
                            echo " | <span class='delete-placeholder'>Delete</span>";
                        }
                        echo "</td>";
                        // --- END CONDITIONAL DELETE OPTION ---
                        
                        echo "</tr>";
                    }
                } else {
                    echo "<tr><td colspan='16'>No products found matching the selected criteria.</td></tr>";
                }
                // Close connection at the very end
                if (isset($conn)) {
                    $conn->close();
                }
                ?>
            </tbody>
        </table>
    </div>

    <!-- The Modal for image zoom -->
    <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>
