<?php
/**
 * Stock Request Management API
 * Handles admin stock requests and PM delivery confirmations
 */

header('Content-Type: application/json');
session_start();

// Include configuration
require_once 'config.php';

// Check authentication - accept admin user if session is active
$is_authenticated = !empty($_SESSION);
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : (isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 'admin');

if (!$is_authenticated || empty($user_id)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized - Please login first']);
    exit;
}

$action = $_GET['action'] ?? $_POST['action'] ?? null;
$method = $_SERVER['REQUEST_METHOD'];

try {
    // Create table if not exists
    createStockRequestsTable();

    switch ($action) {
        case 'create_request':
            if ($method !== 'POST') {
                throw new Exception('Invalid request method');
            }
            handleCreateRequest();
            break;

        case 'get_requests':
            if ($method !== 'GET') {
                throw new Exception('Invalid request method');
            }
            handleGetRequests();
            break;

        case 'fulfill_request':
            if ($method !== 'POST') {
                throw new Exception('Invalid request method');
            }
            handleFulfillRequest();
            break;

        case 'get_request_details':
            if ($method !== 'GET') {
                throw new Exception('Invalid request method');
            }
            handleGetRequestDetails();
            break;

        default:
            throw new Exception('Invalid action: ' . $action);
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Create stock_requests table if it doesn't exist
 */
function createStockRequestsTable() {
    global $conn;

    $sql = "CREATE TABLE IF NOT EXISTS stock_requests (
        id INT PRIMARY KEY AUTO_INCREMENT,
        ingredient_id INT NOT NULL,
        quantity_requested DECIMAL(10,2) NOT NULL,
        priority ENUM('low','medium','high') DEFAULT 'medium',
        notes TEXT,
        status ENUM('pending','fulfilled','cancelled') DEFAULT 'pending',
        requested_by VARCHAR(50) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        fulfilled_by VARCHAR(50),
        quantity_delivered DECIMAL(10,2),
        invoice_ref VARCHAR(100),
        fulfilled_at TIMESTAMP NULL,
        FOREIGN KEY (ingredient_id) REFERENCES ingredients(id) ON DELETE CASCADE,
        INDEX idx_status (status),
        INDEX idx_ingredient (ingredient_id),
        INDEX idx_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    if (!$conn->query($sql)) {
        throw new Exception('Database error: ' . $conn->error);
    }
}

/**
 * Create a new stock request (Admin initiates)
 */
function handleCreateRequest() {
    global $conn;

    $data = json_decode(file_get_contents('php://input'), true);

    // Validate input
    $ingredient_id = $data['ingredient_id'] ?? null;
    $quantity_requested = $data['quantity_requested'] ?? null;
    $priority = $data['priority'] ?? 'medium';
    $notes = $data['notes'] ?? '';
    $requested_by = $data['requested_by'] ?? 'admin';

    if (!$ingredient_id || !$quantity_requested || $quantity_requested <= 0) {
        throw new Exception('Invalid ingredient or quantity');
    }

    // Validate priority
    if (!in_array($priority, ['low', 'medium', 'high'])) {
        $priority = 'medium';
    }

    // Check if ingredient exists
    $stmt = $conn->prepare("SELECT id, name FROM ingredients WHERE id = ?");
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $ingredient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception('Ingredient not found');
    }

    $ingredient = $result->fetch_assoc();
    $stmt->close();

    // Insert new request
    $stmt = $conn->prepare(
        "INSERT INTO stock_requests 
        (ingredient_id, quantity_requested, priority, notes, requested_by, status) 
        VALUES (?, ?, ?, ?, ?, 'pending')"
    );

    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('idss', $ingredient_id, $quantity_requested, $priority, $notes);

    if (!$stmt->execute()) {
        throw new Exception('Failed to create request: ' . $stmt->error);
    }

    $request_id = $conn->insert_id;
    $stmt->close();

    // Log activity
    logActivity("admin_$requested_by", "create_stock_request", "Created stock request for " . $ingredient['name']);

    http_response_code(201);
    echo json_encode([
        'success' => true,
        'message' => 'Stock request created successfully',
        'request_id' => $request_id
    ]);
}

/**
 * Get pending stock requests (PM views)
 */
function handleGetRequests() {
    global $conn;

    // Fetch pending requests with ingredient details
    $sql = "SELECT 
                sr.id,
                sr.ingredient_id,
                sr.quantity_requested,
                sr.priority,
                sr.notes,
                sr.requested_by,
                sr.created_at,
                sr.status,
                i.name AS ingredient_name,
                i.unit,
                i.current_stock,
                i.minimum_stock
            FROM stock_requests sr
            JOIN ingredients i ON sr.ingredient_id = i.id
            WHERE sr.status = 'pending'
            ORDER BY 
                CASE sr.priority
                    WHEN 'high' THEN 1
                    WHEN 'medium' THEN 2
                    WHEN 'low' THEN 3
                END ASC,
                sr.created_at DESC";

    $result = $conn->query($sql);

    if (!$result) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $requests = [];
    while ($row = $result->fetch_assoc()) {
        $requests[] = $row;
    }

    echo json_encode([
        'success' => true,
        'requests' => $requests,
        'count' => count($requests)
    ]);
}

/**
 * Mark request as fulfilled (PM confirms delivery)
 */
function handleFulfillRequest() {
    global $conn;

    $data = json_decode(file_get_contents('php://input'), true);

    // Validate input
    $request_id = $data['request_id'] ?? null;
    $quantity_delivered = $data['quantity_delivered'] ?? null;
    $invoice_ref = $data['invoice_ref'] ?? '';

    if (!$request_id || !$quantity_delivered || $quantity_delivered <= 0) {
        throw new Exception('Invalid request or quantity delivered');
    }

    // Get request details
    $stmt = $conn->prepare(
        "SELECT ingredient_id, quantity_requested FROM stock_requests WHERE id = ? AND status = 'pending'"
    );

    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $request_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception('Request not found or already fulfilled');
    }

    $request = $result->fetch_assoc();
    $stmt->close();

    // Update request status
    $stmt = $conn->prepare(
        "UPDATE stock_requests 
        SET status = 'fulfilled', 
            fulfilled_by = ?, 
            quantity_delivered = ?, 
            invoice_ref = ?,
            fulfilled_at = NOW() 
        WHERE id = ?"
    );

    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('sdsi', $user_id, $quantity_delivered, $invoice_ref, $request_id);

    if (!$stmt->execute()) {
        throw new Exception('Failed to fulfill request: ' . $stmt->error);
    }

    $stmt->close();

    // Log activity
    logActivity($user_id, "fulfill_stock_request", "Fulfilled stock request #$request_id");

    echo json_encode([
        'success' => true,
        'message' => 'Request marked as fulfilled successfully'
    ]);
}

