<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

require "conexion.php";

if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
}
$profileData = array();
$productData = array();
$username = isset($_GET["username"]) ? $_GET["username"] : null;
$category = isset($_GET["category"]) ? $_GET["category"] : null;
if ($username) {
    $profileData = array();
    $profileQuery = "SELECT 
        username,
        email,
        point
    FROM 
        users
    WHERE 
        username LIKE ?;";

    $stmt = $connect->prepare($profileQuery);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $profileResult = $stmt->get_result();

    if ($profileResult) {
        if ($profileResult->num_rows == 1) {

            while ($row = $profileResult->fetch_assoc()) {
                $profileData[] = $row;
            }
        }
    } else {
        $profileData = [];
        echo json_encode(["error" => "Query error: " . $connect->error]);
        exit;
    }
}

$filter = '';
if ($category) {
    if ($category != 'all') $filter = "AND category_id = ?";

    $productQuery = "SELECT 
        product_id, 
        product_name,
        product_description,
        category_id,
        image_url,
        quantity,
        price
    FROM 
        products
    WHERE
        quantity > 0 $filter";

    $stmt = $connect->prepare($productQuery);
    if ($category != 'all')
        $stmt->bind_param("s", $category);
    $stmt->execute();
    $productResult = $stmt->get_result();

    if ($productResult) {
        if ($productResult->num_rows > 0) {

            while ($row = $productResult->fetch_assoc()) {
                $productData[] = $row;
            }
        }
    } else {
        $productData = [];
        echo json_encode(["error" => "Query error: " . $connect->error]);
        exit;
    }
}

$initData = ['profileData' => $profileData, 'productData' => $productData];
$array = [
    'initData' => $initData,
];


echo json_encode($array);


// $insideReportData = [
//     "minQty" => $minQtyData,
//     "maxQty" => $maxQtyData,
//     "categoryFilter" => $categoryData,
//     "productName" => $productNameData
// ];