<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

// Database connection
include 'connect.php';

$sql = "SELECT * FROM products_table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $data = [];
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
} else {
    echo "No data found";
    exit;
}

$conn->close();

if (isset($data)) {
    // Define the filename with current date and time
    $filename = "data_export_" . date('Ymd') . ".xls";
    
    // Set headers for download
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    
    // Start output buffering to capture HTML table
    ob_start();
    echo '<table border="1">';
    echo '<tr>';
    echo '<th>ProductID</th>';
    echo '<th>Product Name</th>';
    echo '<th>Code</th>';
    echo '<th>Product Price</th>';
    echo '<th>Product Cost</th>';
    echo '<th>Stock</th>';
    echo '</tr>';
    
    // Write data to table
    foreach ($data as $row) {
        echo '<tr>';
        echo '<td>' . $row['product_id'] . '</td>';
        echo '<td>' . $row['pr_Name'] . '</td>';
        echo '<td>'.$row['product_number'].'</td>';
        echo '<td>' . $row['pr_Price'] . '</td>';
        echo '<td>' . $row['pr_Cost'] . '</td>';
        echo '<td>' . $row['qty_Onhand'] . '</td>';
        echo '</tr>';
    }
    
    echo '</table>';
    
    // Capture output and clean buffer
    $output = ob_get_clean();
    echo $output;
}
?>
