<?php
/**
 * New Ingredient Request Management API
 * Handles admin requests for new ingredients and PM approval workflow
 */

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
    createNewIngredientRequestsTable();

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

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

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

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

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

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

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

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

    $sql = "CREATE TABLE IF NOT EXISTS ingredient_requests (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(255) NOT NULL,
        description TEXT,
        unit VARCHAR(50) NOT NULL,
        supplier VARCHAR(255),
        quantity_requested DECIMAL(10,2) NOT NULL,
        priority ENUM('low','medium','high') DEFAULT 'medium',
        notes TEXT,
        status ENUM('pending','approved','rejected') DEFAULT 'pending',
        requested_by VARCHAR(50) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        approved_by VARCHAR(50),
        approved_at TIMESTAMP NULL,
        created_ingredient_id INT,
        rejection_reason TEXT,
        rejected_at TIMESTAMP NULL,
        FOREIGN KEY (created_ingredient_id) REFERENCES ingredients(id) ON DELETE SET NULL,
        INDEX idx_status (status),
        INDEX idx_created (created_at),
        INDEX idx_ingredient_name (name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

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

/**
 * Create new ingredient request (Admin initiates)
 */
function handleCreateNewIngredientRequest() {
    global $conn;

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

    // Validate input
    $name = $data['name'] ?? null;
    $description = $data['description'] ?? '';
    $unit = $data['unit'] ?? null;
    $supplier = $data['supplier'] ?? '';
    $quantity_requested = $data['quantity_requested'] ?? null;
    $priority = $data['priority'] ?? 'medium';
    $notes = $data['notes'] ?? '';
    $requested_by = $data['requested_by'] ?? 'admin';

    if (!$name || !$unit || !$quantity_requested || $quantity_requested <= 0) {
        throw new Exception('Missing or invalid required fields (name, unit, quantity)');
    }

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

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

    $stmt->bind_param('s', $name);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        throw new Exception('Ingredient "' . htmlspecialchars($name) . '" already exists in the system');
    }
    $stmt->close();

    // Insert new request
    $stmt = $conn->prepare(
        "INSERT INTO ingredient_requests 
        (name, description, unit, supplier, quantity_requested, priority, notes, requested_by, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')"
    );

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

    $stmt->bind_param('ssssdsss', $name, $description, $unit, $supplier, $quantity_requested, $priority, $notes, $requested_by);

    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_new_ingredient_request", "Requested new ingredient: $name");

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

/**
 * Get pending new ingredient requests (PM views)
 */
function handleGetNewIngredientRequests() {
    global $conn;

    $status = $_GET['status'] ?? 'pending'; // Can filter by pending/approved/rejected
    $valid_statuses = ['pending', 'approved', 'rejected'];
    
    if (!in_array($status, $valid_statuses)) {
        $status = 'pending';
    }

    $sql = "SELECT 
                id,
                name,
                description,
                unit,
                supplier,
                quantity_requested,
                priority,
                notes,
                requested_by,
                created_at,
                status,
                approved_by,
                approved_at,
                created_ingredient_id,
                rejection_reason
            FROM ingredient_requests
            WHERE status = ?
            ORDER BY 
                CASE priority
                    WHEN 'high' THEN 1
                    WHEN 'medium' THEN 2
                    WHEN 'low' THEN 3
                END ASC,
                created_at DESC";

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

    $stmt->bind_param('s', $status);
    $stmt->execute();
    $result = $stmt->get_result();

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

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

/**
 * Approve new ingredient request and create ingredient (PM approves)
 */
function handleApproveRequest() {
    global $conn;

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

    $request_id = $data['request_id'] ?? null;
    $current_stock = $data['current_stock'] ?? 0;
    $minimum_stock = $data['minimum_stock'] ?? 10;
    $unit_cost = $data['unit_cost'] ?? 0;

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

    // Get request details
    $stmt = $conn->prepare(
        "SELECT name, description, unit, supplier, quantity_requested FROM ingredient_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 processed');
    }

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

    // Start transaction
    $conn->begin_transaction();

    try {
        // Create ingredient in ingredients table
        $stmt = $conn->prepare(
            "INSERT INTO ingredients 
            (name, description, unit, supplier, current_stock, minimum_stock, unit_cost, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
        );

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

        $stmt->bind_param('ssssddd', $request['name'], $request['description'], $request['unit'], 
                         $request['supplier'], $current_stock, $minimum_stock, $unit_cost);

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

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

        // Update request with approval details
        $stmt = $conn->prepare(
            "UPDATE ingredient_requests 
            SET status = 'approved', 
                approved_by = ?, 
                approved_at = NOW(),
                created_ingredient_id = ?
            WHERE id = ?"
        );

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

        $stmt->bind_param('sii', $user_id, $ingredient_id, $request_id);

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

        $stmt->close();

        // Commit transaction
        $conn->commit();

        // Log activity
        logActivity($user_id, "approve_new_ingredient", "Approved new ingredient: " . $request['name']);

        echo json_encode([
            'success' => true,
            'message' => 'Ingredient approved and created successfully',
            'ingredient_id' => $ingredient_id,
            'ingredient_name' => $request['name']
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }
}

/**
 * Reject new ingredient request (PM rejects)
 */
function handleRejectRequest() {
    global $conn;

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

    $request_id = $data['request_id'] ?? null;
    $reason = $data['reason'] ?? 'No reason provided';

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

    // Get request details
    $stmt = $conn->prepare(
        "SELECT name FROM ingredient_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 processed');
    }

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

    // Update request rejection
    $stmt = $conn->prepare(
        "UPDATE ingredient_requests 
        SET status = 'rejected', 
            approved_by = ?, 
            rejected_at = NOW(),
            rejection_reason = ?
        WHERE id = ?"
    );

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

    $stmt->bind_param('ssi', $user_id, $reason, $request_id);

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

    $stmt->close();

    // Log activity
    logActivity($user_id, "reject_new_ingredient", "Rejected new ingredient request: " . $request['name']);

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

/**
 * Delete an approved/rejected new ingredient request
 */
function handleDeleteProcessedRequest() {
    global $conn, $user_id;

    $data = json_decode(file_get_contents('php://input'), true);
    $request_id = $data['request_id'] ?? null;

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

    $stmt = $conn->prepare(
        "SELECT id, name, status FROM ingredient_requests 
         WHERE id = ? AND status IN ('approved', 'rejected')"
    );
    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) {
        $stmt->close();
        throw new Exception('Only approved or rejected requests can be deleted');
    }

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

    $delete_stmt = $conn->prepare(
        "DELETE FROM ingredient_requests 
         WHERE id = ? AND status IN ('approved', 'rejected')"
    );
    if (!$delete_stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $delete_stmt->bind_param('i', $request_id);
    if (!$delete_stmt->execute()) {
        throw new Exception('Failed to delete request: ' . $delete_stmt->error);
    }
    $affected = $delete_stmt->affected_rows;
    $delete_stmt->close();

    if ($affected < 1) {
        throw new Exception('Request not found or already deleted');
    }

    logActivity($user_id, "delete_new_ingredient_request", "Deleted {$request['status']} request: " . $request['name']);

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

/**
 * 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();
    }
}
?>