/**
 * Get details of a specific request
 */
function handleGetRequestDetails() {
    global $conn;

    $request_id = $_GET['request_id'] ?? null;

    if (!$request_id) {
        throw new Exception('Request ID is required');
    }

    $stmt = $conn->prepare(
        "SELECT 
            sr.id,
            sr.ingredient_id,
            sr.quantity_requested,
            sr.quantity_delivered,
            sr.priority,
            sr.notes,
            sr.status,
            sr.requested_by,
            sr.fulfilled_by,
            sr.invoice_ref,
            sr.created_at,
            sr.fulfilled_at,
            i.name AS ingredient_name,
            i.unit,
            i.current_stock,
            i.minimum_stock
        FROM stock_requests sr
        JOIN ingredients i ON sr.ingredient_id = i.id
        WHERE sr.id = ?"
    );

    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('i', $request_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        throw new Exception('Request not found');
    }

    $request = $result->fetch_assoc();
    $stmt->close();

    echo json_encode([
        'success' => true,
        'request' => $request
    ]);
}

/**
 * Log activity for audit trail
 */
function logActivity($user_id, $action, $description) {
    global $conn;

    $sql = "INSERT INTO activity_logs (user_id, action, description, activity_date) 
            VALUES (?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE activity_date = NOW()";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param('sss', $user_id, $action, $description);
        $stmt->execute();
        $stmt->close();
    }
}
?>
