<?php
session_start();
include 'shikanisha.kts.php'; // Include your database connection script

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'request') {
    // Ensure session data exists
    if (!isset($_SESSION['request']) || empty($_SESSION['request'])) {
        echo json_encode([
            'success' => false,
            'message' => 'No items in the request session.'
        ]);
        exit;
    }

    $request_by = $_SESSION['type']; // User type from session
    $date = date('Y-m-d H:i:s');
    $status = 'pending';

    // Prepare to insert into `requests` table
    $sql = "INSERT INTO `requests`(`request_by`, `date`, `status`) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        echo json_encode([
            'success' => false,
            'message' => 'Request prepare failed: ' . $conn->error
        ]);
        exit;
    }

    $stmt->bind_param("sss", $request_by, $date, $status);

    if ($stmt->execute()) {
        $request_id = $stmt->insert_id;

        // Prepare `request_items` insert
        $insert_values = [];
        foreach ($_SESSION['request'] as $item) {
            // Sanitize and validate data
            $name = $conn->real_escape_string($item['name']);
            $quantity = intval($item['quantity']);
            $category = $conn->real_escape_string($item['category']);
            $insert_values[] = "('$name', $quantity, '$category', $request_id)";
        }

        $sql = "INSERT INTO `request_items` (`product_name`, `quantity`, `category`, `request_id`) VALUES " . implode(', ', $insert_values);
        if ($conn->query($sql) === TRUE) {
            // Clear the request session data after successful insertion
            unset($_SESSION['request']);

            $response = [
                'success' => true,
                'message' => 'Request submitted successfully!'
            ];
        } else {
            $response = [
                'success' => false,
                'message' => 'Error inserting request items: ' . $conn->error
            ];
        }
    } else {
        $response = [
            'success' => false,
            'message' => 'Error inserting request: ' . $stmt->error
        ];
    }

    $stmt->close();
    $conn->close();

    // Send JSON response
    echo json_encode($response);
    exit;
}
?>
